<?php

namespace App\Http\Controllers\ConstructionDepartment;

use Carbon\Carbon;
use App\Models\Fees;
use App\Models\User;
use App\Models\Ward;
use App\Models\Status;
use App\Models\RoadType;
use App\Models\SbiPayment;
use App\Models\Multifactor;
use App\Models\ServiceName;
use Illuminate\Support\Str;
use App\Models\WaterPayment;
use Illuminate\Http\Request;
use App\Models\AdvertisementTypes;
use Illuminate\Support\Facades\DB;
use App\Models\ApprovalHierarchies;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Barryvdh\Snappy\Facades\SnappyPdf;
use Database\Seeders\RoadTypeRateSeeder;
use App\Models\MedicalHealth\GrantNursingLicense;
use App\Models\CityStructure\CityStructurePartMap;
use App\Models\MedicalHealth\RenewalNursingLicense;
use App\Models\CityStructure\CityStructureZoneCertificate;
use App\Services\ConstructionDepartment\RoadCuttingService;
use App\Models\ConstructionDepartment\ConstructionRoadCutting;
use App\Http\Requests\ConstructionDepartment\RoadCutting\CreateRequest;
use App\Http\Requests\ConstructionDepartment\RoadCutting\UpdateRequest;
use App\Models\ConstructionDepartment\ConstructionRoadCuttingRoadDetail;


class RoadCuttingPermissionController extends Controller
{
    protected $RoadCuttingService;

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

    public function create()
    {
        $options = Ward::get();
        $roadtype = RoadType::get();
        $multifactor = Multifactor::get();
       

        return view('construction-department.road-cutting.create', compact('options', 'roadtype', 'multifactor'));
    }

    public function store(CreateRequest $request)
    {
        $RoadCuttingService = $this->RoadCuttingService->store($request);

        if ($RoadCuttingService) {
            return response()->json([
                'success' => 'Application Submitted Successfully'
            ]);
        } else {
            return response()->json([
                'error' => 'Something went wrong, please try again'
            ]);
        }
    }

    public function edit(string $id)
    {
        $id = decrypt($id);
        $data = ConstructionRoadCutting::findOrFail($id);
        $multidata = ConstructionRoadCuttingRoadDetail::Where('construction_road_cutting_id', $data->id)->get();
        $options = Ward::get();
        $roadtype = RoadType::get();
        $multifactor = Multifactor::get();
        $status = Status::where('table_id', $id)
            ->where('service_id', $data->service_id)
            ->first();

        $paydata = new SbiPayment;
        $roadtype = RoadType::get();
        $approvaldata = ApprovalHierarchies::where('service_id', $data->service_id)->where('table_id', $id)->whereStatus(1)->get();
        return view('construction-department.road-cutting.edit', compact('data', 'options', 'status', 'roadtype', 'multifactor', 'multidata', 'approvaldata','paydata'));
    }


    public function update(UpdateRequest $request, string $id)
    {
        try {
            $result = $this->RoadCuttingService->update($request, $id);
           
            if (is_array($result)) {
                return response()->json([
                    'status'  => $result['status'] ?? false,
                    'message' => $result['message'] ?? 'Something went wrong, please try again.',
                    'data'    => $result['data'] ?? null,
                ]);
            }
            return response()->json([
                'status'  => (bool) $result,
                'message' => $result ? 'Detail updated successfully.' : 'Something went wrong, please try again.',
            ]);
        } catch (\Exception $e) {
            \Log::error('RoadCuttingService update error:', ['exception' => $e]);
            return response()->json([
                'status'  => false,
                'message' => 'An unexpected error occurred while updating.',
                'error'   => $e->getMessage(),
            ], 500);
        }
    }


    public function show($id)
    {
        //dd(decrypt($id));
        $data = ConstructionRoadCutting::with('user')->findOrFail(decrypt($id));
        
       
        
        $multidata = ConstructionRoadCuttingRoadDetail::where('construction_road_cutting_id', $data->id)->get();
      
        $groupedData = [];
        $totalri = 0;
        $landrentTotal = 0;
        $totallength = 0;
        $combinedTotallength = 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;
            $totalri += $riCharge;
            $landrentTotal += $landrent;
            $totallength += $length;
            $groupedData[$roadtype->id]['roadtype'] = $roadtype;
            $groupedData[$roadtype->id]['items'][] = [
                'startpoint' => $item->startpoint,
                'endpoint' => $item->endpoint,
                'length' => $length,
                'defect_factor' => $item->defect_factor,
                'rate' => $rate,
                'year' => $year,
                'ri_charge' => $riCharge,
                'landrent' => $landrent,
            ];
            $groupedData[$roadtype->id]['totalri'] = ($groupedData[$roadtype->id]['totalri'] ?? 0) + $riCharge;
            $groupedData[$roadtype->id]['landrent'] = ($groupedData[$roadtype->id]['landrent'] ?? 0) + $landrent;
            $groupedData[$roadtype->id]['length'] = ($groupedData[$roadtype->id]['length'] ?? 0) + $length;

            $combinedTotallength += $length;
        }
        $noofchamber = (int) $data->no_chamber;

