<?php

namespace App\Http\Controllers;

use Exception;
use Illuminate\Http\Request;
use App\Models\SupplierCategory;
use App\Models\SupplierArea;
use App\Models\SupAgeing;
use Illuminate\Support\Facades\Validator;

class SupplierCategoryController extends Controller
{
    // ===== Supplier Category Methods =====

    // Show form and list of supplier categories
    public function create_supplier_category()
    {
        $categories = SupplierCategory::all();
        return view('maintanance.suppliers.create_supplier_category', compact('categories'));
    }

    // Store new supplier category
    public function store_supplier_category(Request $request)
    {
        try {
            $request->validate([
                'code' => 'required|string|max:255|unique:supplier_categories,code',
                'name' => 'required|string|max:255',
                'description' => 'required|string|max:255',
            ], [
                'code.unique' => 'The code you entered already exists. Please use a different code.',
            ]);

            $category = new SupplierCategory();
            $category->code = $request->code;
            $category->name = $request->name;
            $category->description = $request->description;
            $category->save();

            return redirect()->route('supplier.categories.create')->with('success', 'Category created successfully.');
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    // Edit supplier category
    public function edit_supplier_category(Request $request)
    {
        try {
            $request->validate([
                'id' => 'required|integer|exists:supplier_categories,id',
                'code' => 'required|string|max:255',
                'name' => 'required|string|max:255',
                'description' => 'required|string|max:255',
            ]);

            $result = SupplierCategory::editCategory(
                $request->id,
                $request->code,
                $request->name,
                $request->description
            );

            if ($result) {
                return redirect()->route('supplier.categories.create')->with('success', 'Category updated successfully.');
            }

            return redirect()->route('supplier.categories.create')->withErrors(['error' => 'Update failed.']);
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    // Delete supplier category
    public function delete_supplier_category($id)
    {
        try {
            $result = SupplierCategory::deleteCategory($id);

            if ($result) {
                return redirect()->route('supplier.categories.create')->with('success', 'Category deleted successfully.');
            }

            return redirect()->route('supplier.categories.create')->withErrors(['error' => 'Delete failed.']);
        } catch (Exception $e) {
            return redirect()->route('supplier.categories.create')->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    // ===== Supplier Area Methods =====

    // Show form and list of supplier areas
    public function create_area()
    {
        $areas = SupplierArea::all();
        return view('maintanance.suppliers.create_area_', compact('areas'));
    }

    // Store new supplier area
    public function store_area(Request $request)
    {
        try {
            $request->validate([
                'code' => 'required|string|max:255|unique:supplier_areas,code',
                'name' => 'required|string|max:255',
                'country' => 'required|string|max:255',
                'city' => 'required|string|max:255',
                'specific_location' => 'nullable|string|max:255',
            ], [
                'code.unique' => 'The code you entered already exists. Please use a different code.',
            ]);

            $area = new SupplierArea();
            $area->code = $request->code;
            $area->name = $request->name;
            $area->country = $request->country;
            $area->city = $request->city;
            $area->specific_location = $request->specific_location;
            $area->save();

            return redirect()->route('supplier.areas.create')->with('success', 'Area created successfully.');
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    // Edit supplier area
    public function edit_area(Request $request)
    {
        try {
            $request->validate([
                'id' => 'required|integer|exists:supplier_areas,id',
                'code' => 'required|string|max:255',
                'name' => 'required|string|max:255',
                'country' => 'required|string|max:255',
                'city' => 'required|string|max:255',
                'specific_location' => 'nullable|string|max:255',
            ]);

            $area = SupplierArea::findOrFail($request->id);
            $area->code = $request->code;
            $area->name = $request->name;
            $area->country = $request->country;
            $area->city = $request->city;
            $area->specific_location = $request->specific_location;
            $area->save();

            return redirect()->route('supplier.areas.create')->with('success', 'Area updated successfully.');
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    // Delete supplier area
    public function delete_area($id)
    {
        try {
            $area = SupplierArea::findOrFail($id);
            $area->delete();

            return redirect()->route('supplier.areas.create')->with('success', 'Area deleted successfully.');
        } catch (Exception $e) {
            return redirect()->route('supplier.areas.create')->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }


    // ===== Ageing Methods =====

    // Show the list and form for creating new ageing records
    public function index_ageing()
    {
        $ageings = SupAgeing::all();
        return view('maintanance.customers.create_ageing', compact('ageings'));
    }

    // Store new ageing record (POST)
    public function store_ageing(Request $request)
    {
        $request->validate([
            'age_code' => 'required|string|max:255|unique:ageings,age_code',
            'description' => 'required|string|max:255',
            'group_type' => 'required|string|in:monthly,daily,custom',
            'interval_type' => 'required|string|in:invoice_date,statement_date',
            'interval_30_days' => 'nullable|boolean',
            'interval_7_days' => 'nullable|boolean',
            'interval_custom' => 'nullable|boolean',
            // Add validation for custom_age_1... custom_age_7 and custom_interval_1... custom_interval_6 as needed
        ], [
            'age_code.unique' => 'The code you entered already exists. Please use a different code.',
        ]);

        try {
            $ageing = new SupAgeing();
            $ageing->age_code = $request->age_code;
            $ageing->description = $request->description;
            $ageing->group_type = $request->group_type;
            $ageing->interval_type = $request->interval_type;
            $ageing->interval_30_days = $request->has('interval_30_days');
            $ageing->interval_7_days = $request->has('interval_7_days');
            $ageing->interval_custom = $request->has('interval_custom');

            for ($i = 1; $i <= 7; $i++) {
                $field = 'custom_age_' . $i;
                if ($request->has($field)) {
                    $ageing->$field = $request->$field;
                }
            }
            for ($i = 1; $i <= 6; $i++) {
                $field = 'custom_interval_' . $i;
                if ($request->has($field)) {
                    $ageing->$field = $request->$field;
                }
            }

            $ageing->save();

            return redirect()->route('ageing.index')->with('success', 'Ageing record created successfully.');
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()])->withInput();
        }
    }

    // Update ageing record (PUT)
    public function update_ageing(Request $request, $id)
    {
        $request->validate([
            'age_code' => 'required|string|max:255|unique:ageings,age_code,' . $id,
            'description' => 'required|string|max:255',
            'group_type' => 'required|string|in:monthly,daily,custom',
            'interval_type' => 'required|string|in:invoice_date,statement_date',
            'interval_30_days' => 'nullable|boolean',
            'interval_7_days' => 'nullable|boolean',
            'interval_custom' => 'nullable|boolean',
            // Add validation for custom_age_1... custom_age_7 and custom_interval_1... custom_interval_6 as needed
        ]);

        try {
            $ageing = SupAgeing::findOrFail($id);

            $ageing->age_code = $request->age_code;
            $ageing->description = $request->description;
            $ageing->group_type = $request->group_type;
            $ageing->interval_type = $request->interval_type;
            $ageing->interval_30_days = $request->has('interval_30_days');
            $ageing->interval_7_days = $request->has('interval_7_days');
            $ageing->interval_custom = $request->has('interval_custom');

            for ($i = 1; $i <= 7; $i++) {
                $field = 'custom_age_' . $i;
                if ($request->has($field)) {
                    $ageing->$field = $request->$field;
                }
            }
            for ($i = 1; $i <= 6; $i++) {
                $field = 'custom_interval_' . $i;
                if ($request->has($field)) {
                    $ageing->$field = $request->$field;
                }
            }

            $ageing->save();

            return redirect()->route('ageing.index')->with('success', 'Ageing record updated successfully.');
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()])->withInput();
        }
    }

    // Delete ageing record (DELETE)
    public function delete_ageing($id)
    {
        try {
            $ageing = SupAgeing::findOrFail($id);
            $ageing->delete();

            return redirect()->route('ageing.index')->with('success', 'Ageing record deleted successfully.');
        } catch (Exception $e) {
            return redirect()->route('ageing.index')->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }
}
