<?php

namespace App\Http\Controllers\SuperAdmin;

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

class SuperAdminInvoiceController extends Controller
{
    public function invoicePage()
    {
        $companies = CustomerVendor::all();
        $sales_orders = \App\Models\SalesOrder::with('items')
            ->where('status', 'approved')
            ->whereNotIn('sales_order_no', function ($query) {
                $query->select('buyer_order_no')
                    ->from('tax_invoices')
                    ->whereNotNull('buyer_order_no');
            })
            ->orderBy('id')
            ->get();
        return view('superadmin.invoice.invoiceorder', compact('companies','sales_orders'));
    }

    private function generateInvoiceId()
    {
        $lastInvoice = TaxInvoice::orderBy('id', 'desc')->first();
        if ($lastInvoice && preg_match('/UEPL\/P\/INV\/(\d+)/', $lastInvoice->invoice_no, $matches)) {
            $lastNumber = (int)$matches[1];
            $newNumber = str_pad($lastNumber + 1, 4, '0', STR_PAD_LEFT);
        } else {
            $newNumber = '0001';
        }
        return "UEPL/P/INV/{$newNumber}";
    }

    public function generateInvoiceIdAjax()
    {
        $invoiceNo = $this->generateInvoiceId();
        return response()->json(['invoice_no' => $invoiceNo]);
    }

    public function store(Request $request)
    {
        Log::info('SuperAdmin Invoice received: ' . json_encode($request->all()));

        $items = [];
        $count = count($request->description ?? []);
        for ($i = 0; $i < $count; $i++) {
            $items[] = [
                'description' => $request->description[$i],
                'hsn' => $request->hsn[$i],
                'quantity' => $request->quantity[$i],
                'rate' => $request->rate[$i],
                'per' => $request->per[$i],
                'sgst' => $request->sgst[$i] ?? 0,
                'cgst' => $request->cgst[$i] ?? 0,
                'igst' => $request->igst[$i] ?? 0,
                'amount' => $request->amount[$i],
            ];
        }

        $validated = $request->validate([
            'invoice_no' => 'required|unique:tax_invoices',
            'invoice_date' => 'required|date',
        ]);

        DB::transaction(function () use ($request, $items) {
            $invoice = TaxInvoice::create([
                'invoice_no' => $request->invoice_no,
                'invoice_date' => $request->invoice_date,
                'delivery_note' => $request->delivery_note,
                'terms_payment' => $request->terms_payment,
                'reference_no' => $request->reference_no,
                'other_reference' => $request->other_reference,
                'company_id' => $request->company,
                'address' => $request->address,
                'gst' => $request->gst,
                'phone' => $request->phone,
                'email' => $request->email,
                'buyer_order_no' => $request->buyer_order_no,
                'reference_date' => $request->reference_date,
                'dispatch_through' => $request->dispatch_through,
                'destination' => $request->destination,
                'vehicle_no' => $request->vehicle_no,
                'terms_of_delivery' => $request->terms_of_delivery,
                'taxable_value' => $request->taxable_value,
                'sgst' => $request->sgst ?? 0,
                'cgst' => $request->cgst ?? 0,
                'igst' => $request->igst ?? 0,
                'total_tax_amount' => $request->total_tax_amount,
                'total_amount' => $request->total_amount,
                'amount_in_words' => $request->amount_in_words,
            ]);
            foreach ($items as $item) {
                $invoice->items()->create($item);
            }
        });

        return redirect()->route('superadmin.invoice.invoiceorder')->with('success', 'Invoice and items stored successfully.');
    }

    public function invoiceDetails()
    {
        $invoices = TaxInvoice::with('company')->get();
        return view('superadmin.invoice.invoicedetails', compact('invoices'));
    }
    public function print($id)
    {
        $invoice = TaxInvoice::with(['company', 'items'])->findOrFail($id);
        return view('superadmin.invoice.print', compact('invoice'));
    }
    public function edit($id)
    {
        $invoice = TaxInvoice::with(['company', 'items'])->findOrFail($id);
        $companies = CustomerVendor::all();
        $sales_orders = \App\Models\SalesOrder::where('status', 'approved')
            ->where(function($query) use ($invoice) {
                $query->whereNotIn('sales_order_no', function ($q) use ($invoice) {
                    $q->select('buyer_order_no')
                        ->from('tax_invoices')
                        ->whereNotNull('buyer_order_no')
                        ->where('id', '!=', $invoice->id);
                })
                ->orWhere('sales_order_no', $invoice->buyer_order_no);
            })
            ->orderBy('id')
            ->get();
        return view('superadmin.invoice.edit', compact('invoice', 'companies', 'sales_orders'));
    }

    public function update(Request $request, $id)
    {
        Log::info('SuperAdmin Invoice update received: ' . json_encode($request->all()));

        $invoice = TaxInvoice::findOrFail($id);

        $items = [];
        $count = count($request->description ?? []);
        for ($i = 0; $i < $count; $i++) {
            $items[] = [
                'description' => $request->description[$i],
                'hsn' => $request->hsn[$i],
                'quantity' => $request->quantity[$i],
                'rate' => $request->rate[$i],
                'per' => $request->per[$i],
                'sgst' => $request->sgst[$i] ?? 0,
                'cgst' => $request->cgst[$i] ?? 0,
                'igst' => $request->igst[$i] ?? 0,
                'amount' => $request->amount[$i],
            ];
        }

        $validated = $request->validate([
            'invoice_date' => 'required|date',
        ]);

        DB::transaction(function () use ($request, $items, $invoice) {
            $invoice->update([
                'invoice_date' => $request->invoice_date,
                'delivery_note' => $request->delivery_note,
                'terms_payment' => $request->terms_payment,
                'reference_no' => $request->reference_no,
                'other_reference' => $request->other_reference,
                'company_id' => $request->company,
                'address' => $request->address,
                'gst' => $request->gst,
                'phone' => $request->phone,
                'email' => $request->email,
                'buyer_order_no' => $request->buyer_order_no,
                'reference_date' => $request->reference_date,
                'dispatch_through' => $request->dispatch_through,
                'destination' => $request->destination,
                'vehicle_no' => $request->vehicle_no,
                'terms_of_delivery' => $request->terms_of_delivery,
                'taxable_value' => $request->taxable_value,
                'sgst' => $request->sgst ?? 0,
                'cgst' => $request->cgst ?? 0,
                'igst' => $request->igst ?? 0,
                'total_tax_amount' => $request->total_tax_amount,
                'total_amount' => $request->total_amount,
                'amount_in_words' => $request->amount_in_words,
            ]);

            // Delete existing items and re-create
            $invoice->items()->delete();
            foreach ($items as $item) {
                $invoice->items()->create($item);
            }
        });

        return redirect()->route('superadmin.invoice.invoicedetails')->with('success', 'Invoice updated successfully.');
    }

    public function destroy($id)
    {
        try {
            $invoice = TaxInvoice::findOrFail($id);

            DB::transaction(function () use ($invoice) {
                // Delete related items first
                $invoice->items()->delete();
                // Delete the invoice
                $invoice->delete();
            });

            return response()->json(['success' => true, 'message' => 'Invoice deleted successfully.']);
        } catch (\Exception $e) {
            Log::error('Invoice deletion failed: ' . $e->getMessage());
            return response()->json(['success' => false, 'message' => 'Failed to delete invoice.'], 500);
        }
    }
}
