<?php

namespace App\Http\Controllers;

use App\Customer;
use App\GoodReceiptDetail;
use App\GoodReceiptTruck;
use App\Sale;
use App\Suppliers;
use App\SupplierAccount;
use App\BCheque;
use App\BChequeItem;
use App\BChequeDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;

class BchequeController extends Controller
{
    public function index()
    {
        $b_cheques = BCheque::with(['details', 'items', 'supplier', 'goodReceiptTruck', 'goodReceiptTruck.goodReceiptDetails'])->get();
        return view('b_cheque.index', compact('b_cheques'));
    }

    public function create()
    {
        $trucks = GoodReceiptTruck::with('goodReceipts.goodReceiptDetails')->get();
        $suppliers = Suppliers::all();
        return view('b_cheque.create', compact('trucks', 'suppliers'));
    }

    public function store(Request $request)
    {
        // Validate the request data
        $validatedData = $request->validate([
            'bCheck_date' => 'required|date',
            'pb_no' => 'required|string|max:255',
            'good_receipts_truck_id' => 'required|integer|exists:good_receipts_truck,id_truck',
            'suppliers' => 'required|integer|exists:suppliers,id_supplier',
            'bilty_no' => 'required|string|max:255',
            'detail' => 'nullable|string|max:255',
            'bCheck_status' => 'required|boolean',
            'marka.*' => 'nullable|string|max:255',
            'items_name.*' => 'nullable|string|max:255',
            'bori.*' => 'nullable|numeric',
            'weight.*' => 'nullable|numeric',
            'rate.*' => 'nullable|numeric',
            'amount.*' => 'nullable|numeric',
            'total_bori' => 'nullable|numeric',
            'total_weight' => 'nullable|numeric',
            'total_amount' => 'nullable|numeric',
            'total_expanse_amount' => 'nullable|numeric',
            'save_amount' => 'nullable|numeric',
            'commission_rate' => 'nullable|numeric|max:100',
            'commission' => 'nullable|numeric',
            'more' => 'nullable|numeric',
            'rent_received' => 'nullable|numeric',
            'labour' => 'nullable|numeric',
            'market_fees' => 'nullable|numeric',
            'post_expense' => 'nullable|numeric',
            'miscellaneous_expense' => 'nullable|numeric',
            'cash' => 'nullable|numeric',
        ]);

        // Store the BCheque data
        $bCheque = BCheque::create([
            'bussiness_id' => auth()->user()->business_id,
            'good_receipts_truck_id' => $validatedData['good_receipts_truck_id'],
            'customer_id' => null,
            'supplier_id' => $validatedData['suppliers'],
            'date' => $validatedData['bCheck_date'],
            'pb_no' => $validatedData['pb_no'],
            'bilty_no' => $validatedData['bilty_no'],
            'detail' => $validatedData['detail'],
            'status' => $validatedData['bCheck_status'],
            'created_by' => auth()->user()->name,
        ]);

        // Store BCheque Items data
        if (!empty($validatedData['marka'])) {
            foreach ($validatedData['marka'] as $index => $marka) {
                if ($marka && isset($validatedData['items_name'][$index])) {
                    BChequeItem::create([
                        'b_cheque_id' => $bCheque->id_b_cheque,
                        'marka' => $marka,
                        'item' => $validatedData['items_name'][$index],
                        'bori' => $validatedData['bori'][$index],
                        'weight' => $validatedData['weight'][$index],
                        'rate' => $validatedData['rate'][$index],
                        'amount' => $validatedData['amount'][$index],
                        'created_by' => auth()->user()->name,
                    ]);
                }
            }
        }

        // Store BCheque Details data
        $bChequeDetail = BChequeDetail::create([
            'b_cheque_id' => $bCheque->id_b_cheque,
            'rent_recieve_amount' => $validatedData['rent_received'],
            'labour_amount' => $validatedData['labour'],
            'market_fees_amount' => $validatedData['market_fees'],
            'post_expense_amount' => $validatedData['post_expense'],
            'miscellaneous_expense_amount' => $validatedData['miscellaneous_expense'],
            'cash_amount' => $validatedData['cash'],
            'commission_rate' => $validatedData['commission_rate'],
            'commission_amount' => $validatedData['commission'],
            'else_more_amount' => $validatedData['more'],
            'details' => $validatedData['detail'],
            'total_bori' => $validatedData['total_bori'],
            'weight' => $validatedData['weight'],
            'total_amount' => $validatedData['total_amount'],
            'total_expanse_amount' => $validatedData['total_expanse_amount'],
            'save_amount' => $validatedData['save_amount'],
            'created_by' => auth()->user()->name,
        ]);

        // Update or Create SupplierAccount
        $supplierAccount = SupplierAccount::where('suppliers_id', $validatedData['suppliers'])->first();

        if ($supplierAccount) {
            // If the supplier account exists, update the debit amount
            $supplierAccount->debit += $validatedData['save_amount'];
            $supplierAccount->save();
        } else {
            // If no supplier account exists, create a new one
            SupplierAccount::create([
                'suppliers_id' => $validatedData['suppliers'],
                'debit' => $validatedData['save_amount'],
                'credit' => '0',
                'balance' => '0',
            ]);
        }

        // Redirect with success message
        return redirect()->route('b_cheque.list')->with('success', 'B-Cheque has been created successfully.');
    }

