<?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\Purchaser;
use App\PurchaserAccount;
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 PurchaserController extends Controller
{

    protected string $module = 'Purchasers';

    public function __construct()
    {
        $module = $this->module;

        $this->middleware("permission:$module list")->only(['index']);
        $this->middleware("permission:$module view")->only(['show']);
        $this->middleware("permission:$module add")->only(['create', 'store']);
        $this->middleware("permission:$module edit")->only(['edit', 'update']);
        $this->middleware("permission:$module delete")->only(['destroy']);
    }
    public function index()
    {
        $purchasers = Purchaser::all();
        return view('purchaser.index', compact('purchasers'));
    }


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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        // dd($request->status);
        $validatedData = $request->validate([
            'opening_date' => 'nullable|date',
            'purchaser_name' => 'required|string|max:255|unique:purchasers,purchaser_name',
            'purchaser_name_urdu' => 'nullable|string|max:255|unique:purchasers,purchaser_name_urdu',
            'email' => 'nullable|email|max:255',
            'contact_person' => 'nullable|string|max:255',
            'address' => 'nullable|string|max:255',
            'purchaser_address_urdu' => 'nullable|string|max:255',
            'city' => 'nullable',
            'phone_1' => 'nullable|max:15',
            'phone_2' => 'nullable|max:15',
            'website' => 'nullable|url|max:255',
            'status' => 'nullable|in:0,1',
            'blance_dr' => 'nullable|string',
            'blance_cr' => 'nullable|string',
        ]);

        // Create new Purchaser
        $purchaser = new Purchaser();
        $purchaser->purchaser_name = $validatedData['purchaser_name'];
        $purchaser->purchaser_name_urdu = $validatedData['purchaser_name_urdu'] ?? null;
        $purchaser->purchaser_email = $validatedData['email'] ?? null;
        $purchaser->purchaser_address = $validatedData['address'] ?? null;
        $purchaser->purchaser_address_urdu = $validatedData['purchaser_address_urdu'] ?? null;
        $purchaser->purchaser_city = $validatedData['city'] ?? null;
        $purchaser->contact_person = $validatedData['contact_person'] ?? null;
        $purchaser->phone_1 = $validatedData['phone_1'] ?? null;
        $purchaser->phone_2 = $validatedData['phone_2'] ?? null;
        $purchaser->website = $validatedData['website'] ?? null;
        $purchaser->status = $request->status ?? 1;
        $purchaser->opening_bal_dr = $validatedData['blance_dr'] ?? null;
        $purchaser->opening_bal_cr = $validatedData['blance_cr'] ?? null;
        $purchaser->opening_date = $validatedData['opening_date'] ?? null;

        $purchaser->save();

        // if (!empty($validatedData['blance_dr']) || !empty($validatedData['blance_cr'])) {
        //     $purchaserAccount = PurchaserAccount::where('purchaser_id', $purchaser->id_purchaser)->first();
        //     // $accountData = explode('|', $validatedData['account_info']);
        //     // $accountName = $accountData[0] ?? null;
        //     // $accountNo = $accountData[1] ?? null;
        //     $accountName = 'Payable to Purchasers';
        //     $accountNo = '28';

        //     if ($purchaserAccount) {
        //         // Update existing purchaser account
        //         $purchaserAccount->account_name = $accountName;
        //         $purchaserAccount->account_no = $accountNo;
        //         $purchaserAccount->debit += $validatedData['blance_dr'] ?? 0;
        //         $purchaserAccount->credit += $validatedData['blance_cr'] ?? 0;
        //         $purchaserAccount->balance = $purchaserAccount->debit - $purchaserAccount->credit;
        //         $purchaserAccount->save();
        //     } else {
        //         // Create a new purchaser account if it doesn't exist
        //         $dataToCreate = [
        //             'purchaser_id' => $purchaser->id_purchaser,
        //             '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),
        //         ];
        //         PurchaserAccount::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->voucher_date = $validatedData['opening_date'];
        //         $voucherDebit->transaction_acc_no = '27';
        //         $voucherDebit->transaction_acc_name = 'Payable to Purchasers';
        //         $voucherDebit->business_partner_type = 'Purchaser';
        //         $voucherDebit->partner_name = $validatedData['purchaser_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->voucher_date = $validatedData['opening_date'];
        //         $voucherCredit->transaction_acc_no = '27';
        //         $voucherCredit->transaction_acc_name = 'Payable to Purchasers';
        //         $voucherCredit->business_partner_type = 'Purchaser';
        //         $voucherCredit->partner_name = $validatedData['purchaser_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 = 'Purchaser';  // 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
        // }


        if ($request->ajax()) {
            $getPurchaser = Purchaser::all()->toArray();
            return response()->json([
                'success' => true,
                'message' => 'New Purchaser Added Successfully!',
                'purchasers' =>  $getPurchaser,
            ]);
        }
        session()->flash('success', "New Purchaser Added Successfully");
        return redirect('purchaser/list');
    }



    public function edit($id)
    {
        try {
            $dec_id = \Crypt::decrypt($id);
        } catch (DecryptException $e) {
            return redirect()->back()->withErrors('Invalid ID');
        }

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

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


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

        // Validate the incoming request data
        $request->validate([
            'purchaser_opening_date'      => 'nullable|date',
            'purchaser_name'          => 'required|string|max:255',
            'purchaser_name_urdu'     => 'nullable|string|max:255',
            'email'                  => 'nullable|email|max:255',
            'contact_person'         => 'nullable|string|max:255',
            'address'                => 'nullable|string|max:255',
            'purchaser_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 purchaser by ID
            $purchaser = Purchaser::findOrFail($id_purchaser);

            // Update purchaser data
            $purchaser->opening_date          = $request->customer_ope_date;
            $purchaser->purchaser_name         = $request->purchaser_name;
            $purchaser->purchaser_name_urdu    = $request->purchaser_name_urdu;
            $purchaser->purchaser_email        = $request->email;
            $purchaser->contact_person        = $request->contact_person;
            $purchaser->purchaser_address      = $request->address;
            $purchaser->purchaser_address_urdu = $request->purchaser_address_urdu;
            $purchaser->purchaser_city         = $request->city;
            $purchaser->phone_1               = $request->phone_1;
            $purchaser->phone_2               = $request->phone_2;
            $purchaser->website               = $request->website;
            $purchaser->status                = $request->status;
            $purchaser->opening_bal_dr        = $request->blance_dr;
            $purchaser->opening_bal_cr        = $request->blance_cr;

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

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

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


    public function brand($id)
    {
        $purchaserId = \Crypt::decrypt($id);
        $purchaser = Purchaser::with('brands')->findOrFail($purchaserId);

        return view('purchaser.purchaser_brands', compact('purchaser', 'purchaserId'));
    }

    public function brand_create($id)
    {
        $purchaserId = \Crypt::decrypt($id);
        $purchaser = Purchaser::where('id_purchaser', $purchaserId)->first();
        $brands = Brands::all();

        return view('purchaser.brands_create', compact('brands', 'purchaser', 'purchaserId'));
    }

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

        $purchaserId = $request->purchaser;

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

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

        return redirect()->back();
    }


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

    // public function view($id)
    // {
    //     $purchaser = Suppliers::all();
    //     $dec_id = Crypt::decrypt($id);
    //     $view = Suppliers::where('id_purchaser', $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('purchaser.view', compact('purchaser', 'view'));
    // }

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

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