<?php

namespace App\Services\Pwd;

use App\Models\Status;
use App\Models\RoadType;
use App\Models\Multifactor;
use App\Services\CommonService;
use App\Models\ServiceCredential;
use Illuminate\Support\Facades\DB;
use App\Models\Pwd\GrantingTelecom;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use App\Models\Pwd\GrantingTelecomDetails;
use App\Services\AapaleSarkarLoginCheckService;


class GrantingTelecomService
{
    protected $aapaleSarkarLoginCheckService;
    protected $commonservice;

    public function __construct(AapaleSarkarLoginCheckService $aapaleSarkarLoginCheckService, CommonService $commonservice)
    {
        $this->aapaleSarkarLoginCheckService = $aapaleSarkarLoginCheckService;
        $this->commonservice = $commonservice;
    }



    public function store($request)
    {
        DB::beginTransaction();

        try {
            $user = Auth::user();
            $request['user_id'] = Auth::id();
            $request['service_id'] = 2032;
            if ($request->hasFile('upload_prescribed_formats')) {
                $request['prescribed_docs'] = $request->file('upload_prescribed_formats')
                    ->store('MedicalHealth/potholes', 'public');
            }

            if ($request->hasFile('government_docs')) {
                $request['government_doc'] = $request->file('government_docs')
                    ->store('MedicalHealth/potholes', 'public');
            }
            if ($request->hasFile('tax_docs')) {
                $request['tax_doc'] = $request->file('tax_docs')
                    ->store('MedicalHealth/potholes', 'public');
            }
            if ($request->hasFile('outstanding_docs')) {
                $request['outstanding_doc'] = $request->file('outstanding_docs')
                    ->store('MedicalHealth/potholes', 'public');
            }

            if ($request->hasFile('gps_docs')) {
                $request['gps_doc'] = $request->file('gps_docs')
                    ->store('MedicalHealth/potholes', 'public');
            }
            $data = $request->except([
                'application_no',
                'roadtype',
                'startpoint',
                'endpoint',
                'road_length',
                'defect_factor'
            ]);

            $grantingTelecom = GrantingTelecom::create($data);

            if ($grantingTelecom) {
                $applicationNo = 'MBMC/' . $request['service_id'] . '/' . $grantingTelecom->id . '/' . date('dmY');
                $grantingTelecom->update(['application_no' => $applicationNo]);
            }
            foreach ($request->roadtype as $index => $type) {
                GrantingTelecomDetails::create([
                    'gratingtelecom_id' => $grantingTelecom->id,
                    'roadtype' => $type,
                    'startpoint' => $request->startpoint[$index],
                    'endpoint' => $request->endpoint[$index],
                    'length' => $request->road_length[$index],
                    'defect_factor' => $request->defect_factor[$index],
                ]);


                $status = Status::create([
                    'service_id' => 2032,
                    'department_id' => 10,
                    'table_id' => $grantingTelecom->id,
                    'user_id' => Auth::user()->id
                ]);

                $totalgrand = $this->calculateGrossTotal($grantingTelecom->id);

                $this->commonservice->store_approval_hierarchies($grantingTelecom, $user, $status);
            }

            DB::commit();
            return [true];
        } catch (\Exception $e) {
            DB::rollBack();
            return [false, $e->getMessage()];
        }
    }


    public function edit($id)
    {
        return GrantingTelecom::find($id);
    }



    // public function update_old($request, $id)
    // {
    //     DB::beginTransaction();

    //     try {
    //         $grantingTelecom = GrantingTelecom::findOrFail($id);
    //        // dd($grantingTelecom);
    //         $multidata = GrantingTelecomDetails::where('gratingtelecom_id', $grantingTelecom->id)->get();
            
    //         $status_id = $grantingTelecom->statuses()
    //             ->where('service_id', $grantingTelecom->service_id)
    //             ->first()?->id;
    //         $groupedData = [];
    //         $totalri = 0;
    //         $landrentTotal = 0;
    //         $totallength = 0;
    //         $combinedTotalRI = 0;
    //         $combinedLength = 0;
    //         $combinedSecurty = 0;
    //         $totalgrand = 0;
    //         $cgstamount = 0;
    //         $sgst = 0;

           


    //         if ($request->hasFile('upload_photos')) {
    //             $request['upload_photo'] = $request->file('upload_photos')
    //                 ->store('Grant/Telecom', 'public');
    //         }

    //         if ($request->hasFile('upload_prescribed_formats')) {
    //             $request['prescribed_docs'] = $request->file('upload_prescribed_formats')
    //                 ->store('MedicalHealth/potholes', 'public');
    //         }

    //         if ($request->hasFile('gps_docs')) {
    //             $request['gps_doc'] = $request->file('gps_docs')
    //                 ->store('MedicalHealth/potholes', 'public');
    //         }