    public function edit($id)
    {
        $id = Crypt::decrypt($id);
        $b_cheque = BCheque::with(['items', 'details'])->findOrFail($id);
        $trucks = GoodReceiptTruck::with('goodReceipts.goodReceiptDetails')->get();
        $suppliers = Suppliers::all();
    
        return view('b_cheque.edit', compact('b_cheque', 'trucks', 'suppliers'));
    }

    public function update(Request $request, $id)
    {
        // Decrypt the ID
        $b_cheque_id = Crypt::decrypt($id);

        // Validate the request data
        $validatedData = $request->validate([
            'bCheck_date' => 'required|date',
            'pb_no' => 'required|string|max:255',
            'good_receipts_truck_id' => 'required|integer|exists:good_receipts_truck,id_truck',
            'suppliers' => 'required|integer|exists:suppliers,id_supplier',
            'bilty_no' => 'required|string|max:255',
            'detail' => 'nullable|string|max:255',
            'bCheck_status' => 'required|boolean',
            'marka.*' => 'nullable|string|max:255',
            'items_name.*' => 'nullable|string|max:255',
            'bori.*' => 'nullable|numeric',
            'weight.*' => 'nullable|numeric',
            'rate.*' => 'nullable|numeric',
            'amount.*' => 'nullable|numeric',
            'total_bori' => 'nullable|numeric',
            'total_weight' => 'nullable|numeric',
            'total_amount' => 'nullable|numeric',
            'total_expanse_amount' => 'nullable|numeric',
            'save_amount' => 'nullable|numeric',
            'commission_rate' => 'nullable|numeric|max:100',
            'commission' => 'nullable|numeric',
            'more' => 'nullable|numeric',
            'payment_details' => 'nullable|string|max:255',
            'rent_received' => 'nullable|numeric',
            'labour' => 'nullable|numeric',
            'market_fees' => 'nullable|numeric',
            'post_expense' => 'nullable|numeric',
            'miscellaneous_expense' => 'nullable|numeric',
            'cash' => 'nullable|numeric',
        ]);

        try {
            // Start Transaction
            DB::beginTransaction();

            // Find the b_cheque record
            $b_cheque = BCheque::findOrFail($b_cheque_id);
            // Update the main b_cheque details
            $b_cheque->update([
                'business_id' => auth()->user()->business_id,
                'good_receipts_truck_id' => $validatedData['good_receipts_truck_id'],
                'supplier_id' => $validatedData['suppliers'],
                'date' => $validatedData['bCheck_date'],
                'pb_no' => $validatedData['pb_no'],
                'bilty_no' => $validatedData['bilty_no'],
                'detail' => $validatedData['detail'],
                'status' => $validatedData['bCheck_status'],
                'created_by' => auth()->user()->name,
            ]);

            // Delete existing items
            $b_cheque->items()->delete();

            // Create new items
            foreach ($validatedData['marka'] as $index => $marka) {
                BChequeItem::create([
                    'b_cheque_id' => $b_cheque->id_b_cheque,
                    'marka' => $marka,
                    'item' => $validatedData['items_name'][$index],
                    'bori' => $validatedData['bori'][$index],
                    'weight' => $validatedData['weight'][$index],
                    'rate' => $validatedData['rate'][$index],
                    'amount' => $validatedData['amount'][$index],
                    'created_by' => auth()->user()->name,
                ]);
            }

            // Update or Create BChequeDetail
            $b_cheque_detail = $b_cheque->details()->first();

            if ($b_cheque_detail) {
                $b_cheque_detail->update([
                    'rent_recieve_amount' => $validatedData['rent_received'],
                    'labour_amount' => $validatedData['labour'],
                    'market_fees_amount' => $validatedData['market_fees'],
                    'post_expense_amount' => $validatedData['post_expense'],
                    'miscellaneous_expense_amount' => $validatedData['miscellaneous_expense'],
                    'cash_amount' => $validatedData['cash'],
                    'commission_rate' => $validatedData['commission_rate'],
                    'commission_amount' => $validatedData['commission'],
                    'else_more_amount' => $validatedData['more'],
                    'payment_details' => $validatedData['payment_details'],
                    'total_bori' => $validatedData['total_bori'],
                    'total_weight' => $validatedData['total_weight'],
                    'total_amount' => $validatedData['total_amount'],
                    'total_expanse_amount' => $validatedData['total_expanse_amount'],
                    'save_amount' => $validatedData['save_amount'],
                    'created_by' => auth()->user()->name,
                ]);
            } else {
                BChequeDetail::create([
                    'b_cheque_id' => $b_cheque->id_b_cheque,
                    'rent_recieve_amount' => $validatedData['rent_received'],
                    'labour_amount' => $validatedData['labour'],
                    'market_fees_amount' => $validatedData['market_fees'],
                    'post_expense_amount' => $validatedData['post_expense'],
                    'miscellaneous_expense_amount' => $validatedData['miscellaneous_expense'],
                    'cash_amount' => $validatedData['cash'],
                    'commission_rate' => $validatedData['commission_rate'],
                    'commission_amount' => $validatedData['commission'],
                    'else_more_amount' => $validatedData['more'],
                    'payment_details' => $validatedData['payment_details'],
                    'total_bori' => $validatedData['total_bori'],
                    'total_weight' => $validatedData['total_weight'],
                    'total_amount' => $validatedData['total_amount'],
                    'total_expanse_amount' => $validatedData['total_expanse_amount'],
                    'save_amount' => $validatedData['save_amount'],
                    'created_by' => auth()->user()->name,
                ]);
            }

            // Commit Transaction
            DB::commit();
            // Redirect with success message
            return redirect()->route('b_cheque.list')->with('success', 'B-Cheque has been updated successfully.');

        } catch (\Exception $e) {
            // Rollback Transaction
            DB::rollBack();

            // Redirect back with error message
            return redirect()->back()->with('error', 'An error occurred while updating the B-Cheque. Please try again.');
        }
    }

