<?php

namespace Modules\SystemCore\App\Http\Controllers;

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

class SupplierController extends Controller
{
    public function index()
    {
        return view('systemcore::suppliers.index');
    }

    public function indexAjax(Request $request)
    {
        $query = CoreSupplier::with(['paymentTerm'])
            ->select('core_suppliers.*');

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

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

        return datatables($query)
            ->addColumn('actions', function ($supplier) {
                return view('components.datatable-actions', [
                    'id' => $supplier->id,
                    'actions' => [
                        ['label' => __('View'), 'icon' => 'bx bx-show', 'url' => route('systemcore.suppliers.show', $supplier->id)],
                        ['label' => __('Edit'), 'icon' => 'bx bx-edit', 'url' => route('systemcore.suppliers.edit', $supplier->id)],
                        ['label' => __('Delete'), 'icon' => 'bx bx-trash', 'onclick' => "deleteSupplier({$supplier->id})"],
                    ],
                ])->render();
            })
            ->editColumn('status', fn ($supplier) => "<span class='badge bg-{$supplier->status->color()}'>{$supplier->status->label()}</span>")
            ->editColumn('is_active', fn ($supplier) => $supplier->is_active ? '<span class="badge bg-success">'.__('Active').'</span>' : '<span class="badge bg-secondary">'.__('Inactive').'</span>')
            ->rawColumns(['status', 'is_active', 'actions'])
            ->make(true);
    }

    public function create()
    {
        return view('systemcore::suppliers.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'company_name' => 'nullable|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone_number' => 'nullable|string|max:50',
            'mobile' => 'nullable|string|max:50',
            'website' => 'nullable|url|max:255',
            'tax_id' => 'nullable|string|max:100',
            'vat_number' => 'nullable|string|max:100',
            'payment_term_id' => 'nullable|exists:core_payment_terms,id',
            'credit_limit' => 'nullable|numeric|min:0',
            'notes' => 'nullable|string',
        ]);

        $supplier = CoreSupplier::create($validated);

        return redirect()->route('systemcore.suppliers.index')
            ->with('success', __('Supplier created successfully'));
    }

    public function show(CoreSupplier $supplier)
    {
        $supplier->load([
            'paymentTerm',
            'addresses',
            'contacts',
            'documents',
            'purchaseOrders' => function ($query) {
                $query->orderBy('order_date', 'desc')->limit(10);
            },
        ]);

        // Calculate statistics
        $stats = [
            'total_orders' => $supplier->purchaseOrders()->count(),
            'total_spent' => $supplier->purchaseOrders()->sum('total_amount'),
            'pending_orders' => $supplier->purchaseOrders()->where('status', 'pending')->count(),
            'completed_orders' => $supplier->purchaseOrders()->where('status', 'completed')->count(),
            'addresses_count' => $supplier->addresses()->count(),
            'contacts_count' => $supplier->contacts()->count(),
            'documents_count' => $supplier->documents()->count(),
        ];

        return view('systemcore::suppliers.show', compact('supplier', 'stats'));
    }

    public function edit(CoreSupplier $supplier)
    {
        return view('systemcore::suppliers.edit', compact('supplier'));
    }

    public function update(Request $request, CoreSupplier $supplier)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'company_name' => 'nullable|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone_number' => 'nullable|string|max:50',
            'mobile' => 'nullable|string|max:50',
            'website' => 'nullable|url|max:255',
            'tax_id' => 'nullable|string|max:100',
            'vat_number' => 'nullable|string|max:100',
            'payment_term_id' => 'nullable|exists:core_payment_terms,id',
            'credit_limit' => 'nullable|numeric|min:0',
            'status' => 'required|string',
            'notes' => 'nullable|string',
        ]);

        $supplier->update($validated);

        return redirect()->route('systemcore.suppliers.index')
            ->with('success', __('Supplier updated successfully'));
    }

    public function destroy(CoreSupplier $supplier)
    {
        $supplier->delete();

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

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

        $suppliers = CoreSupplier::where('name', 'like', "%{$search}%")
            ->orWhere('email', 'like', "%{$search}%")
            ->orWhere('supplier_code', 'like', "%{$search}%")
            ->limit(20)
            ->get(['id', 'supplier_code', 'name', 'email', 'phone_number']);

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