<?php

namespace App\Http\Controllers\Gerai;

use App\Models\invoice\Invoice;
use App\Models\invoice\Deposit;
use App\Models\gerai\GeraiInvoice;
use App\Models\gerai\GeraiItem;
use App\Models\gerai\GeraiArPayment;
use App\Models\gerai\GeraiDeposit;
use App\Http\Controllers\GetAPIController;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use App\Helpers\ActivityLogger;

class GeraiController extends Controller
{
    private $itemMapper;
    private $stockItemMethod;
    private $stallMethod;
    private $transporterMethod;
    private $paymentMethod;

    public function __construct()
    {
        $this->middleware('permission:invoice-view', ['only' => ['index', 'show']]);
        $this->middleware('permission:invoice-add', ['only' => ['create', 'store']]);
        $this->middleware('permission:invoice-edit', ['only' => ['edit', 'update']]);
        $this->middleware('permission:invoice-delete', ['only' => ['destroy']]);
        
        $this->itemMapper = Config::get('itemMapper');
        $this->transporterMethod = (new GetAPIController())->getTransporterMethod();
        $this->stallMethod = (new GetAPIController())->getStallMethod();
        $this->stockItemMethod = (new GetAPIController())->getStockItem();
        $this->paymentMethod = (new GetAPIController())->getPaymentMethod();
    }

    public function index(Request $request)
    {
        Session::flash('backUrl', $request->fullUrl());
        return view('gerai.index');
    }

    public function create(): View
    {
        if (Session::has('backUrl')) {
            Session::keep('backUrl');
        }
        
        $transporterMethod = $this->transporterMethod;
        $stallMethod = $this->stallMethod;
        $stockItemMethod = $this->stockItemMethod;
        $paymentMethod = $this->paymentMethod;
        
        return view('gerai.create', compact('transporterMethod', 'stallMethod', 'stockItemMethod', 'paymentMethod'));
    }

    /**
     * Validate input
     */
    private function validateInput(Request $request, GeraiInvoice $invoice = null, $isUpdate = false)
    {
        // Main invoice validation
        $messages = $this->getValidationMessages();

        $validPaymentMethods = $this->paymentMethod['result'] ?? [];
        
        // Determine the ignore value based on update or create
        $ignoreValue = $isUpdate && $invoice ? $invoice->parentInvoiceNo : ($invoice?->id ?? null);

        $data = $request->validate([
            'parentInvoiceNo' => [
                'required', 
                'string', 
                'min:6',
                'max:255',
                // Check uniqueness in gerai_invoice table
                Rule::unique('gerai_invoice', 'parentInvoiceNo')->ignore($ignoreValue, 'parentInvoiceNo'),
                // Check uniqueness in invoice table
                Rule::unique('invoice', 'invoiceNo')->ignore($ignoreValue, 'invoiceNo'),
            ],
            'date' => 'required|date_format:d/m/Y',
            'transporterCode' => 'required|string|max:255',
            'transporterName' => 'required|string|max:255',
            'vehicleNo' => 'required|string|max:255',
            'phoneNo' => 'required|string|max:20',
            'paymentMethod' => ['required', 'string', 'max:255', Rule::in($validPaymentMethods)],
            'statusID' => 'required|in:1,2',
            'GrandQuantity' => 'nullable|numeric|min:0',
            'GrandTotal' => 'nullable|numeric|min:0',
        ], $messages);

        $statusID = $request->input('statusID');

        // Get old deposit IDs for update scenario
        // $oldDepositIds = [];
        // if ($isUpdate && $invoice) {
        //     $oldDepositIds = GeraiDeposit::whereHas('invoice', function($query) use ($invoice) {
        //         $query->where('parentInvoiceNo', $invoice->parentInvoiceNo);
        //     })->pluck('id')->toArray();
        // }

        $stallValidationRules = [
            'stall' => 'required|array|min:1',
            'stall.*.stallId' => 'required|string',
            // 'stall.*.depositNo' => [
            //     'nullable',
            //     'string',
            //     Rule::unique('gerai_deposit', 'depositNo')->whereNotIn('id', $oldDepositIds),
            //     Rule::unique('deposit', 'depositNo')->whereNotIn('id', $oldDepositIds),
            // ],
            'stall.*.depositPaymentMethod' => [
                'nullable',
                'string',
                Rule::in($validPaymentMethods),
            ],
            'stall.*.depositAmount' => 'nullable|numeric|min:0|max:99999999',
        ];

        // Conditional quantity validation based on statusID
        if ($statusID == 2) {
            $stallValidationRules['stall.*.quantityTong'] = 'required|numeric|min:1';
        } else {
            $stallValidationRules['stall.*.quantityTong'] = 'required|numeric|min:0';
        }

        $request->validate($stallValidationRules, $messages);

        $stallData = $request->input('stall');

        return [
            'data' => $data,
            'stallData' => $stallData,
            'statusID' => $statusID,
        ];
    }

