<?php

namespace Modules\SystemCore\App\Http\Controllers;

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

class PaymentTermController extends Controller
{
    public function index()
    {
        return view('systemcore::payment-terms.index');
    }

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

        // 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 ($term) {
                return view('components.datatable-actions', [
                    'id' => $term->id,
                    'actions' => [
                        ['label' => __('Edit'), 'icon' => 'bx bx-edit', 'url' => route('systemcore.payment-terms.edit', $term->id)],
                        ['label' => __('Delete'), 'icon' => 'bx bx-trash', 'onclick' => "deletePaymentTerm({$term->id})"],
                    ],
                ])->render();
            })
            ->editColumn('is_active', fn ($term) => $term->is_active ? '<span class="badge bg-success">'.__('Active').'</span>' : '<span class="badge bg-secondary">'.__('Inactive').'</span>')
            ->editColumn('description', fn ($term) => $term->description ?? '-')
            ->rawColumns(['is_active', 'actions'])
            ->make(true);
    }

    public function create()
    {
        return view('systemcore::payment-terms.create');
    }

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

        CorePaymentTerm::create($validated);

        return redirect()->route('systemcore.payment-terms.index')
            ->with('success', __('Payment term created successfully'));
    }

    public function edit(CorePaymentTerm $paymentTerm)
    {
        return view('systemcore::payment-terms.edit', compact('paymentTerm'));
    }

    public function update(Request $request, CorePaymentTerm $paymentTerm)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:core_payment_terms,code,'.$paymentTerm->id,
            'days' => 'required|integer|min:0',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        $paymentTerm->update($validated);

        return redirect()->route('systemcore.payment-terms.index')
            ->with('success', __('Payment term updated successfully'));
    }

    public function destroy(CorePaymentTerm $paymentTerm)
    {
        // Check if payment term is being used
        $customersCount = $paymentTerm->customers()->count();
        $suppliersCount = $paymentTerm->suppliers()->count();

        if ($customersCount > 0 || $suppliersCount > 0) {
            return response()->json([
                'success' => false,
                'message' => __('Cannot delete payment term. It is being used by :customers customer(s) and :suppliers supplier(s).', [
                    'customers' => $customersCount,
                    'suppliers' => $suppliersCount,
                ]),
            ], 422);
        }

        $paymentTerm->delete();

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

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

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

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