<?php

namespace Modules\SystemCore\App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\SystemCore\App\Models\CoreTaxConfiguration;

class TaxConfigurationController extends Controller
{
    public function index()
    {
        return view('systemcore::tax-configurations.index');
    }

    public function indexAjax(Request $request)
    {
        $query = CoreTaxConfiguration::select('core_tax_configurations.*');

        // Search
        if ($request->filled('search.value')) {
            $search = $request->input('search.value');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('code', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%");
            });
        }

        // Filter by active status
        if ($request->filled('is_active')) {
            $query->where('is_active', $request->is_active);
        }

        return datatables($query)
            ->addColumn('actions', function ($tax) {
                return view('components.datatable-actions', [
                    'id' => $tax->id,
                    'actions' => [
                        ['label' => __('Edit'), 'icon' => 'bx bx-edit', 'url' => route('systemcore.tax-configurations.edit', $tax->id)],
                        ['label' => __('Delete'), 'icon' => 'bx bx-trash', 'onclick' => "deleteTaxConfiguration({$tax->id})"],
                    ],
                ])->render();
            })
            ->editColumn('rate', fn ($tax) => number_format($tax->rate, 2).'%')
            ->editColumn('is_active', fn ($tax) => $tax->is_active ? '<span class="badge bg-success">'.__('Active').'</span>' : '<span class="badge bg-secondary">'.__('Inactive').'</span>')
            ->editColumn('description', fn ($tax) => $tax->description ?? '-')
            ->rawColumns(['is_active', 'actions'])
            ->make(true);
    }

    public function create()
    {
        return view('systemcore::tax-configurations.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:core_tax_configurations,code',
            'rate' => 'required|numeric|min:0|max:100',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        CoreTaxConfiguration::create($validated);

        return redirect()->route('systemcore.tax-configurations.index')
            ->with('success', __('Tax configuration created successfully'));
    }

    public function edit(CoreTaxConfiguration $taxConfiguration)
    {
        return view('systemcore::tax-configurations.edit', compact('taxConfiguration'));
    }

    public function update(Request $request, CoreTaxConfiguration $taxConfiguration)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:core_tax_configurations,code,'.$taxConfiguration->id,
            'rate' => 'required|numeric|min:0|max:100',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        $taxConfiguration->update($validated);

        return redirect()->route('systemcore.tax-configurations.index')
            ->with('success', __('Tax configuration updated successfully'));
    }

    public function destroy(CoreTaxConfiguration $taxConfiguration)
    {
        // Check if tax configuration is being used
        $productsCount = $taxConfiguration->products()->count();

        if ($productsCount > 0) {
            return response()->json([
                'success' => false,
                'message' => __('Cannot delete tax configuration. It is being used by :count product(s).', [
                    'count' => $productsCount,
                ]),
            ], 422);
        }

        $taxConfiguration->delete();

        return response()->json([
            'success' => true,
            'message' => __('Tax configuration deleted successfully'),
        ]);
    }

    public function search(Request $request)
    {
        $search = $request->get('search', '');

        $taxes = CoreTaxConfiguration::where('name', 'like', "%{$search}%")
            ->orWhere('code', 'like', "%{$search}%")
            ->limit(20)
            ->get(['id', 'code', 'name', 'rate']);

        return response()->json($taxes);
    }
}