    /**
     * Used by both store and update methods
     */
    private function getValidationMessages()
    {
        return [
            // Parent Invoice
            'parentInvoiceNo.required' => 'Parent Invoice Number is required.',
            'parentInvoiceNo.min' => 'Parent Invoice Number must be at least 6 characters.',
            'parentInvoiceNo.unique' => 'This Parent Invoice Number already exists.',
            'parentInvoiceNo.max' => 'Parent Invoice Number cannot exceed 50 characters.',
            
            // Date
            'date.required' => 'Date is required.',
            'date.date_format' => 'Date must be in format DD/MM/YYYY.',
            
            // Transporter
            'transporterCode.required' => 'Transporter is required.',
            'transporterName.required' => 'Transporter Name is required.',
            
            // Vehicle
            'vehicleNo.required' => 'Vehicle Number is required.',
            
            // Phone
            'phoneNo.required' => 'Phone Number is required.',
            'phoneNo.max' => 'Phone Number cannot exceed 20 characters.',
            
            // Payment Method
            'paymentMethod.required' => 'Payment Method is required.',
            
            // Status
            'statusID.required' => 'Status is required.',
            'statusID.in' => 'Invalid status selected.',
            
            // Grand Total
            'GrandQuantity.numeric' => 'Grand Quantity must be a number.',
            'GrandQuantity.min' => 'Grand Quantity cannot be negative.',
            'GrandTotal.numeric' => 'Grand Total must be a number.',
            'GrandTotal.min' => 'Grand Total cannot be negative.',
            
            // Stall Array
            'stall.required' => 'At least one stall is required.',
            'stall.array' => 'Invalid stall data format.',
            'stall.min' => 'At least one stall is required.',
            
            // Stall Fields
            'stall.*.stallId.required' => 'Stall selection is required.',
            'stall.*.stallId.string' => 'Invalid stall selection.',
            
            // Quantity
            'stall.*.quantityTong.required' => 'Quantity is required.',
            'stall.*.quantityTong.numeric' => 'Quantity must be a number.',
            'stall.*.quantityTong.min' => 'Quantity cannot be 0 when submitting.',
            
            // Deposit
            // 'stall.*.depositNo.string' => 'Deposit Reference Number must be text.',
            // 'stall.*.depositNo.unique' => 'This Deposit Reference Number already exists.',
            'stall.*.depositPaymentMethod.string' => 'Invalid deposit payment method.',
            'stall.*.depositPaymentMethod.in' => 'Invalid deposit payment method selected.',
            'stall.*.depositAmount.numeric' => 'Deposit Amount must be a number.',
            'stall.*.depositAmount.min' => 'Deposit Amount cannot be negative.',
            'stall.*.depositAmount.max' => 'Deposit Amount cannot exceed 99,999,999.',
        ];
    }

