<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\SalesOrder;
use App\Models\SalesOrderItem;
use App\Models\CustomerVendor;
use Illuminate\Support\Facades\Log;

class SalesController extends Controller
{
    public function salesPage()
    {
        Log::info("admin accessed Sales Order Form");
        return view('admin.sales.salesorder');
    }
    public function print($id)
    {
        $order = SalesOrder::with(['items', 'customer'])->findOrFail($id);
        return view('admin.sales.print', compact('order'));
    } 
    public function salesDetails()
    {
        Log::info("admin accessed Sales Details Page");
        $orders = SalesOrder::with('customer')->get();
        return view('admin.sales.salesdetails', compact('orders'));
    }

    public function show($id)
    {
        $order = SalesOrder::with(['items', 'customer'])->findOrFail($id);
        return view('admin.sales.show', compact('order'));
    }
    public function getSalesOrderById($id)
    {
        $order = SalesOrder::with(['items', 'customer'])->findOrFail($id);
        return response()->json($order);
    }
    // Get all quotations (for dropdown)
    public function getQuotations()
    {
        $quotations = \App\Models\Quotation::with('customer')
            ->whereHas('customer', function ($q) {
                $q->where('company_role', '!=', 'Vendor');
            })
            ->orderBy('id', 'desc')
            ->get(['id', 'quotation_no']);

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

    // Get single quotation details
    public function getQuotationById($id)
    {
        // Eager load customer and rfq
        $quotation = \App\Models\Quotation::with('customer', 'rfq')
            ->whereHas('customer', function ($q) {
                $q->where('company_role', '!=', 'Vendor');
            })
            ->find($id);

        if (!$quotation) {
            return response()->json(['error' => 'Quotation not found or belongs to a Vendor'], 404);
        }

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

    public function getNonVendorQuotations()
    {
        $quotations = \App\Models\Quotation::with('customer')
            ->whereHas('customer', function ($q) {
                $q->where('company_role', '!=', 'Vendor');
            })->get();

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

    public function edit($id)
    {
        $order = SalesOrder::with('items')->findOrFail($id);
        $customers = CustomerVendor::select('id', 'company')->get();
        $editOrderId = $id; // <-- Add this
        return view('admin.sales.edit', compact('order', 'customers', 'editOrderId'));
    }

    public function update(Request $request, $id)
    {
        Log::info("admin: Starting Sales Order Update...");

        try {
            Log::debug("Incoming Request Data:", $request->all());

            $validated = $request->validate([
                'soNo1' => 'required|unique:sales_orders,sales_order_no,' . $id,
                'soDate' => 'required|date',
                'companyName' => 'required|string',
                'grandTotal' => 'required|numeric'
            ]);

            DB::beginTransaction();

            $salesOrder = SalesOrder::findOrFail($id);
            $salesOrder->update([
                'sales_order_no' => $request->input('soNo1'),
                'sales_order_date' => $request->input('soDate'),
                'grn_no' => $request->input('grnNo1') ?? null,
                'customer_ref_no' => $request->input('custRefSoNo') ?? null,
                'company_name' => $request->input('companyName'),
                'company_address' => $request->input('soCompanyAddress'),
                'company_gstn' => $request->input('soCompanyGSTN'),
                'company_phone' => $request->input('soCompanyPhone'),
                'company_email' => $request->input('soCompanyEmail'),
                'quotation_no' => $request->input('quotationNo2') ?? null,
                'quotation_date' => $request->input('quotationDate') ?? null,
                'rfq_no' => $request->input('rfqNo') ?? null,
                'rfq_date' => $request->input('rfqDate') ?? null,
                'part_no' => $request->input('partNo') ?? null,
                'project_material_no' => $request->input('projectMaterialNo') ?? null,
                'drawing_no' => $request->input('drawingId') ?? null,
                'drawing_rev' => $request->input('drawingRevision') ?? null,
                'description' => $request->input('projectDescription') ?? null,
                'bill_address' => $request->input('billAddress') ?? null,
                'ship_address' => $request->input('shipAddress') ?? null,
                'product_type' => $request->input('productType'),
                'inr_in_words' => $request->input('GT_in_letters'),
                'subtotal' => $request->input('totalAmount'),
                'sgst_amount' => $request->input('sgstA'),
                'cgst_amount' => $request->input('cgstA'),
                'igst_amount' => $request->input('IgstA'),
                'round_up' => $request->input('roundUp'),
                'grand_total' => $request->input('grandTotal')
            ]);

            if ($request->hasFile('customerSO')) {
                $path = $request->file('customerSO')->store('customer_sos', 'public');
                $salesOrder->update(['customer_so_path' => $path]);
            }

            $salesOrder->items()->delete();

            $items = $request->input('tableProducts');
            if (!is_array($items)) {
                $items = json_decode($items, true);
            }
            if (!is_array($items)) {
                throw new \Exception("Invalid items format received");
            }
            foreach ($items as $item) {
                SalesOrderItem::create([
                    'sales_order_id' => $salesOrder->id,
                    'sl_no' => $item['slNo'],
                    'material_code' => $item['materialCode'] ?? null,
                    'hsn_code' => $item['hsnCode'] ?? null,
                    'material_description' => $item['description'] ?? null,
                    'additional_details' => $item['additionalDetails'] ?? null,
                    'required_by_date' => $item['reqByDate'] ?? null,
                    'quantity' => $item['quantity'] ?? 0,
                    'uom' => $item['uom'] ?? null,
                    'unit_rate' => $item['unitRate'] ?? 0,
                    'discount' => $item['discount'] ?? 0,
                    'value' => $item['value'] ?? 0,
                    'sgst' => $item['sgst'] ?? 0,
                    'cgst' => $item['cgst'] ?? 0,
                    'igst' => $item['igst'] ?? 0,
                    'amount' => $item['amount'] ?? 0,
                ]);
            }

            DB::commit();

            return response()->json([
                'message' => 'Sales Order updated successfully!',
                'id' => $salesOrder->id
            ], 200);
        } catch (\Illuminate\Validation\ValidationException $e) {
            DB::rollBack();
            return response()->json(['error' => 'Validation failed', 'details' => $e->validator->getMessageBag()], 422);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['error' => 'Server error occurred', 'message' => $e->getMessage()], 500);
        }
    }

    public function destroy($id)
    {
        try {
            $order = SalesOrder::findOrFail($id);
            $order->items()->delete();
            $order->delete();

            return response()->json(['message' => 'Sales Order deleted successfully']);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to delete order'], 500);
        }
    }

    public function getCustomers()
    {
        try {
            $customers = CustomerVendor::select('id', 'company')->get();
            return response()->json($customers);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to load companies'], 500);
        }
    }

    public function getCustomerById($id)
    {
        try {
            $customer = CustomerVendor::find($id);

            if (!$customer) {
                return response()->json(['error' => 'Customer not found'], 404);
            }

            return response()->json([
                'billingAddress' => $customer->billing_Address,
                'gstNo' => $customer->gstno,
                'mobile' => $customer->mobile,
                'email' => $customer->email
            ]);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to fetch customer details'], 500);
        }
    }

    public function generateSOId()
    {
        try {
            $lastSo = SalesOrder::orderByDesc('id')->first();

            if ($lastSo && isset($lastSo->sales_order_no)) {
                $lastId = intval(preg_replace('/[^0-9]/', '', substr($lastSo->sales_order_no, -4)));
            } else {
                $lastId = 0;
            }

            $newId = str_pad($lastId + 1, 4, '0', STR_PAD_LEFT);
            $soId = "UEPL/SO/{$newId}";

            return response()->json(['so_id' => $soId]);
        } catch (\Exception $e) {
            return response()->json(['so_id' => 'UEPL/SO/0001']);
        }
    }

    public function generateGRNId()
    {
        try {
            $lastGrn = SalesOrder::orderByDesc('id')->first();

            if ($lastGrn && isset($lastGrn->grn_no)) {
                $lastId = intval(preg_replace('/[^0-9]/', '', substr($lastGrn->grn_no, -4)));
            } else {
                $lastId = 0;
            }

            $newId = str_pad($lastId + 1, 4, '0', STR_PAD_LEFT);
            $grnId = "UEPL/GRN/{$newId}";

            return response()->json(['grn_id' => $grnId]);
        } catch (\Exception $e) {
            return response()->json(['grn_id' => 'UEPL/GRN/0001']);
        }
    }

    public function store(Request $request)
    {
        Log::info('[SalesOrder] Store called');

        try {
            Log::info('[SalesOrder] Incoming request data:', $request->all());

            $validated = $request->validate([
                'soNo1' => 'required|unique:sales_orders,sales_order_no',
                'soDate' => 'required|date',
                'companyName' => 'required|string',
                'grandTotal' => 'required|numeric'
            ]);
            Log::info('[SalesOrder] Validation passed', $validated);

            DB::beginTransaction();

            Log::info('[SalesOrder] Creating SalesOrder record');
            $salesOrder = SalesOrder::create([
                'sales_order_no' => $request->input('soNo1'),
                'sales_order_date' => $request->input('soDate'),
                'grn_no' => $request->input('grnNo1') ?? null,
                'customer_ref_no' => $request->input('custRefSoNo') ?? null,
                'company_name' => $request->input('companyName'),
                'company_address' => $request->input('soCompanyAddress'),
                'company_gstn' => $request->input('soCompanyGSTN'),
                'company_phone' => $request->input('soCompanyPhone'),
                'company_email' => $request->input('soCompanyEmail'),
                'quotation_no' => $request->input('quotationNo2') ?? null,
                'quotation_date' => $request->input('quotationDate') ?? null,
                'rfq_no' => $request->input('rfqNo') ?? null,
                'rfq_date' => $request->input('rfqDate') ?? null,
                'part_no' => $request->input('partNo') ?? null,
                'project_material_no' => $request->input('projectMaterialNo') ?? null,
                'drawing_no' => $request->input('drawingId') ?? null,
                'drawing_rev' => $request->input('drawingRevision') ?? null,
                'description' => $request->input('projectDescription') ?? null,
                'bill_address' => $request->input('billAddress') ?? null,
                'ship_address' => $request->input('shipAddress') ?? null,
                'product_type' => $request->input('productType'),
                'inr_in_words' => $request->input('GT_in_letters'),
                'subtotal' => $request->input('totalAmount'),
                'sgst_amount' => $request->input('sgstA'),
                'cgst_amount' => $request->input('cgstA'),
                'igst_amount' => $request->input('IgstA'),
                'round_up' => $request->input('roundUp'),
                'grand_total' => $request->input('grandTotal')
            ]);
            Log::info('[SalesOrder] SalesOrder created', ['id' => $salesOrder->id]);

            $items = $request->input('tableProducts');
            Log::info('[SalesOrder] tableProducts received:', ['tableProducts' => $items]);
            if (!is_array($items)) {
                throw new \Exception("Invalid items format received");
            }

            foreach ($items as $item) {
                SalesOrderItem::create([
                    'sales_order_id' => $salesOrder->id,
                    'sl_no' => $item['slNo'] ?? null,
                    'material_code' => $item['materialCode'] ?? null,
                    'hsn_code' => $item['hsnCode'] ?? null,
                    'material_description' => $item['description'] ?? null,
                    'additional_details' => $item['additionalDetails'] ?? null,
                    'required_by_date' => $item['reqByDate'] ?? null,
                    'quantity' => $item['quantity'] ?? 0,
                    'uom' => $item['uom'] ?? null,
                    'unit_rate' => $item['unitRate'] ?? 0,
                    'discount' => $item['discount'] ?? 0,
                    'value' => $item['value'] ?? 0,
                    'sgst' => $item['sgst'] ?? 0,
                    'cgst' => $item['cgst'] ?? 0,
                    'igst' => $item['igst'] ?? 0,
                    'amount' => $item['amount'] ?? 0,
                ]);
            }
            Log::info('[SalesOrder] SalesOrderItems created');

            DB::commit();

            Log::info('[SalesOrder] Sales order saved successfully', ['id' => $salesOrder->id]);
            return response()->json([
                'message' => 'Sales Order saved successfully!',
                'id' => $salesOrder->id
            ], 201);
        } catch (\Illuminate\Validation\ValidationException $e) {
            DB::rollBack();
            Log::error('[SalesOrder] Validation failed', [
                'errors' => $e->validator->getMessageBag(),
                'trace' => $e->getTraceAsString(),
            ]);
            return response()->json(['error' => 'Validation failed', 'details' => $e->validator->getMessageBag()], 422);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('[SalesOrder] Exception occurred', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request_data' => $request->all()
            ]);
            return response()->json(['error' => 'Server error occurred', 'message' => $e->getMessage()], 500);
        }
    }
}