        $chamberfee = $noofchamber * 30000;


        $pdf = SnappyPdf::loadView('construction-department.road-cutting.constructioncertificate', ['data' => $data, 'combinedTotallength' => $combinedTotallength, 'item' => $item]);
        $pdf->setPaper('a4')
            ->setOption('margin-top', 10)
            ->setOption('margin-bottom', 10)
            ->setOption('margin-left', 5)
            ->setOption('margin-right', 5)
            ->setOption('enable-smart-shrinking', true)
            ->setOption('disable-smart-shrinking', false)
            ->setOption('no-stop-slow-scripts', true)
           
            ->setOption('footer-left', 'Page: [page] of [toPage]');
        return $pdf->inline('certificate.pdf');
    }

    public function generateReceipt($id)
{
    $data = ConstructionRoadCutting::findOrFail(decrypt($id));
    $multidata = ConstructionRoadCuttingRoadDetail::where('construction_road_cutting_id', $data->id)->get();

    // // Initialize totals
    // $totalRI = 0;
    // $totalLandrent = 0;
    // $totalChamberFee = 0;
    // $totalBeforeGst = 0;
    // $totalCgst = 0;
    // $totalSgst = 0;
    // $totalGst = 0;
    // $totalDeposit = 0;
    // $grandTotal = 0;
    // $totalLength = 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;

    //     $totalBeforeGstItem = $riCharge + $landrent + $chamberfee;
    //     $cgstItem = $totalBeforeGstItem * 0.09;
    //     $sgstItem = $totalBeforeGstItem * 0.09;
    //     $gstTotalItem = $cgstItem + $sgstItem;
    //     $depositItem = $riCharge * 0.10;

    //     $grandTotalItem = $totalBeforeGstItem + $gstTotalItem + $depositItem;

    //     // Accumulate totals
    //     $totalRI += $riCharge;
    //     $totalLandrent += $landrent;
    //     $totalChamberFee += $chamberfee;
    //     $totalBeforeGst += $totalBeforeGstItem;
    //     $totalCgst += $cgstItem;
    //     $totalSgst += $sgstItem;
    //     $totalGst += $gstTotalItem;
    //     $totalDeposit += $depositItem;
    //     $grandTotal += $grandTotalItem;
    //     $totalLength += $length;
    // }
    // Grouping by road type (same as Blade)
$grouped = $multidata->groupBy('roadtype');

// Initialize totals
$totalRI = 0;
$totalLandrent = 0;
$totalChamberFee = 0;
$totalBeforeGst = 0;
$totalCgst = 0;
$totalSgst = 0;
$totalGst = 0;
$totalDeposit = 0;
$grandTotal = 0;
$totalLength = 0;

// Chamber fee single time value
$noofchamber = (int) $data->no_chamber;
$chamberfee = $noofchamber * 30000;

$roadTypeCounter = 0;

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

    $roadTypeCounter++;

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

    $itemCounter = 0;

    foreach ($items 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 FIRST ROAD TYPE
        $itemChamberFee = ($itemCounter == 1) ? $effectiveChamberFee : 0;

        $totalBeforeGstItem = $riCharge + $landrent + $itemChamberFee;
        $cgstItem = $totalBeforeGstItem * 0.09;
        $sgstItem = $totalBeforeGstItem * 0.09;
        $gstTotalItem = $cgstItem + $sgstItem;

        $depositItem = $riCharge * 0.10;

        $grandTotalItem = $totalBeforeGstItem + $gstTotalItem + $depositItem;

        // Accumulate totals
        $totalRI += $riCharge;
        $totalLandrent += $landrent;
        $totalChamberFee += $itemChamberFee;
        $totalBeforeGst += $totalBeforeGstItem;
        $totalCgst += $cgstItem;
        $totalSgst += $sgstItem;
        $totalGst += $gstTotalItem;
        $totalDeposit += $depositItem;
        $grandTotal += $grandTotalItem;
        $totalLength += $length;
    }
}


    $paymentData = SbiPayment::where('table_id', $data->id)
        ->where('service_id', $data->service_id)
        ->first();

    $pdf = SnappyPdf::loadView('construction-department.road-cutting.receipt', [
        'data' => $data,
        'paymentdata' => $paymentData,
        'roadDetails' => $multidata,
        'netamount'=>$totalBeforeGst,
        'combinedTotalRI' => $totalRI,
        'totalLandrent' => $totalLandrent,
        'combinedLength' => $totalLength,
        'chamberfee' => $totalChamberFee,
        'combinedSecurty' => $totalDeposit,
        'cgstamount' => $totalCgst,
        'sgstamount' => $totalSgst,
        'totalgrand' => $grandTotal,
    ]);

    $pdf->setPaper('a4')
        ->setOption('margin-top', 10)
        ->setOption('margin-bottom', 10)
        ->setOption('margin-left', 5)
        ->setOption('margin-right', 5)
        ->setOption('enable-smart-shrinking', true)
        ->setOption('disable-smart-shrinking', false)
        ->setOption('no-stop-slow-scripts', true)
        ->setOption('footer-left', 'Page: [page] of [toPage]');

    return $pdf->inline('receipt.pdf');
}




    public function demand_note($id)
    {
      
        $data = ConstructionRoadCutting::with('user')->findOrFail(decrypt($id));
         

       $approval_date = DB::table('approval_hierarchies')
    ->where('service_id', $data->service_id) // match service_id
    ->where('table_id', $data->id)          // match ConstructionRoadCutting id
    ->first();
    

        $multidata = ConstructionRoadCuttingRoadDetail::where('construction_road_cutting_id', $data->id)->get();
        $groupedData = [];
        $totalri = 0;
        $landrentTotal = 0;
        $totallength = 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;
            $totalri += $riCharge;
            $landrentTotal += $landrent;
            $totallength += $length;
            $groupedData[$roadtype->id]['roadtype'] = $roadtype;
            $groupedData[$roadtype->id]['items'][] = [
                'startpoint' => $item->startpoint,
                'endpoint' => $item->endpoint,
                'length' => $length,
                'defect_factor' => $item->defect_factor,
                'rate' => $rate,
                'year' => $year,
                'ri_charge' => $riCharge,
                'landrent' => $landrent,
            ];

            $groupedData[$roadtype->id]['totalri'] = ($groupedData[$roadtype->id]['totalri'] ?? 0) + $riCharge;
            $groupedData[$roadtype->id]['landrent'] = ($groupedData[$roadtype->id]['landrent'] ?? 0) + $landrent;
            $groupedData[$roadtype->id]['length'] = ($groupedData[$roadtype->id]['length'] ?? 0) + $length;

            $groupedData[$roadtype->id]['totalri'] = ($groupedData[$roadtype->id]['totalri'] ?? 0) + $riCharge;
            $groupedData[$roadtype->id]['landrent'] = ($groupedData[$roadtype->id]['landrent'] ?? 0) + $landrent;
        }
        $noofchamber = (int) $data->no_chamber;
        $chamberfee = $noofchamber * 30000;
        // dd($chamberfee);
        return SnappyPdf::loadView('construction-department.road-cutting.demandnote', [
            'data' => $data,
            'groupedData' => $groupedData,
            'chamberfee' => $chamberfee,
            'landrentTotal' => $landrentTotal,
            'approval_date' => $approval_date,
        ])->setOption('orientation', 'Landscape')->inline('demandnote.pdf');
    }



    public function calculateGrossTotal($id)
    {
        $data = ConstructionRoadCutting::findOrFail(decrypt($id));
        $multidata = ConstructionRoadCuttingRoadDetail::where('construction_road_cutting_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;

            $totalBeforeGst = $riCharge + $landrent;
            $cgst = $totalBeforeGst * 0.09;
            $sgst = $totalBeforeGst * 0.09;
            $gstTotal = $cgst + $sgst;
            $deposit = $riCharge * 0.10;

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

            $grossTotal += $grandTotal;
        }

        return $grossTotal; // returns numeric value
    }


    // public function certificateOne_old($id){

        
    //     $data = ConstructionRoadCutting::with('user')->findOrFail(decrypt($id));
        
    //     $multidata = ConstructionRoadCuttingRoadDetail::where('construction_road_cutting_id', $data->id)->get();
      
    //     $groupedData = [];
    //     $totalri = 0;
    //     $landrentTotal = 0;
    //     $totallength = 0;
    //     $combinedTotallength = 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;
    //         $totalri += $riCharge;
    //         $landrentTotal += $landrent;
    //         $totallength += $length;
    //         $groupedData[$roadtype->id]['roadtype'] = $roadtype;
    //         $groupedData[$roadtype->id]['items'][] = [
    //             'startpoint' => $item->startpoint,
    //             'endpoint' => $item->endpoint,
    //             'length' => $length,
    //             'defect_factor' => $item->defect_factor,
    //             'rate' => $rate,
    //             'year' => $year,
    //             'ri_charge' => $riCharge,
    //             'landrent' => $landrent,
    //         ];
    //         $groupedData[$roadtype->id]['totalri'] = ($groupedData[$roadtype->id]['totalri'] ?? 0) + $riCharge;
    //         $groupedData[$roadtype->id]['landrent'] = ($groupedData[$roadtype->id]['landrent'] ?? 0) + $landrent;
    //         $groupedData[$roadtype->id]['length'] = ($groupedData[$roadtype->id]['length'] ?? 0) + $length;

    //         $combinedTotallength += $length;
    //     }
    //     $noofchamber = (int) $data->no_chamber;

    //     $chamberfee = $noofchamber * 30000;


    //     $pdf = SnappyPdf::loadView('construction-department.road-cutting.constructioncertificate', ['data' => $data, 'combinedTotallength' => $combinedTotallength, 'item' => $item]);
    //     $pdf->setPaper('a4')
    //         ->setOption('margin-top', 10)
    //         ->setOption('margin-bottom', 10)
    //         ->setOption('margin-left', 5)
    //         ->setOption('margin-right', 5)
    //         ->setOption('enable-smart-shrinking', true)
    //         ->setOption('disable-smart-shrinking', false)
    //         ->setOption('no-stop-slow-scripts', true)
    //         // ->setOption('footer-right', now()->format('d-m-Y h:i:s'))
    //         ->setOption('footer-left', 'Page: [page] of [toPage]');
    //     return $pdf->inline('certificate.pdf');

    // }


    public function certificateOne($id)
{
    
    $realId = decrypt($id);

    
    ConstructionRoadCutting::where('id', $realId)->update([
        'is_generated' => 1,
        'certificate_generated_at' => \Carbon\Carbon::now(),
        
        
    ]);

    
    $data = ConstructionRoadCutting::with('user')->findOrFail($realId);

    $multidata = ConstructionRoadCuttingRoadDetail::where('construction_road_cutting_id', $data->id)->get();

    $groupedData = [];
    $totalri = 0;
    $landrentTotal = 0;
    $totallength = 0;
    $combinedTotallength = 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;

        $totalri += $riCharge;
        $landrentTotal += $landrent;
        $totallength += $length;

        $groupedData[$roadtype->id]['roadtype'] = $roadtype;
        $groupedData[$roadtype->id]['items'][] = [
            'startpoint' => $item->startpoint,
            'endpoint' => $item->endpoint,
            'length' => $length,
            'defect_factor' => $item->defect_factor,
            'rate' => $rate,
            'year' => $year,
            'ri_charge' => $riCharge,
            'landrent' => $landrent,
        ];

        $groupedData[$roadtype->id]['totalri'] =
            ($groupedData[$roadtype->id]['totalri'] ?? 0) + $riCharge;

        $groupedData[$roadtype->id]['landrent'] =
            ($groupedData[$roadtype->id]['landrent'] ?? 0) + $landrent;

        $groupedData[$roadtype->id]['length'] =
            ($groupedData[$roadtype->id]['length'] ?? 0) + $length;

        $combinedTotallength += $length;
    }

    $noofchamber = (int) $data->no_chamber;
    $chamberfee = $noofchamber * 30000;

    $pdf = SnappyPdf::loadView(
        'construction-department.road-cutting.constructioncertificate',
        [
            'data' => $data,
            'combinedTotallength' => $combinedTotallength,
            'item' => $item
        ]
    );

    $pdf->setPaper('a4')
        ->setOption('margin-top', 10)
        ->setOption('margin-bottom', 10)
        ->setOption('margin-left', 5)
        ->setOption('margin-right', 5)
        ->setOption('enable-smart-shrinking', true)
        ->setOption('disable-smart-shrinking', false)
        ->setOption('no-stop-slow-scripts', true)
        ->setOption('footer-left', 'Page: [page] of [toPage]');

    return $pdf->inline('certificate.pdf');
}


}