    public function store(Request $request)
    {
        if (Session::has('backUrl')) {
            Session::keep('backUrl');
        }

        try {
            $validatedData = $this->validateInput($request);
        } catch (\Illuminate\Validation\ValidationException $e) {
            // Laravel validation failed - return with validation errors
            return redirect()->back()
                ->withInput()
                ->withErrors($e->errors())
                ->with([
                    'message' => 'Validation failed. Please check the form.',
                    'alert-type' => 'error'
                ]);
        } catch (\Exception $e) {
            // Other exceptions (like duplicate deposit number)
            return redirect()->back()
                ->withInput()
                ->with([
                    'message' => $e->getMessage(),
                    'alert-type' => 'error'
                ]);
        }

        $data = $validatedData['data'];
        $stallData = $validatedData['stallData'];
        $statusID = $validatedData['statusID'];
        $parentInvoiceNo = $data['parentInvoiceNo'];

        Log::info("Store Gerai - Starting", [
            'parentInvoiceNo' => $parentInvoiceNo,
            'stallCount' => count($stallData),
            'statusID' => $statusID
        ]);

        $dbFormattedDate = Carbon::createFromFormat('d/m/Y', $data['date'])->format('Y-m-d');
        
        $errors = [];
        $successCount = 0;
        $subInvoiceCounter = 1;

        if ($statusID == 2) {
            // Filter active stalls (quantity > 0)
            $activeStalls = array_filter($stallData, function($stall) {
                return isset($stall['quantityTong']) && $stall['quantityTong'] > 0;
            });
            $activeStalls = array_values($activeStalls); // Reindex
        } else {
            $activeStalls = $stallData;
        }

        $tongPrice = $this->stockItemMethod['items'][0]['price'];
        
        try {
            DB::beginTransaction();
            
            // STEP 1: Create all invoices in database first
            $createdInvoices = [];
            foreach ($activeStalls as $index => $stall) {
                $subInvoiceNo = $parentInvoiceNo . '-' . $subInvoiceCounter;
                $geraiCode = $stall['stallId'];
                $totalAmount = $stall['quantityTong'] * $tongPrice;

                // Create GeraiInvoice
                $geraiInvoice = GeraiInvoice::create([
                    'invoiceNo' => $subInvoiceNo,
                    'parentInvoiceNo' => $parentInvoiceNo,
                    'date' => $dbFormattedDate,
                    'debtorCode' => $geraiCode,
                    'debtorName' => $geraiCode,
                    'transporterCode' => $data['transporterCode'],
                    'transporterName' => $data['transporterName'],
                    'vehicleNo' => $data['vehicleNo'],
                    'phoneNo' => $data['phoneNo'] ?? null,
                    'totalQuantity' => $stall['quantityTong'],
                    'totalAmount' => $totalAmount,
                    'grandQuantity' => $data['GrandQuantity'] ?? 0,
                    'grandTotal' => $data['GrandTotal'] ?? 0,
                    'statusID' => $statusID,
                ]);

                // Create GeraiArPayment
                $payment = GeraiArPayment::create([
                    'debtor' => $geraiCode,
                    'paymentMethod' => $data['paymentMethod'],
                    'paymentAmount' => $totalAmount,
                    'geraiInvoiceID' => $geraiInvoice->id,
                ]);

                // Create GeraiItem
                GeraiItem::create([
                    'itemTong' => $this->itemMapper['TONG'],
                    'quantity' => $stall['quantityTong'],
                    'unitPrice' => $tongPrice,
                    'geraiInvoiceID' => $geraiInvoice->id,
                ]);

                ActivityLogger::logGeraiInvoiceCreated($geraiInvoice, $statusID);

                // Create GeraiDeposit if provided
                $deposit = null;
                if (!empty($stall['depositAmount'])) {
                    $deposit = GeraiDeposit::create([
                        'depositNo' => $subInvoiceNo,
                        'debtor' => $geraiCode,
                        'depositAmount' => $stall['depositAmount'],
                        'paymentMethod' => $stall['depositPaymentMethod'] ?? null,
                        'geraiInvoiceID' => $geraiInvoice->id,
                    ]);
                }

                $createdInvoices[] = [
                    'invoice' => $geraiInvoice,
                    'payment' => $payment,
                    'deposit' => $deposit
                ];

                $subInvoiceCounter++;
            }

            // STEP 2: If submitted, post to AutoCount
            if ($statusID == 2) {
                $this->postToAutoCount(
                    $createdInvoices,
                    $parentInvoiceNo,
                    $data['transporterCode'],
                    $data['vehicleNo'],
                    $dbFormattedDate,
                    $data['GrandQuantity']
                );
            }

            DB::commit();

            // Set notification message based on status
            $notificationMessage = $statusID == 1 ? 'Draft saved.' : 'Submitted!';
            
            $notification = [
                'message' => $notificationMessage,
                'alert-type' => 'success'
            ];
            // Redirect based on user permission
            if (auth()->user()->can('invoice-view')) {
                return redirect()->route('admin.gerai.index')->with($notification);
            } else {
                return redirect()->route('admin.dashboard')->with($notification);
            }

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Store Gerai - Failed', [
                'error' => $e->getMessage(),
                'parent_invoice' => $parentInvoiceNo
            ]);
            