    public function destroy($id)
    {
        try {
            // Decrypt the ID
            $b_cheque_id = Crypt::decrypt($id);

            // Find the B-Cheque record
            $b_cheque = BCheque::findOrFail($b_cheque_id);

            // Delete associated items and details
            $b_cheque->items()->delete();
            $b_cheque->details()->delete();

            // Delete the main B-Cheque record
            $b_cheque->delete();

            // Redirect with success message
            return redirect()->route('b_cheque.list')->with('success', 'B-Cheque has been deleted successfully.');
        } catch (\Exception $e) {
            // Redirect back with error message
            return redirect()->back()->with('error', 'An error occurred while deleting the B-Cheque. Please try again.');
        }
    }

    public function getItemsByTruck($truckId)
    {
        $items = GoodReceiptDetail::where('truck_id', $truckId)->pluck('goods_name', 'id_grd')->toArray();
        $markas = GoodReceiptDetail::where('truck_id', $truckId)->pluck('marka')->unique()->toArray();

        return response()->json([
            'items' => $items,
            'markas' => $markas
        ]);
    }

    public function getItemsByMarka($truckId, $marka)
    {
        $items = GoodReceiptDetail::where('truck_id', $truckId)->where('marka', $marka)->pluck('goods_name', 'id_grd')->toArray();

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