<?php

namespace App\Http\Controllers;

use App\SaleRateApplication;
use App\Http\Controllers\Controller;
use App\GoodReceiptTruck;
use App\Sale;
use App\Suppliers;
use App\SalesItemDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;

class SalesRateApplicationController extends Controller
{
    protected string $module = 'Sales Rate Application';

    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()
    {
        // $sales = SaleRateApplication::with(['salesItemsDetails', 'salesPerBoriWeight', 'customer', 'goodReceiptTruck', 'goodReceiptTruck.goodReceiptDetails'])->get();
        return view('sale_rate_application.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $soldTrucks = Sale::whereHas('salesItemsDetails')
            ->with('goodReceiptTruck')
            ->get()
            ->pluck('goodReceiptTruck')
            ->unique('id_truck');

        $sales = Sale::with([
            'salesItemsDetails',
            'salesPerBoriWeight',
            'customer',
            'goodReceiptTruck',
            'goodReceiptTruck.goodReceiptDetails',
            'goodReceiptTruck.goodReceiptDetails.goodReceipt.supplier'
        ])->get();

        $suppliers = Suppliers::all();

        return view('sale_rate_application.create', compact('soldTrucks', 'sales', 'suppliers'));
    }

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

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\SaleRateApplication  $saleRateApplication
     * @return \Illuminate\Http\Response
     */
    public function edit(SaleRateApplication $saleRateApplication)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\SaleRateApplication  $saleRateApplication
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, SaleRateApplication $saleRateApplication)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\SaleRateApplication  $saleRateApplication
     * @return \Illuminate\Http\Response
     */
    public function destroy(SaleRateApplication $saleRateApplication)
    {
        //
    }

    public function salesRateApply(Request $request)
    {
        // Validate the form data
        $validatedData = $request->validate([
            'sale_rate_date' => 'required|date',
            'custom_price' => 'required|string',
            'salesDeId.*' => 'required|integer',
            'mainCate.*' => 'required|string|max:255',
            'parentCate.*' => 'required|string|max:255',
            'childCate.*' => 'required|string|max:255',
            'marka.*' => 'required|string|max:255',
            'bori.*' => 'required|string',
            'weight.*' => 'required|string',
            'rate.*' => 'required|string',
            'amount.*' => 'required|string',
        ]);

        $price = str_replace(',', '', $validatedData['custom_price']);

        // Update the sales item details
        if (!empty($validatedData['salesDeId'])) {
            foreach ($validatedData['salesDeId'] as $index => $salesDeId) {
                if ($salesDeId && isset($validatedData['mainCate'][$index])) {
                    SalesItemDetail::where('id_sid', $salesDeId)
                        ->update([
                            'rate' => $price,
                            'amount' => $validatedData['amount'][$index],
                            'rate_applied_on' => $validatedData['sale_rate_date'],
                        ]);
                }
            }
        }

        // Fetch unique trucks that have associated sales items details
        $soldTrucks = Sale::whereHas('salesItemsDetails')
            ->with('goodReceiptTruck')
            ->get()
            ->pluck('goodReceiptTruck')
            ->unique('id_truck'); // Ensure unique trucks by truck ID

        // Fetch sales with related data (eager load relationships to optimize queries)
        $sales = Sale::with([
            'salesItemsDetails',
            'salesPerBoriWeight',
            'customer',
            'goodReceiptTruck',
            'goodReceiptTruck.goodReceiptDetails',
            'goodReceiptTruck.goodReceiptDetails.goodReceipt.supplier'
        ])->get();

        $suppliers = Suppliers::all();

        return redirect()->route('sale_rate.create')
            ->with(['soldTrucks' => $soldTrucks, 'sales' => $sales, 'suppliers' => $suppliers, 'success' => 'Sales Rate Applied Successfully.']);
    }
}