    //         $user = Auth::user();
    //         $status = ($user->hasRole('JuniorEngineer')) ? 1 : 0;
    //         $totalgrand = $this->calculateGrossTotal($id);
    //         $updateData = $request->except(['roadtype', 'startpoint', 'endpoint', 'road_length', 'defect_factor', 'detail_ids']);
    //         $updateData['status'] = $status;
    //         $updateData['amount'] = $totalgrand;

    //        $updateData['start_date'] = $request->start_date; 
    //         $updateData['end_date'] = $request->end_date;
    //         $updateData['is_startdate_enddate'] = (!empty($updateData['start_date']) && !empty($updateData['end_date'])) ? 1 : 0;
                   
            

           

    //         $grantingTelecom->update_oldone($updateData);
            

    //         $existingIds = GrantingTelecomDetails::where('gratingtelecom_id', $id)->pluck('id')->toArray();
    //         $formIds = $request->detail_ids ?? [];

    //         if ($grantingTelecom->wasChanged('ward_area') && $status_id) {
    //             $resetResponse = $this->commonservice->reset_next_approvers($status_id)->getData(true);

    //             if (isset($resetResponse['status']) && $resetResponse['status'] === false) {
    //                 DB::rollBack();
    //                 return [
    //                     'status' => false,
    //                     'message' => $resetResponse['message'],
    //                 ];
    //             }
    //         }
    //         $idsToDelete = array_diff($existingIds, $formIds);
    //         GrantingTelecomDetails::whereIn('id', $idsToDelete)->delete();

    //         foreach ($request->roadtype as $index => $type) {
    //             $detailId = $formIds[$index] ?? null;

    //             $detailData = [
    //                 'gratingtelecom_id' => $grantingTelecom->id,
    //                 'roadtype' => $type,
    //                 'startpoint' => $request->startpoint[$index],
    //                 'endpoint' => $request->endpoint[$index],
    //                 'length' => $request->road_length[$index],
    //                 'defect_factor' => $request->defect_factor[$index],
    //             ];

    //             if ($detailId && in_array($detailId, $existingIds)) {
    //                 GrantingTelecomDetails::where('id', $detailId)->update($detailData);
    //             } else {
    //                 GrantingTelecomDetails::create($detailData);
    //             }
    //         }

    //         DB::commit();
    //         return true;
    //     } catch (\Exception $e) {
    //         DB::rollBack();
    //         Log::error('Granting Telecom update failed: ' . $e->getMessage());
    //         return false;
    //     }
    // }


    public function update($request, $id)
{
    DB::beginTransaction();

    try {
        $grantingTelecom = GrantingTelecom::findOrFail($id);

        // Status ID for next approver logic
        $status_id = $grantingTelecom->statuses()
            ->where('service_id', $grantingTelecom->service_id)
            ->first()?->id;

        // Handle file uploads
        if ($request->hasFile('upload_photos')) {
            $request['upload_photo'] = $request->file('upload_photos')
                ->store('Grant/Telecom', 'public');
        }
        if ($request->hasFile('upload_prescribed_formats')) {
            $request['prescribed_docs'] = $request->file('upload_prescribed_formats')
                ->store('MedicalHealth/potholes', 'public');
        }
        if ($request->hasFile('gps_docs')) {
            $request['gps_doc'] = $request->file('gps_docs')
                ->store('MedicalHealth/potholes', 'public');
        }

        // Set status based on role
        $user = Auth::user();
        $status = $user->hasRole('JuniorEngineer') ? 1 : 0;

        // Calculate total
        $totalgrand = $this->calculateGrossTotal($id);

        // Prepare update data
        $updateData = $request->except([
            'roadtype', 'startpoint', 'endpoint', 'road_length', 'defect_factor', 'detail_ids'
        ]);
        $updateData['status'] = $status;
        $updateData['amount'] = $totalgrand;
        $updateData['start_date'] = $request->start_date ?? null;
        $updateData['end_date'] = $request->end_date ?? null;
        $updateData['is_startdate_enddate'] = !empty($updateData['start_date']) && !empty($updateData['end_date']) ? 1 : 0;

        $grantingTelecom->update($updateData);

        // Handle existing detail IDs
        $existingIds = GrantingTelecomDetails::where('gratingtelecom_id', $id)->pluck('id')->toArray();
        $formIds = $request->detail_ids ?? [];

        // Reset next approvers if ward changed
        if ($grantingTelecom->wasChanged('ward_area') && $status_id) {
            $resetResponse = $this->commonservice->reset_next_approvers($status_id)->getData(true);
            if (!empty($resetResponse['status']) && $resetResponse['status'] === false) {
                DB::rollBack();
                return [
                    'status' => false,
                    'message' => $resetResponse['message'],
                ];
            }
        }

        // Delete removed details
        $idsToDelete = array_diff($existingIds, $formIds);
        if (!empty($idsToDelete)) {
            GrantingTelecomDetails::whereIn('id', $idsToDelete)->delete();
        }

        // Add or update details only if roadtype exists and is array
        $roadtypes = $request->roadtype ?? [];
        if (is_array($roadtypes) && count($roadtypes) > 0) {
            $startpoints = $request->startpoint ?? [];
            $endpoints   = $request->endpoint ?? [];
            $lengths     = $request->road_length ?? [];
            $defects     = $request->defect_factor ?? [];

            foreach ($roadtypes as $index => $type) {
                $detailId = $formIds[$index] ?? null;

                $detailData = [
                    'gratingtelecom_id' => $grantingTelecom->id,
                    'roadtype' => $type,
                    'startpoint' => $startpoints[$index] ?? null,
                    'endpoint' => $endpoints[$index] ?? null,
                    'length' => $lengths[$index] ?? null,
                    'defect_factor' => $defects[$index] ?? null,
                ];

                if ($detailId && in_array($detailId, $existingIds)) {
                    GrantingTelecomDetails::where('id', $detailId)->update($detailData);
                } else {
                    GrantingTelecomDetails::create($detailData);
                }
            }
        }

        DB::commit();
        return true;

    } catch (\Exception $e) {
        DB::rollBack();
        Log::error('Granting Telecom update failed: ' . $e->getMessage());
        return false;
    }
}



