<?php

namespace Modules\SystemCore\App\Http\Controllers;

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

class SalesOrderController extends Controller
{
    public function index()
    {
        return view('systemcore::sales-orders.index');
    }

    public function indexAjax(Request $request)
    {
        $query = CoreSalesOrder::with(['customer', 'user'])
            ->select('core_sales_orders.*');

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

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

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

        return datatables($query)
            ->addColumn('customer_name', function ($order) {
                return $order->customer ? $order->customer->name : '-';
            })
            ->addColumn('actions', function ($order) {
                return view('components.datatable-actions', [
                    'id' => $order->id,
                    'actions' => [
                        ['label' => __('View'), 'icon' => 'bx bx-show', 'url' => route('systemcore.sales-orders.show', $order->id)],
                        ['label' => __('Edit'), 'icon' => 'bx bx-edit', 'url' => route('systemcore.sales-orders.edit', $order->id)],
                        ['label' => __('Delete'), 'icon' => 'bx bx-trash', 'onclick' => "deleteSalesOrder({$order->id})"],
                    ],
                ])->render();
            })
            ->editColumn('order_date', fn ($order) => $order->order_date?->format('Y-m-d'))
            ->editColumn('delivery_date', fn ($order) => $order->delivery_date?->format('Y-m-d'))
            ->editColumn('total_amount', fn ($order) => number_format($order->total_amount, 2))
            ->editColumn('status', fn ($order) => "<span class='badge bg-{$order->status->color()}'>{$order->status->label()}</span>")
            ->editColumn('payment_status', function ($order) {
                $colors = [
                    'pending' => 'warning',
                    'partial' => 'info',
                    'paid' => 'success',
                    'overdue' => 'danger',
                ];
                $color = $colors[$order->payment_status] ?? 'secondary';

                return "<span class='badge bg-{$color}'>".ucfirst($order->payment_status).'</span>';
            })
            ->rawColumns(['status', 'payment_status', 'actions'])
            ->make(true);
    }

    public function create()
    {
        $customers = CoreCustomer::where('status', 'active')
            ->orderBy('name')
            ->get(['id', 'customer_code', 'name']);

        $paymentTerms = \Modules\SystemCore\App\Models\CorePaymentTerm::active()
            ->orderBy('name')
            ->get(['id', 'name', 'days']);

        $taxConfigurations = \Modules\SystemCore\App\Models\CoreTaxConfiguration::active()
            ->orderBy('name')
            ->get(['id', 'name', 'rate']);

        return view('systemcore::sales-orders.create', compact('customers', 'paymentTerms', 'taxConfigurations'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'customer_id' => 'required|exists:core_customers,id',
            'payment_term_id' => 'nullable|exists:core_payment_terms,id',
            'order_date' => 'required|date',
            'delivery_date' => 'nullable|date|after_or_equal:order_date',
            'status' => 'required|string',
            'payment_status' => 'nullable|string',
            'payment_method' => 'nullable|string',
            'notes' => 'nullable|string',
            'subtotal' => 'nullable|numeric|min:0',
            'tax_amount' => 'nullable|numeric|min:0',
            'discount_amount' => 'nullable|numeric|min:0',
            'shipping_cost' => 'nullable|numeric|min:0',
            'total_amount' => 'nullable|numeric|min:0',
            'line_items' => 'nullable|array',
            'line_items.*.product_id' => 'required|exists:core_products,id',
            'line_items.*.tax_id' => 'nullable|exists:core_tax_configurations,id',
            'line_items.*.product_name' => 'nullable|string',
            'line_items.*.product_sku' => 'nullable|string',
            'line_items.*.quantity' => 'required|numeric|min:0.01',
            'line_items.*.unit_price' => 'required|numeric|min:0',
            'line_items.*.tax_rate' => 'nullable|numeric|min:0|max:100',
            'line_items.*.discount_amount' => 'nullable|numeric|min:0',
            'line_items.*.line_total' => 'required|numeric',
        ]);

        // Set default payment status if not provided
        if (! isset($validated['payment_status'])) {
            $validated['payment_status'] = 'pending';
        }

        // Set user_id to current user
        $validated['user_id'] = auth()->id();

        // Create the sales order
        $salesOrder = CoreSalesOrder::create($validated);

        // Create line items if provided
        if (! empty($validated['line_items'])) {
            foreach ($validated['line_items'] as $lineItem) {
                $salesOrder->orderLines()->create([
                    'product_id' => $lineItem['product_id'],
                    'product_variant_id' => null,
                    'tax_id' => $lineItem['tax_id'] ?? null,
                    'tax_rate' => $lineItem['tax_rate'] ?? null,
                    'product_name' => $lineItem['product_name'] ?? '',
                    'product_sku' => $lineItem['product_sku'] ?? '',
                    'quantity' => $lineItem['quantity'],
                    'unit_price' => $lineItem['unit_price'],
                    'tax_amount' => isset($lineItem['tax_rate']) ? ($lineItem['quantity'] * $lineItem['unit_price'] * $lineItem['tax_rate'] / 100) : 0,
                    'discount_amount' => $lineItem['discount_amount'] ?? 0,
                    'line_total' => $lineItem['line_total'],
                ]);
            }
        }

        // Dispatch event for accounting sync if payment status is paid or partial
        if (in_array($salesOrder->payment_status, ['paid', 'partial'])) {
            event(new \Modules\SystemCore\App\Events\SalesOrderPaymentStatusChanged(
                $salesOrder,
                'pending', // old status (default)
                $salesOrder->payment_status // new status
            ));
        }

        return redirect()->route('systemcore.sales-orders.index')
            ->with('success', __('Sales order created successfully'));
    }

    public function show(CoreSalesOrder $salesOrder)
    {
        $salesOrder->load([
            'customer',
            'user',
            'orderLines' => function ($query) {
                $query->with(['product', 'productVariant']);
            },
        ]);

        return view('systemcore::sales-orders.show', compact('salesOrder'));
    }

    public function edit(CoreSalesOrder $salesOrder)
    {
        $customers = CoreCustomer::where('status', 'active')
            ->orderBy('name')
            ->get(['id', 'customer_code', 'name']);

        return view('systemcore::sales-orders.edit', compact('salesOrder', 'customers'));
    }

    public function update(Request $request, CoreSalesOrder $salesOrder)
    {
        $validated = $request->validate([
            'customer_id' => 'required|exists:core_customers,id',
            'order_date' => 'required|date',
            'delivery_date' => 'nullable|date|after_or_equal:order_date',
            'status' => 'required|string',
            'payment_status' => 'required|string',
            'notes' => 'nullable|string',
        ]);

        $salesOrder->update($validated);

        return redirect()->route('systemcore.sales-orders.index')
            ->with('success', __('Sales order updated successfully'));
    }

    public function destroy(CoreSalesOrder $salesOrder)
    {
        $salesOrder->delete();

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