<?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' => 'required|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->opening_date = $validatedData['opening_date'] ? \Carbon\Carbon::createFromFormat('d/m/Y', $validatedData['opening_date'])->format('Y-m-d') : null;
        
        $supplier->save();

        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\Supplier  $supplier
     * @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)
    {
        $dec_id = \Crypt::decrypt($id);

        // Fetch supplier and associated brands
        $supplier = Suppliers::where('id_supplier', $dec_id)->first();

        // Retrieve the brands associated with the supplier
        $supplier_brands = DB::table('supplier_brand')
            ->leftJoin('brands', 'supplier_brand.brand_id', '=', 'brands.id_brands')
            ->leftJoin('suppliers', 'supplier_brand.supplier_id', '=', 'suppliers.id_supplier')
            ->where('suppliers.id_supplier', $dec_id)
            ->select('supplier_brand.*', 'suppliers.supplier_name', 'brands.brands_name')
            ->get();


        // dd($supplier_brands);

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

    public function brand_create($id)
    {
        $dec_id = \Crypt::decrypt($id);
        $supplier = Suppliers::where('id_supplier', $dec_id)->first();
        $brands = Brands::all();
        return view('supplier.brands_create', compact('brands', 'supplier'));
    }

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

        $exists = SupplierBrand::where('brand_id', $request->brand)
            ->where('supplier_id', $request->supplier)
            ->exists();

        if ($exists) {
            session()->flash('warning', 'Brand already assigned to supplier.');
        } else {
            $store = new SupplierBrand();
            $store->brand_id = $request->brand;
            $store->supplier_id = $request->supplier;
            $store->save();
            session()->flash('success', 'Brand 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'));
    }
}
