<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Purchase;
use App\Models\Expense;
use App\Models\PurchaseItem;
use App\Models\IssuedCheque;
use Illuminate\Support\Facades\DB;


class purchaseController extends Controller
{
    public function index()
    {
        // Get the current auto-increment value for the 'purchases' table
        $currentAutoIncrement = DB::select("SHOW TABLE STATUS LIKE 'purchases'");

        // Extract the auto_increment value
        $autoIncrementValue = $currentAutoIncrement[0]->Auto_increment;

        return response()->json(['auto_increment_value' => $autoIncrementValue]);
    }

    public function store(Request $request)
    {
        // 1. Validate high-level purchase fields including 'grn_no'
        $validated = $request->validate([
            'grn_no' => 'required',
            'invoice_no' => 'required|string',
            'supplier_id' => 'required|integer',
            'total_vat' => 'required|numeric',
            'total_sscl' => 'required|numeric',
            'total_margin' => 'required|numeric',
            'sub_total' => 'required|numeric',
            'special_discount' => 'nullable|string',
            'percentage_discount' => 'nullable|string',
            'net_total' => 'required|numeric',
            'payment_method' => 'required|string',
            'payment_amount' => 'required|numeric',
            'credit_payment_due_on' => 'nullable|string',
            'credit_payment_date' => 'nullable|date',
            'cheque_data.*.cheque_no' => 'required|string',
            'cheque_data.*.bank_name' => 'required|string',
            'cheque_data.*.branch_name' => 'required|string',
            'cheque_data.*.cheque_date' => 'required|date',
            'cheque_data.*.amount' => 'required|numeric',
        ]);

        DB::beginTransaction();

        try {
            // 2. Insert into purchases table with grn_no
            $purchase = Purchase::create([
                'invoice_no' => $request->invoice_no,
                'supplier_id' => $request->supplier_id,
                'total_vat' => $request->total_vat,
                'total_sscl' => $request->total_sscl,
                'total_margin' => $request->total_margin,
                'sub_total' => $request->sub_total,
                'special_discount' => $request->special_discount,
                'percentage_discount' => $request->percentage_discount,
                'net_total' => $request->net_total,
            ]);

            // Validate item_data
            $request->validate([
                'item_data' => 'required|array',
                'item_data.*.qty' => 'required|integer',
                'item_data.*.initialCost' => 'required|numeric',
                'item_data.*.vatAmount' => 'required|numeric',
                'item_data.*.ssclAmount' => 'required|numeric',
                'item_data.*.finalCost' => 'required|numeric',
                'item_data.*.marketPrice' => 'required|numeric',
                'item_data.*.totalCost' => 'required|numeric',
                'item_data.*.marginPercentage' => 'required|numeric',
                'item_data.*.isFree' => 'required|boolean',
                'item_data.*.item_id' => 'required|integer',
            ]);

            // 3. Insert into purchase_items table
            foreach ($request->item_data as $item) {
                PurchaseItem::create([
                    'grn_no' => $request->grn_no, // Now valid due to purchase creation
                    'qty' => $item['qty'],
                    'initial_cost' => $item['initialCost'],
                    'vat_amount' => $item['vatAmount'],
                    'sscl_amount' => $item['ssclAmount'],
                    'final_cost' => $item['finalCost'],
                    'sales_price' => $item['marketPrice'],
                    'margin_amount' => $item['finalCost'] - $item['initialCost'],
                    'margin_percentage' => $item['marginPercentage'],
                    'market_price' => $item['marketPrice'],
                    'total_cost' => $item['totalCost'],
                    'isFree' => $item['isFree'] ? 1 : 0,
                    'item_id' => $item['item_id'],
                ]);
            }

            // 4. Insert into expense table
            Expense::create([
                'grn_no' => $request->grn_no,
                'payment_method' => $request->payment_method,
                'payment_amount' => $request->payment_amount,
                'credit_payment_due_on' => $request->credit_payment_due_on,
                'credit_payment_due_date' => $request->credit_payment_date,
            ]);

            if ($request->payment_method === 'cheque') {
                // Use 'cheque_data' from the request
                $cheques = $request->cheque_data ?? [];
            
                foreach ($cheques as $chequeData) {
                    IssuedCheque::create([
                        'grn_no' => $request->grn_no,
                        'cheque_no' => $chequeData['cheque_no'],
                        'bank_name' => $chequeData['bank_name'],
                        'branch_name' => $chequeData['branch_name'],
                        'cheque_date' => $chequeData['cheque_date'],
                        'amount' => $chequeData['amount'],
                    ]);
                }
            }

            DB::commit();
            return response()->json(['message' => 'Purchase saved successfully'], 200);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}
