<?php

namespace App\Http\Controllers;

use App\Brands;
use App\Suppliers;
use App\SupplierAccount;
use App\SupplierSaleOrder;
use App\SupplierPaymentHistory;
use App\Http\Controllers\Controller;
use App\SupplierBrand;
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()
    {
        $supplier = Suppliers::all();
        return view('supplier.create', compact('supplier'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
    */
    public function store(Request $request)
    {
        // Validate incoming request data
        $validatedData = $request->validate([
            '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',
            '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|between:0,9999999999999.99',
            'blance_cr' => 'nullable|numeric|between:0,9999999999999.99',
            'opening_date' => 'nullable',
        ]);

        // 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->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 = $validatedData['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'])){

            // Update or Create SupplierAccount
            $supplierAccount = SupplierAccount::where('suppliers_id', $supplier->id_supplier)->first();

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

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

    /**
     * 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();
        // dd($edit);
        // $edit = currency_exchange_rate::all();

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

    public function update(Request $request, $id)
    {
        $dec_id = \Crypt::decrypt($id);
        $update = Suppliers::where('id_supplier', $dec_id)->first();
        $update->supplier_name = $request->supplier_name;
        $update->supplier_name_urdu = $request->supplier_name_urdu;
        $update->supplier_email = $request->email;
        $update->supplier_address = $request->address;
        $update->supplier_address_urdu = $request->supplier_address_urdu;
        $update->contact_person = $request->contact_person;
        $update->phone_1 = $request->phone_1;
        $update->phone_2 = $request->phone_2;
        $update->website = $request->website;
        $update->status = $request->status;
        $update->opening_bal_dr = $request->blance_dr;
        $update->opening_bal_cr = $request->blance_cr;
        $update->opening_date = $request->opening_date;
        $update->save();
        session()->flash('info', "Supplier Updated Successfully");

        return redirect('supplier/list');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Suppliers  $suppliers
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $Supplier = Suppliers::find($id);
        $Supplier->delete();
        session()->flash('warning', "Supplier Removed");
        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'));
    }
}