    // public static function calculateGrossTotal_old($id)
    // {
    //     $data = GrantingTelecom::findOrFail($id);
    //     $multidata = GrantingTelecomDetails::where('gratingtelecom_id', $data->id)->get();
    //     $grossTotal = 0;
    //     foreach ($multidata as $item) {
    //         $roadtype = RoadType::find($item->roadtype);
    //         $multifactor = Multifactor::find($item->defect_factor);

    //         $length = (float) $item->length;
    //         $rate = $roadtype ? (float) $roadtype->rate : 0;
    //         $year = $multifactor ? (float) $multifactor->year : 1;

    //         $riCharge = $length * $rate * $year;
    //         $landrent = $length * 200;

    //         $noofchamber = (int) $data->no_chamber;
    //         $chamberfee = $noofchamber * 30000;
    //         $totalBeforeGst = $riCharge + $landrent + $chamberfee;
    //         $cgst = $totalBeforeGst * 0.09;
    //         $sgst = $totalBeforeGst * 0.09;
    //         $gstTotal = $cgst + $sgst;
    //         $deposit = $riCharge * 0.10;

    //         $grandTotal = $totalBeforeGst + $gstTotal + $deposit;

    //         $grossTotal += $grandTotal;
    //     }
    //     $data->amount = $grossTotal;
    //     $data->save();
    //     return $grossTotal;
    // }



    public static function calculateGrossTotal($id)
{
    $data = GrantingTelecom::findOrFail($id);
        $multidata = GrantingTelecomDetails::where('gratingtelecom_id', $data->id)->get();

    if ($multidata->isEmpty()) {
        return 0;
    }

    // CHAMBER FEE (only once for entire calculation)
    $noofchamber = (int) $data->no_chamber;
    $chamberfee = $noofchamber * 30000;

    // Group by Road Type (same as Blade)
    $grouped = $multidata->groupBy('roadtype');

    $grossTotal = 0;
    $roadTypeCounter = 0;

    foreach ($grouped as $roadtypeId => $groupItems) {

        $roadTypeCounter++;

        // Chamber fee applies only to FIRST road type
        $effectiveChamberFee = ($roadTypeCounter == 1) ? $chamberfee : 0;

        $itemCounter = 0;

        foreach ($groupItems as $item) {
            $itemCounter++;

            $roadtype = RoadType::find($item->roadtype);
            $multifactor = Multifactor::find($item->defect_factor);

            $length = (float) $item->length;
            $rate = $roadtype ? (float) $roadtype->rate : 0;
            $year = $multifactor ? (float) $multifactor->year : 1;

            $riCharge = $length * $rate * $year;
            $landrent = $length * 200;

            // chamber fee only for the FIRST ITEM of the FIRST ROAD TYPE
            $itemChamberFee = ($itemCounter == 1) ? $effectiveChamberFee : 0;

            // Total before GST
            $totalBeforeGst = $riCharge + $landrent + $itemChamberFee;

            $cgst = $totalBeforeGst * 0.09;
            $sgst = $totalBeforeGst * 0.09;
            $gstTotal = $cgst + $sgst;

            // Security deposit 10% only on RI charges
            $deposit = $riCharge * 0.10;

            // Final Grand Total for this row
            $grandTotal = $totalBeforeGst + $gstTotal + $deposit;

            $grossTotal += $grandTotal;
        }
    }

    // Save
    $data->amount = $grossTotal;
    $data->save();

    return $grossTotal;
}



}
