<?php

namespace App\Http\Controllers\Pwd;

use App\Models\Status;
use App\Models\RoadType;
use App\Models\SbiPayment;
use App\Models\Multifactor;
use Illuminate\Http\Request;
use App\Services\CommonService;
use Illuminate\Support\Facades\DB;
use App\Models\ApprovalHierarchies;
use App\Models\Pwd\GrantingTelecom;
use App\Http\Controllers\Controller;
use Barryvdh\Snappy\Facades\SnappyPdf;
use App\Models\Pwd\GrantingTelecomDetails;
use App\Services\Pwd\GrantingTelecomService;
use App\Http\Requests\Pwd\GrantingTelecom\CreateRequest;
use App\Http\Requests\Pwd\GrantingTelecom\UpdateRequest;

class GrantingTelecomController extends Controller
{
    protected $commonService;
    protected $grantingTelecom;


    public function __construct(GrantingTelecomService $grantingTelecom, CommonService $commonService)
    {
        $this->grantingTelecom = $grantingTelecom;
        $this->commonService = $commonService;
    }

    public function create()
    {
        $options = $this->commonService->getActiveWard();
        $zones = $this->commonService->getActiveZone();
        $roadtype = RoadType::get();
        $multifactor =Multifactor::get();

        return view('pwd.granting-telecom.create')->with([
            'options' => $options,
            'zones' => $zones,
            'roadtype'  => $roadtype,
            'multifactor' => $multifactor
        ]);
    }

    public function store(CreateRequest $request)
    {

        $grantingTelecom = $this->grantingTelecom->store($request);

        if ($grantingTelecom[0]) {
            return response()->json([
                'success' => 'Application Submitted Successfully'
            ]);
        } else {
            return response()->json([
                'error' => $grantingTelecom[1]
            ]);
        }
    }



    public function edit($id)
    {
        $id = decrypt($id);
        $grantingTelecom = GrantingTelecom::findOrFail($id);
        $multidata =GrantingTelecomDetails::Where('gratingtelecom_id', $grantingTelecom->id)->get();
        $multifactor =Multifactor::get();
        $roadtype = RoadType::get();
          $paydata = new SbiPayment;
        $options = $this->commonService->getActiveWard();
        $zones = $this->commonService->getActiveZone();
        $status = Status::where('table_id', $id)
            ->where('service_id', $grantingTelecom->service_id)
            ->first();

        $approvaldata = ApprovalHierarchies::where('service_id',$grantingTelecom->service_id)->where('table_id',$id)->get();


        return view('pwd.granting-telecom.update')->with([
            'grantingTelecom' =>  $grantingTelecom,
            'options' => $options,
            'zones' => $zones,
            'status' => $status,
            'advertisemenent' => $grantingTelecom,
            'roadtype' => $roadtype,
            'multidata' => $multidata,
            'multifactor' => $multifactor,
            'paydata'=> $paydata,
            'approvaldata' => $approvaldata
        ]);
    }
    public function update(UpdateRequest $request, string $id)
    {
       
        $grantingTelecom = $this->grantingTelecom->update($request, $id);
       

       if ($grantingTelecom) {
            return response()->json([
                'success' => 'Detail updated successfully'
            ]);
        } else {
            return response()->json([
                'error' => 'Something went wrong, please try again'
            ]);
        }
    }

    public function show($id)
    {
        $data = GrantingTelecom::with('user')->findOrFail(decrypt($id));
        $multidata = GrantingTelecomDetails::where('gratingtelecom_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('pwd.granting-telecom.pwdcertificate', ['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 generateReceipt($id)
    {
        $data = GrantingTelecom::with('user')->findOrFail(decrypt($id));
        $multidata = GrantingTelecomDetails::where('gratingtelecom_id', $data->id)->get();

    
    // $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;

        
    //     $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('pwd.granting-telecom.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-right', now()->format('d-m-Y h:i:s'))
            ->setOption('footer-left', 'Page: [page] of [toPage]');

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

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

$approval_dategranting = DB::table('approval_hierarchies')
    ->where('service_id', $data->service_id) // match service_id
    ->where('table_id', $data->id)          // match ConstructionRoadCutting id
    ->first();
        
        $multidata = GrantingTelecomDetails::where('gratingtelecom_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,
            ];

            // dd($riCharge);

            $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;

        }
        $riChargedeposit = $riCharge * 0.10;
        $noofchamber = (int) $data->no_chamber;
        $chamberfee = $noofchamber * 30000;
        $cgst = $totalri * 0.09;
        $sgst = $totalri * 0.09;
        $totalgst = $cgst + $sgst;
        $grandtotal = $riChargedeposit + $totalri + $totalgst + $chamberfee + $landrentTotal;

        return SnappyPdf::loadView('pwd.granting-telecom.demandnote', [
            'data' => $data,
            'groupedData' => $groupedData,
            'chamberfee' => $chamberfee,
            'riChargedeposit' => $riChargedeposit,
            'cgst' => $cgst,
            'sgst' => $sgst,
            'totalgst' => $totalgst,
            'grandtotal' => $grandtotal,
            'totalri' => $totalri,
            'landrentTotal' => $landrentTotal,
            'approval_dategranting' => $approval_dategranting
        ])->setOption('orientation', 'Landscape')->inline('demandnote.pdf');

    }

    //  public function generatedemandnote($id){
    //     $data = GrantingTelecom::with('user')->findOrFail(decrypt($id));
    //     $roadtypedata = RoadType::where('id', $data->road_type)->first();
    //     $statusdata = Status::where('service_id', $data->service_id)->where('table_id', $data->id)->first();
    //     $multifactor = Multifactor::where('id', $statusdata->defect_factor)->first();

    //     $length = (int) $data->length_road;
    //     $rate = (int) $roadtypedata->rate;
    //     $year = (float) $multifactor->year;
    //     $riCharge = $length * $rate * $year;
    //     $noofchamber  = (int)  $data->no_chamber;
    //     $chamberfee = $noofchamber * 30000;
    //     $landrent = $length * 200;
    //     $riChargedeposit = $riCharge * 0.10;
    //     $totalri = $riCharge + $landrent;
    //     $cgst = $totalri * 0.09;
    //     $sgst = $totalri * 0.09;
    //     $totalgst = $cgst + $sgst;
    //     $grandtotal = $riChargedeposit + $totalri + $totalgst;


    //     $pdf = SnappyPdf::loadView('pwd.granting-telecom.demandnote',
    //         [
    //             'data' => $data,
    //             'roadtypedata' => $roadtypedata,
    //             'statusdata' => $statusdata,
    //             'multifactor' => $multifactor,
    //             'riCharge' => $riCharge,
    //             'chamberfee' => $chamberfee,
    //             'landrent' => $landrent,
    //             'riChargedeposit' => $riChargedeposit,
    //             'totalri' => $totalri,
    //             'cgst' => $cgst,
    //             'sgst'=> $sgst,
    //             'totalgst' => $totalgst,
    //             'grandtotal' => $grandtotal
    //         ]);

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



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

    
    GrantingTelecom::where('id', $realId)->update([
        'is_generated' => 1,
        'certificate_generated_at' => \Carbon\Carbon::now(),
        
        
    ]);
	
	
        $data = GrantingTelecom::with('user')->findOrFail(decrypt($id));
        $multidata = GrantingTelecomDetails::where('gratingtelecom_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('pwd.granting-telecom.pwdcertificate', ['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');
    }
}