            return redirect()->back()->withInput()->with([
                'message' => 'Error creating invoices: ' . $e->getMessage(),
                'alert-type' => 'error'
            ]);
        }
    }

    public function show($id)
    {
        if (Session::has('backUrl')) {
            Session::keep('backUrl');
        }
        
        $geraiInvoice = GeraiInvoice::with(['items', 'arPayment', 'deposit', 'status'])->findOrFail($id);
        
        $formattedDate = Carbon::parse($geraiInvoice->date)->format('d/m/Y');
        
        return view('gerai.show', compact('geraiInvoice', 'formattedDate'));
    }

    public function edit($id)
    {
        if (Session::has('backUrl')) {
            Session::keep('backUrl');
        }

        $geraiInvoice = GeraiInvoice::with(['items', 'deposit', 'arPayment', 'status'])
            ->findOrFail($id);

        // Check if already submitted
        if ($geraiInvoice->statusID == 2) {
            $notification = [
                'message' => 'This invoice is already submitted and cannot be edited',
                'alert-type' => 'error'
            ];
            return redirect()->route('admin.gerai.index')->with($notification);
        }

        $parentInvoiceNo = $geraiInvoice->parentInvoiceNo;

        // Load ALL gerai invoices with the same parent
        $allGerais = GeraiInvoice::with(['items', 'deposit'])
            ->where('parentInvoiceNo', $parentInvoiceNo)
            ->orderBy('invoiceNo', 'asc')
            ->get();

        // Build stallData array for the blade
        $stallData = [];
        foreach ($allGerais as $gerai) {
            $item = $gerai->items->first();
            $deposit = $gerai->deposit->first();

            $stallData[] = [
                'stallId' => $gerai->debtorCode,
                'quantityTong' => $item?->quantity ?? 0,
                'depositNo' => $deposit?->depositNo ?? '',
                'depositPaymentMethod' => $deposit?->paymentMethod ?? '',
                'depositAmount' => $deposit?->depositAmount ?? 0,
            ];
        }

        $formattedDate = Carbon::parse($geraiInvoice->date)->format('d/m/Y');
        $transporterMethod = $this->transporterMethod;
        $stallMethod = $this->stallMethod;
        $stockItemMethod = $this->stockItemMethod;
        $paymentMethod = $this->paymentMethod;

        return view('gerai.update', compact(
            'geraiInvoice',
            'parentInvoiceNo',
            'stallData',
            'formattedDate',
            'transporterMethod',
            'stallMethod',
            'stockItemMethod',
            'paymentMethod'
        ));
    }

    public function update(Request $request, $id)
    {
        if (Session::has('backUrl')) {
            Session::keep('backUrl');
        }

        $geraiInvoice = GeraiInvoice::findOrFail($id);
        $oldParentInvoiceNo = $geraiInvoice->parentInvoiceNo;
        
        try {
            $validatedData = $this->validateInput($request, $geraiInvoice, true);
        } catch (\Illuminate\Validation\ValidationException $e) {
            // Laravel validation failed - return with validation errors
            return redirect()->back()
                ->withInput()
                ->withErrors($e->errors())
                ->with([
                    'message' => 'Validation failed. Please check the form.',
                    'alert-type' => 'error'
                ]);
        } catch (\Exception $e) {
            // Other exceptions (like duplicate deposit number)
            return redirect()->back()
                ->withInput()
                ->with([
                    'message' => $e->getMessage(),
                    'alert-type' => 'error'
                ]);
        }
        
        $data = $validatedData['data'];
        $stallData = $validatedData['stallData'];
        $statusID = $validatedData['statusID'];
        $parentInvoiceNo = $data['parentInvoiceNo'];

        Log::info("Update Gerai - Starting", [
            'old_parent_invoice_no' => $oldParentInvoiceNo,
            'new_parent_invoice_no' => $parentInvoiceNo,
            'stallCount' => count($stallData),
            'statusID' => $statusID
        ]);

        $dbFormattedDate = Carbon::createFromFormat('d/m/Y', $data['date'])->format('Y-m-d');
        
        // Filter active stalls (quantity > 0)
        if ($statusID == 2) {
            $activeStalls = array_filter($stallData, function($stall) {
                return isset($stall['quantityTong']) && $stall['quantityTong'] > 0;
            });
            $activeStalls = array_values($activeStalls);
        } else {
            $activeStalls = $stallData;
        }

        $tongPrice = $this->stockItemMethod['items'][0]['price'];
        
        // Filter active stalls (quantity > 0)
        if ($statusID == 2) {
            $activeStalls = array_filter($stallData, function($stall) {
                return isset($stall['quantityTong']) && $stall['quantityTong'] > 0;
            });
            $activeStalls = array_values($activeStalls);
        } else {
            $activeStalls = $stallData;
        }

        $tongPrice = $this->stockItemMethod['items'][0]['price'];

        try {
            DB::beginTransaction();

            // STEP 1: Delete ALL existing gerai invoices with OLD parent invoice number
            GeraiInvoice::where('parentInvoiceNo', $oldParentInvoiceNo)->delete();
            Log::info('Update Gerai - Deleted existing gerais for old parent: ' . $oldParentInvoiceNo);

            // STEP 2: Recreate ALL gerais in database with NEW parent invoice number
            $createdInvoices = [];
            $subInvoiceCounter = 1;

            foreach ($activeStalls as $index => $stall) {
                $subInvoiceNo = $parentInvoiceNo . '-' . $subInvoiceCounter;
                $geraiCode = $stall['stallId'];
                $totalAmount = $stall['quantityTong'] * $tongPrice;

                // Create Invoice with NEW parent invoice number
                $geraiInvoice = GeraiInvoice::create([
                    'invoiceNo' => $subInvoiceNo,
                    'parentInvoiceNo' => $parentInvoiceNo,  // Use NEW parent invoice number
                    'date' => $dbFormattedDate,
                    'debtorCode' => $geraiCode,
                    'debtorName' => $geraiCode,
                    'transporterCode' => $data['transporterCode'],
                    'transporterName' => $data['transporterName'], 
                    'vehicleNo' => $data['vehicleNo'],
                    'phoneNo' => $data['phoneNo'] ?? null,   
                    'totalQuantity' => $stall['quantityTong'],
                    'totalAmount' => $totalAmount,
                    'grandQuantity' => $data['GrandQuantity'] ?? 0,
                    'grandTotal' => $data['GrandTotal'] ?? 0,
                    'statusID' => $statusID,
                ]);

                // Create Payment
                $payment = GeraiArPayment::create([
                    'debtor' => $geraiCode,
                    'paymentMethod' => $data['paymentMethod'],
                    'paymentAmount' => $totalAmount,
                    'geraiInvoiceID' => $geraiInvoice->id,
                ]);

                // Create Item
                GeraiItem::create([
                    'itemTong' => $this->itemMapper['TONG'],
                    'quantity' => $stall['quantityTong'],
                    'unitPrice' => $tongPrice,
                    'geraiInvoiceID' => $geraiInvoice->id,
                ]);

                // Create Deposit if provided
                $deposit = null;
                if (!empty($stall['depositAmount'])) {
                    $deposit = GeraiDeposit::create([
                        'depositNo' => $subInvoiceNo,
                        'debtor' => $geraiCode,
                        'depositAmount' => $stall['depositAmount'],
                        'paymentMethod' => $stall['depositPaymentMethod'] ?? null,
                        'geraiInvoiceID' => $geraiInvoice->id,
                    ]);
                }

                ActivityLogger::logInvoiceUpdated($geraiInvoice, $geraiInvoice->statusID);

                $createdInvoices[] = [
                    'invoice' => $geraiInvoice,
                    'payment' => $payment,
                    'deposit' => $deposit
                ];

                $subInvoiceCounter++;
            }

            if ($statusID == 2) {
                $this->postToAutoCount(
                    $createdInvoices,
                    $parentInvoiceNo,
                    $data['transporterCode'],
                    $data['vehicleNo'],
                    $dbFormattedDate,
                    $data['GrandQuantity']
                );
            }

            DB::commit();

            // Set notification message based on status
            $notificationMessage = $statusID == 1 ? 'Draft updated.' : 'Updated and submitted!';
            
            $notification = [
                'message' => $notificationMessage,
                'alert-type' => 'success'
            ];

            // Redirect based on user permission
            if (auth()->user()->can('invoice-view')) {
                return redirect()->route('admin.gerai.index')->with($notification);
            } else {
                return redirect()->route('admin.dashboard')->with($notification);
            }

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Update Gerai - Failed', [
                'error' => $e->getMessage(),
                'old_parent_invoice' => $oldParentInvoiceNo,
                'new_parent_invoice' => $parentInvoiceNo
            ]);
            
            return redirect()->back()->withInput()->with([
                'message' => 'Error updating invoices: ' . $e->getMessage(),
                'alert-type' => 'error'
            ]);
        }
    }

    /**
     * Deletes ALL gerais with same parent invoice number
     */
    public function destroy($id)
    {
        $geraiInvoice = GeraiInvoice::findOrFail($id);
        $parentInvoiceNo = $geraiInvoice->parentInvoiceNo;
        
        if (!auth()->user()->can('invoice-delete')) {
            return response()->json([
                'message' => 'You do not have permission.',
                'alert-type' => 'warning'
            ], 403);
        }
        
        try {
            DB::beginTransaction();
            
            // Get ALL gerais with same parent
            $allGerais = GeraiInvoice::where('parentInvoiceNo', $parentInvoiceNo)->get();
            
            Log::info('Delete Gerai - Starting', [
                'clicked_id' => $id,
                'parent_invoice' => $parentInvoiceNo,
                'total_gerais' => $allGerais->count(),
                'status' => $geraiInvoice->statusID
            ]);
            
            // If submitted (statusID = 2), delete from AutoCount first
            if ($geraiInvoice->statusID == 2) {
                Log::info('==================== AUTOCOUNT DELETION STARTED ====================');
                
                // STEP 1: Delete Deposits for each Gerai (if exists)
                Log::info('---------- STEP 1: DELETING DEPOSITS ----------');
                $depositDeleteCount = 0;
                
                foreach ($allGerais as $index => $gerai) {
                    $deposit = $gerai->deposit()->first();
                    
                    if ($deposit && $deposit->depositNo) {
                        $deleteDepositDocNo = ["docNo" => $deposit->depositNo];
                        
                        Log::info("(API/DeleteDeposit) Deposit #{" . ($index + 1) . "}");
                        Log::info("Delete DEPOSIT\n" . json_encode($deleteDepositDocNo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
                        
                        $response = (new GetAPIController())->deleteDeposit($deleteDepositDocNo);
                        
                        Log::info("RESPONSE\n" . json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
                        
                        if ($response['success']) {
                            Log::info("Deposit #{" . ($index + 1) . "} - DELETED ✓");
                            $depositDeleteCount++;
                        } else {
                            Log::warning("Deposit #{" . ($index + 1) . "} - DELETE FAILED (continuing...)", [
                                'error' => $response['result'] ?? 'Unknown error'
                            ]);
                        }
                    }
                }
                
                Log::info("STEP 1 COMPLETED - Deposits Deleted: {$depositDeleteCount}\n");
                
                // STEP 2: Delete AR Payments for each Gerai
                Log::info('---------- STEP 2: DELETING AR PAYMENTS ----------');
                $paymentDeleteCount = 0;
                
                foreach ($allGerais as $index => $gerai) {
                    $payment = $gerai->arPayment()->first();
                    
                    if ($payment && $payment->paymentNo) {
                        $deleteARDocNo = ["docNo" => $payment->paymentNo];
                        
                        Log::info("(API/DeleteARPayment) AR Payment #{" . ($index + 1) . "}");
                        Log::info("Delete AR PAYMENT\n" . json_encode($deleteARDocNo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
                        
                        $response = (new GetAPIController())->deleteARPayment($deleteARDocNo);
                        
                        Log::info("RESPONSE\n" . json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
                        
                        if ($response['success']) {
                            Log::info("AR Payment #{" . ($index + 1) . "} - DELETED ✓");
                            $paymentDeleteCount++;
                        } else {
                            Log::warning("AR Payment #{" . ($index + 1) . "} - DELETE FAILED (continuing...)", [
                                'error' => $response['result'] ?? 'Unknown error'
                            ]);
                        }
                    }
                }
                
                Log::info("STEP 2 COMPLETED - AR Payments Deleted: {$paymentDeleteCount}\n");
                
                // STEP 3: Delete Sales Invoices for each Gerai (CHANGED FROM DELETING PARENT INVOICE)
                Log::info('---------- STEP 3: DELETING SALES INVOICES ----------');
                $invoiceDeleteCount = 0;
                
                foreach ($allGerais as $index => $gerai) {
                    $deleteInvoiceDocNo = ["docNo" => "KPBIV-" . $gerai->invoiceNo];
                    
                    Log::info("(API/DeleteSalesInvoice) Sales Invoice #{" . ($index + 1) . "}");
                    Log::info("Delete SALES INVOICE\n" . json_encode($deleteInvoiceDocNo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
                    
                    $response = (new GetAPIController())->deleteInvoice($deleteInvoiceDocNo);
                    
                    Log::info("RESPONSE\n" . json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
                    
                    if ($response['success']) {
                        Log::info("Sales Invoice #{" . ($index + 1) . "} - DELETED ✓");
                        $invoiceDeleteCount++;
                    } else {
                        Log::warning("Sales Invoice #{" . ($index + 1) . "} - DELETE FAILED (continuing...)", [
                            'error' => $response['result'] ?? 'Unknown error'
                        ]);
                    }
                }
                
                Log::info("STEP 3 COMPLETED - Sales Invoices Deleted: {$invoiceDeleteCount}\n");
                
                Log::info('==================== AUTOCOUNT DELETION COMPLETED ====================');
                Log::info('DELETION SUMMARY', [
                    'deposits_deleted' => $depositDeleteCount,
                    'payments_deleted' => $paymentDeleteCount,
                    'invoices_deleted' => $invoiceDeleteCount,
                    'total_operations' => $depositDeleteCount + $paymentDeleteCount + $invoiceDeleteCount
                ]);
            }
            
            // Delete ALL gerais from database (cascade handles related records)
            GeraiInvoice::where('parentInvoiceNo', $parentInvoiceNo)->delete();
            
            DB::commit();
            
            ActivityLogger::logGeraiInvoiceDeleted($geraiInvoice);

            Log::info('Delete Gerai - Success', [
                'parent_invoice' => $parentInvoiceNo,
                'deleted_count' => $allGerais->count()
            ]);
            
            return response()->json([
                'message' => 'Gerai Invoice(s) deleted successfully',
                'alert-type' => 'success'
            ], 200);
            
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error("Gerai Invoice Delete Error", [
                'error' => $e->getMessage(),
                'parent_invoice' => $parentInvoiceNo,
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'message' => 'Error deleting invoice: ' . $e->getMessage(),
                'alert-type' => 'error'
            ], 500);
        }
    }

    private function postToAutoCount($createdInvoices, $parentInvoiceNo, $transporterCode, $vehicleNo, $dbFormattedDate, $grandQuantity)
    {
        $tongPrice = $this->stockItemMethod['items'][0]['price'];
        
        Log::info('==================== AUTOCOUNT POSTING STARTED ====================');
        Log::info('Parent Invoice Details', [
            'parent_invoice_no' => $parentInvoiceNo,
            'transporter_code' => $transporterCode,
            'vehicle_no' => $vehicleNo,
            'document_date' => $dbFormattedDate,
            'total_gerais' => count($createdInvoices),
            'grand_quantity' => $grandQuantity ?? 'N/A'
        ]);

        // STEP 1: Post Sales Invoices for each Gerai (CHANGED FROM SALES ORDERS)
        Log::info('---------- STEP 1: POSTING SALES INVOICES ----------');
        $invoiceCount = 0;
        
        foreach ($createdInvoices as $index => $item) {
            $geraiInvoice = $item['invoice'];
            
            $salesInvoicePost = [
                "debtorCode" => $geraiInvoice->debtorCode,  // Gerai code (customer)
                "documentNo" => "KPBIV-" . $geraiInvoice->invoiceNo,
                "documentDate" => $geraiInvoice->date,
                "vehicleNo" => $vehicleNo,
                "items" => [[
                    "itemCode" => $this->itemMapper['TONG'],
                    "quantity" => $geraiInvoice->totalQuantity,
                    "unitPrice" => $tongPrice
                ]]
            ];

            Log::info("(API/CreateSalesInvoice) Sales Invoice #{" . ($index + 1) . "}");
            Log::info("Create SALES INVOICE\n" . json_encode($salesInvoicePost, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

            $response = (new GetAPIController())->postSalesInvoice($salesInvoicePost);
            
            Log::info("RESPONSE\n" . json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
            
            if (!$response['success']) {
                Log::error("Sales Invoice #{" . ($index + 1) . "} - FAILED", [
                    'error' => $response['result'],
                    'gerai_code' => $geraiInvoice->debtorCode
                ]);
                throw new \Exception('Sales Invoice Error for ' . $geraiInvoice->debtorCode . ': ' . $response['result']);
            }
            
            $invoiceCount++;
            Log::info("Sales Invoice #{" . ($index + 1) . "} - SUCCESS ✓\n");
        }
        
        Log::info("STEP 1 COMPLETED - Total Sales Invoices Posted: {$invoiceCount}\n");

        // STEP 2: Post AR Payments for each Gerai
        Log::info('---------- STEP 2: POSTING AR PAYMENTS ----------');
        $paymentCount = 0;
        
        foreach ($createdInvoices as $index => $item) {
            $geraiInvoice = $item['invoice'];
            $payment = $item['payment'];
            
            $arPayment = [
                "debtorCode" => $geraiInvoice->debtorCode,
                "paymentMethod" => $payment->paymentMethod,
                "docDate" => $geraiInvoice->date,
                "amount" => $geraiInvoice->totalAmount,
                "chequeNo" => null,
                "knockOffItems" => [[
                    "invoiceNo" => "KPBIV-" . $geraiInvoice->invoiceNo,
                    "amount" => $geraiInvoice->totalAmount
                ]]
            ];

            Log::info("(API/CreateReceivePayment) AR Payment #{" . ($index + 1) . "}");
            Log::info("Create AR PAYMENT\n" . json_encode($arPayment, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

            $response = (new GetAPIController())->postARPayment($arPayment);
            
            Log::info("RESPONSE\n" . json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
            
            if (!$response['success']) {
                Log::error("AR Payment #{" . ($index + 1) . "} - FAILED", [
                    'error' => $response['result'],
                    'debtor_code' => $geraiInvoice->debtorCode
                ]);
                throw new \Exception('AR Payment Error for ' . $geraiInvoice->debtorCode . ': ' . $response['result']);
            }

            // Update payment number
            $payment->paymentNo = $response['result'];
            $payment->save();
            
            Log::info("AR Payment #{" . ($index + 1) . "} - SUCCESS ✓ (Payment No: {$payment->paymentNo})\n");
            
            $paymentCount++;
        }
        
        Log::info("STEP 2 COMPLETED - Total AR Payments Posted: {$paymentCount}\n");

        // STEP 3: Post Deposits for each Gerai (if exists)
        Log::info('---------- STEP 3: POSTING DEPOSITS ----------');
        $depositCount = 0;
        $depositSkipped = 0;
        
        foreach ($createdInvoices as $index => $item) {
            $geraiInvoice = $item['invoice'];
            $deposit = $item['deposit'];
            if ($deposit) {
                $depositPost = [
                    "documentNo" => $geraiInvoice->invoiceNo,
                    "documentDate" => $geraiInvoice->date,
                    "depositMethod" => "CUSTOMER DEPOSIT",
                    "customerAccount" => $geraiInvoice->debtorCode,
                    "items" => [[
                        "paymentMethod" => $deposit->paymentMethod,
                        "depositAmount" => floatval($deposit->depositAmount)
                    ]]
                ];

                Log::info("(API/CreateDeposit) Deposit #{" . ($index + 1) . "}");
                Log::info("Create DEPOSIT\n" . json_encode($depositPost, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

                $response = (new GetAPIController())->postDeposit($depositPost);
                
                Log::info("RESPONSE\n" . json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

                if ($response['success']) {
                    $deposit->depositAccNo = $response['result'] ?? null;
                    $deposit->save();
                    
                    Log::info("Deposit #{" . ($index + 1) . "} - SUCCESS ✓ (Deposit Acc: {$deposit->depositAccNo})\n");
                    
                    $depositCount++;
                } else {
                    Log::warning("Deposit #{" . ($index + 1) . "} - FAILED (Non-critical)\n" . json_encode([
                        'error' => $response['result']
                    ], JSON_PRETTY_PRINT));
                }
            } else {
                Log::info("Deposit #{" . ($index + 1) . "} - SKIPPED (No deposit found)\n");
                $depositSkipped++;
            }
        }
        
        Log::info("STEP 3 COMPLETED - Deposits Posted: {$depositCount}, Skipped: {$depositSkipped}\n");

        Log::info('==================== AUTOCOUNT POSTING COMPLETED ====================');
        Log::info('SUMMARY', [
            'sales_invoices_posted' => $invoiceCount,
            'ar_payments_posted' => $paymentCount,
            'deposits_posted' => $depositCount,
            'deposits_skipped' => $depositSkipped,
            'total_operations' => $invoiceCount + $paymentCount + $depositCount
        ]);
    }
}