<?php

namespace App\Http\Controllers;

use App\City;
use App\Brands;
use App\Suppliers;
use App\SupplierAccount;
use App\SupplierSaleOrder;
use App\SupplierPaymentHistory;
use App\Http\Controllers\Controller;
use App\SupplierBrand;
use App\TransactionAccount;
use App\Voucher;
use App\VouchersUniqueNumber;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;

class SupplierController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $suppliers = Suppliers::all();
        return view('supplier.index', compact('suppliers'));
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $cities = City::all();
        $supplier = Suppliers::all();
        $accounts = TransactionAccount::where('transaction_account_name', '=',  'Payable to Suppliers')->get();

        return view('supplier.create', compact('supplier', 'accounts', 'cities'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'opening_date' => 'nullable|date',
            'supplier_name' => 'required|string|max:255',
            'supplier_name_urdu' => 'nullable|string|max:255',
            'email' => 'nullable|email|max:255',
            'contact_person' => 'nullable|string|max:255',
            'address' => 'nullable|string|max:255',
            'supplier_address_urdu' => 'nullable|string|max:255',
            'city' => 'nullable',
            'phone_1' => 'nullable|string|max:15',
            'phone_2' => 'nullable|string|max:15',
            'website' => 'nullable|url|max:255',
            'status' => 'nullable|in:0,1',
            'blance_dr' => 'nullable|string',
            'blance_cr' => 'nullable|string',
        ]);

        // Create new Supplier
        $supplier = new Suppliers();
        $supplier->supplier_name = $validatedData['supplier_name'];
        $supplier->supplier_name_urdu = $validatedData['supplier_name_urdu'] ?? null;
        $supplier->supplier_email = $validatedData['email'] ?? null;
        $supplier->supplier_address = $validatedData['address'] ?? null;
        $supplier->supplier_address_urdu = $validatedData['supplier_address_urdu'] ?? null;
        $supplier->supplier_city = $validatedData['city'] ?? null;
        $supplier->contact_person = $validatedData['contact_person'] ?? null;
        $supplier->phone_1 = $validatedData['phone_1'] ?? null;
        $supplier->phone_2 = $validatedData['phone_2'] ?? null;
        $supplier->website = $validatedData['website'] ?? null;
        $supplier->status = $request->status;
        $supplier->opening_bal_dr = $validatedData['blance_dr'] ?? null;
        $supplier->opening_bal_cr = $validatedData['blance_cr'] ?? null;
        $supplier->opening_date = $validatedData['opening_date'] ?? null;

        $supplier->save();

        if (!empty($validatedData['blance_dr']) || !empty($validatedData['blance_cr'])) {
            $supplierAccount = SupplierAccount::where('suppliers_id', $supplier->id_supplier)->first();
            // $accountData = explode('|', $validatedData['account_info']);
            // $accountName = $accountData[0] ?? null;
            // $accountNo = $accountData[1] ?? null;
            $accountName = 'Payable to Suppliers';
            $accountNo = '27';

            if ($supplierAccount) {
                // Update existing supplier account
                $supplierAccount->account_name = $accountName;
                $supplierAccount->account_no = $accountNo;
                $supplierAccount->debit += $validatedData['blance_dr'] ?? 0;
                $supplierAccount->credit += $validatedData['blance_cr'] ?? 0;
                $supplierAccount->balance = $supplierAccount->debit - $supplierAccount->credit;
                $supplierAccount->save();
            } else {
                // Create a new supplier account if it doesn't exist
                $dataToCreate = [
                    'suppliers_id' => $supplier->id_supplier,
                    'account_name' => $accountName,
                    'account_no' => $accountNo,
                    'debit' => $validatedData['blance_dr'] ?? 0,
                    'credit' => $validatedData['blance_cr'] ?? 0,
                    // 'balance' => ($validatedData['blance_dr'] ?? 0) - ($validatedData['blance_cr'] ?? 0),
                    'balance' => (float)str_replace(',', '', $validatedData['blance_dr'] ?? 0) - (float)str_replace(',', '', $validatedData['blance_cr'] ?? 0),
                ];
                SupplierAccount::create($dataToCreate);
            }

            $uniqueVoucherNumber = 'JV-' . str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);

            // Create a new VouchersUniqueNumber record
            $voucherUniqueNumber = new VouchersUniqueNumber();
            $voucherUniqueNumber->voucher_type = 'Journal Voucher';
            $voucherUniqueNumber->voucher_number = $uniqueVoucherNumber;
            $voucherUniqueNumber->save();
            // Create vouchers based on the presence of debit and credit values

            // Voucher for Debit
            if (!empty($validatedData['blance_dr'])) {

                $voucherDebit = new Voucher();
                $voucherDebit->vouchers_unique_number_id = $voucherUniqueNumber->id_vouchers_unique_number;
                $voucherDebit->date = $validatedData['opening_date'];
                $voucherDebit->transaction_acc_no = '27';
                $voucherDebit->transaction_acc_name = 'Payable to Suppliers';
                $voucherDebit->business_partner_type = 'Supplier';
                $voucherDebit->partner_name = $validatedData['supplier_name'];
                $voucherDebit->debit = $validatedData['blance_dr'];
                $voucherDebit->credit = 0;
                // dd($voucherDebit);
                $voucherDebit->save();
            }

            // Voucher for Credit
            if (!empty($validatedData['blance_cr'])) {
                $uniqueVoucherNumber = 'JV-' . str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);

                // Create a new VouchersUniqueNumber record

                $voucherCredit = new Voucher();
                $voucherCredit->vouchers_unique_number_id = $voucherUniqueNumber->id_vouchers_unique_number;
                $voucherCredit->date = $validatedData['opening_date'];
                $voucherCredit->transaction_acc_no = '27';
                $voucherCredit->transaction_acc_name = 'Payable to Suppliers';
                $voucherCredit->business_partner_type = 'Supplier';
                $voucherCredit->partner_name = $validatedData['supplier_name'];
                $voucherCredit->debit = 0;
                $voucherCredit->credit = $validatedData['blance_cr'];
                // dd($voucherCredit);
                $voucherCredit->save();
            }
            // Generate unique voucher number
            // $uniqueVoucherNumber = 'JV-' . str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);

            // // Create a new VouchersUniqueNumber record
            // $voucherUniqueNumber = new VouchersUniqueNumber();
            // $voucherUniqueNumber->voucher_type = 'Journal Voucher';
            // $voucherUniqueNumber->voucher_number = $uniqueVoucherNumber;
            // $voucherUniqueNumber->save();

            // // Create the voucher and associate it with the VouchersUniqueNumber
            // $voucher = new Voucher();
            // $voucher->vouchers_unique_number_id = $voucherUniqueNumber->id_vouchers_unique_number;
            // $voucher->date = $validatedData['opening_date'];  // Date for the voucher
            // $voucher->account_no = $accountNo;  // Account number from account_info
            // $voucher->account_title = $accountName;  // Account name from account_info
            // $voucher->business_partner_type = 'Supplier';  // Fixed value for partner type
            // $voucher->debit = $validatedData['blance_dr'] ?? 0;
            // $voucher->credit = $validatedData['blance_cr'] ?? 0;
            // $voucher->status = 'Posted';
            // $voucher->save();

            // Redirect to the voucher print route, passing the id of VouchersUniqueNumber
        }

        session()->flash('success', "New Supplier Added Successfully");
        return redirect('supplier/list');
    }

    public function print($id)
    {
        $id = Crypt::decrypt($id);

        $vouchersNumber = VouchersUniqueNumber::with(['vouchers' => function ($query) {
            $query->where('business_partner_type', 'Supplier');
        }])->where('id_vouchers_unique_number', $id)->first();

        if (!$vouchersNumber) {
            abort(404, 'Voucher not found.');
        }

        $voucherSingle = $vouchersNumber->vouchers->first();

        return view('voucher.view', compact('vouchersNumber', 'voucherSingle'));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Supplier  $supplier
     * @return \Illuminate\Http\Response
     */
    public function show(Supplier $supplier)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Supplier  $supplier
     * @return \Illuminate\Http\Response
     */
    // public function edit($id)
    // {
    //     $dec_id = \Crypt::decrypt($id);
    //     $edit = Suppliers::where('id_supplier', $dec_id)->first();
    //     $cities = City::all();
    //     // dd($edit);
    //     // $edit = currency_exchange_rate::all();

    //     return view('supplier.edit', compact('edit', 'cities'));
    // }
    public function edit($id)
    {
        try {
            $dec_id = \Crypt::decrypt($id);
        } catch (DecryptException $e) {
            // Handle decryption failure (e.g., redirect or show error)
            return redirect()->back()->withErrors('Invalid ID');
        }

        $edit = Suppliers::where('id_supplier', $dec_id)->first();
        $cities = City::all();

        return view('supplier.edit', compact('edit', 'cities'));
    }


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

        // Validate the incoming request data
        $request->validate([
            'supplier_opening_date'      => 'nullable|date',
            'supplier_name'          => 'required|string|max:255',
            'supplier_name_urdu'     => 'nullable|string|max:255',
            'email'                  => 'nullable|email|max:255',
            'contact_person'         => 'nullable|string|max:255',
            'address'                => 'nullable|string|max:255',
            'supplier_address_urdu'  => 'nullable|string|max:255',
            'city'                   => 'nullable',
            'phone_1'                => 'nullable|string|max:15',
            'phone_2'                => 'nullable|string|max:15',
            'website'                => 'nullable|url|max:255',
            'status'                 => 'nullable|in:0,1',
            'blance_dr'              => 'nullable|numeric',
            'blance_cr'              => 'nullable|numeric',
        ]);

        try {
            // Find the supplier by ID
            $supplier = Suppliers::findOrFail($id_supplier);

            // Update supplier data
            $supplier->opening_date          = $request->customer_ope_date;
            $supplier->supplier_name         = $request->supplier_name;
            $supplier->supplier_name_urdu    = $request->supplier_name_urdu;
            $supplier->supplier_email        = $request->email;
            $supplier->contact_person        = $request->contact_person;
            $supplier->supplier_address      = $request->address;
            $supplier->supplier_address_urdu = $request->supplier_address_urdu;
            $supplier->supplier_city         = $request->city;
            $supplier->phone_1               = $request->phone_1;
            $supplier->phone_2               = $request->phone_2;
            $supplier->website               = $request->website;
            $supplier->status                = $request->status;
            $supplier->opening_bal_dr        = $request->blance_dr;
            $supplier->opening_bal_cr        = $request->blance_cr;

            // Save the updated supplier data
            $supplier->save();

            // Redirect back with success message
            return redirect()->route('supplier.list')->with('success', 'Supplier updated successfully.');
        } catch (\Exception $e) {
            // Handle any errors that may occur
            return redirect()->back()->with('error', 'Something went wrong while updating the supplier.')->withInput();
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Suppliers  $suppliers
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        // $dec_id = Crypt::decrypt($id);
        $edit_vendor = Suppliers::where('id_supplier', $id)->delete();
        // dd($edit_vendor);
        session()->flash('success', "Deleted Successfully");
        return redirect()->back();
    }


    public function brand($id)
    {
        $supplierId = \Crypt::decrypt($id);
        $supplier = Suppliers::with('brands')->findOrFail($supplierId);

        return view('supplier.supplier_brands', compact('supplier', 'supplierId'));
    }

    public function brand_create($id)
    {
        $supplierId = \Crypt::decrypt($id);
        $supplier = Suppliers::where('id_supplier', $supplierId)->first();
        $brands = Brands::all();

        return view('supplier.brands_create', compact('brands', 'supplier', 'supplierId'));
    }

    public function brand_store(Request $request)
    {
        $request->validate([
            'brand' => 'required|array',
            'brand.*' => 'exists:brands,id_brands',
            'supplier' => 'required|exists:suppliers,id_supplier',
        ]);

        $supplierId = $request->supplier;

        foreach ($request->brand as $brandId) {
            $exists = SupplierBrand::where('brand_id', $brandId)
                ->where('supplier_id', $supplierId)
                ->exists();
            if (!$exists) {
                $store = new SupplierBrand();
                $store->brand_id = $brandId;
                $store->supplier_id = $supplierId;
                $store->save();
            }
        }

        session()->flash('success', 'Brands assigned to supplier successfully.');

        return redirect()->back();
    }


    public function brand_destroy($id)
    {
        $supplier_brand = SupplierBrand::find($id);
        if ($supplier_brand) {
            $supplier_brand->delete();
            session()->flash('warning', "Supplier's Brand Removed");
        } else {
            session()->flash('error', "Supplier's Brand Not Found");
        }
        return redirect()->back();
    }

    // public function view($id)
    // {
    //     $supplier = Suppliers::all();
    //     $dec_id = Crypt::decrypt($id);
    //     $view = Suppliers::where('id_supplier', $dec_id)->first();
    //     // $inquiry1 = inquiry::where('customer_id', $view->id_customers)->get();
    //     // $quotations = [];
    //     // $inquiry = inquiry::select('inquiry.*', 'inquirytypes.type_id', 'inquirytypes.type_name')
    //     //     ->join('inquirytypes', 'inquirytypes.type_id', 'inquiry.id_inquiry')
    //     //     // ->join('users' ,'users.id' , 'inquiry.saleperson' )
    //     //     ->where('customer_id', $view->id_customers)->get();

    //     //     foreach ($inquiry as $in) {
    //     //         $quotation = quotation::where('inquiry_id', $in->id_inquiry)->get();
    //     //     if ($quotation) {
    //     //         $quotations[] = $quotation;
    //     //     }
    //     //         }

    //     // dd($quotations);
    //     return view('supplier.view', compact('supplier', 'view'));
    // }

    public function view($id)
    {
        $dec_id = Crypt::decrypt($id);
        $supplier = Suppliers::with(['accounts', 'saleOrders', 'paymentHistory'])->where('id_supplier', $dec_id)->first();

        return view('supplier.view', compact('supplier'));
    }
}
