<?php

namespace App\Http\Controllers\WaterSupplyDepartment;

use App\Models\Status;
use App\Models\SbiPayment;
use App\Models\WaterPayment;
use App\Models\WaterPrabhag;
use Illuminate\Http\Request;
use App\Services\CommonService;
use App\Models\WaterPrabhagWards;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Barryvdh\Snappy\Facades\SnappyPdf;
use App\Models\ApprovalRequestHierarchy;
use App\Models\WaterDepartment\Waternewconnection;
use App\Services\WaterDepartment\NewWaterConnectionService;
use App\Http\Requests\WaterDepartment\NewWaterConnection\CreateNewConnectionRequest;
use App\Http\Requests\WaterDepartment\NewWaterConnection\UpdateNewConnectionRequest;


class NewWaterConnectionController extends Controller
{
    protected $newWaterConnectionService;
    protected $commonService;

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

    public function create()
    {
        $wards = $this->commonService->getActiveWard();

        $zones = $this->commonService->getActiveZone();
        $prabhags = WaterPrabhag::get();


        return view('water-supply-department.new-water-connection.create')->with([
            'wards' => $wards,
            'zones' => $zones,
            'prabhags' => $prabhags,
        ]);
    }

    public function getWard($prabhag){
        $wards = WaterPrabhagWards::where('prabhag_id',$prabhag)->get();

        return $wards;
    }

    public function fetchDetails(Request $request)
    {
        $request->validate([
            'marchantid' => 'required|string',
            'connection_no' => 'required|string',
        ]);

        $waterdata = [
            "jsonData" => [
                [
                    "MerchantID" => $request->marchantid,
                    "connno" => $request->connection_no,
                ]
            ]
        ];

        $jsonData = json_encode($waterdata);

        $encryptedData = $this->commonService->encryptString($jsonData);

        $apidata = $this->commonService->sendEncryptedWaterData($encryptedData);

        return response()->json([
            'jsonData' => [
                'encr_request' => $apidata,
            ]
        ]);
    }

    public function updateRoad(Request $request){
        $validated = $request->validate([
            'road_repair_type' => 'nullable',
            'road_repair_length' => 'nullable'
        ]);

        $updatedRoad = Waternewconnection::find($request->formId);

        if($updatedRoad){
            $updatedRoad->update($request->all());
        }

        return response()->json([
            'status' => 'success',
            'message' => 'Road updated successfully!',
            'data' => $updatedRoad
        ]);
    }

    //   public function encryptRequestData(Request $request)
    // {
    //     $data = $request->all();

    //     $jsonData = json_encode($data);

    //     $encryptedData = $this->encryptString($jsonData);

    //     return response()->json([
    //         'jsonData' => [
    //             'encr_request' => $encryptedData
    //         ]
    //     ]);
    // }

    public function store(CreateNewConnectionRequest $request)
    {
        $newWaterConnectionService = $this->newWaterConnectionService->store($request);
        // return $newWaterConnectionService;
        if ($newWaterConnectionService[0]) {
            return response()->json([
                'success' => 'Detail Stored successfully'
            ]);
        } else {
            return response()->json([
                'error' => $newWaterConnectionService[1]
            ]);
        }
    }

    public function edit(string $id)
    {
        $data = Waternewconnection::findOrFail(decrypt($id));

        $wards = $this->commonService->getActiveWard();

        $zones = $this->commonService->getActiveZone();

        $status = Status::where('table_id', decrypt($id))
        ->where('service_id', $data->service_id)
        ->first();
        $userRoleId = Auth::user()->roles->first()->id;
        $secondApprover = ApprovalRequestHierarchy::where('service_id', $data->service_id)->where('second_approver_designation_id',$userRoleId)->first();
        $thirdApprover = ApprovalRequestHierarchy::where('service_id', $data->service_id)->where('third_approver_designation_id',$userRoleId)->first();


         // ✅ Fetch Prabhag Name
    $prabhagName = WaterPrabhag::where('id', $data->prabhag)->value('name');

    // ✅ Fetch Ward Name
    $wardName = WaterPrabhagWards::where('id', $data->ward_area)->value('ward_name');

        return view('water-supply-department.new-water-connection.edit')->with([
            'data' => $data,
            'wards' => $wards,
            'zones' => $zones,
            'secondApprover' => $secondApprover,
            'thirdApprover' => $thirdApprover,
            'status' => $status,
            'prabhagName' => $prabhagName,
        'wardName' => $wardName,
        ]);
    }

    public function update(UpdateNewConnectionRequest $request, string $id)
    {
        $newWaterConnectionService = $this->newWaterConnectionService->update($request, $id);

        if ($newWaterConnectionService[0]) {
            return response()->json([
                'success' => 'Detail updated successfully'
            ]);
        } else {
            return response()->json([
                'error' => $newWaterConnectionService[1]
            ]);
        }
    }

    public function show($id)
    {
        $data = Waternewconnection::with('user')->findOrFail(decrypt($id));
        $pdf = SnappyPdf::loadView('water-supply-department.new-water-connection.newwaterconnectioncertificate', ['data' => $data]);
        $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 getWaterFine($id, $usage, $subUsage){
        $query = WaterPayment::where('service_id', $id)->where('type', $usage);
        if($subUsage){
            $query->where('sub_type', $subUsage);
        }
        return $query->value('rate');
    }

    public function generateReceipt($id)
    {
        $data = Waternewconnection::with('user')->findOrFail(decrypt($id));
        $paymentdata = SbiPayment::Where('table_id',$data->id)->where('service_id', $data->service_id)->first();
        $amount = null;
        $roadAmount = null;
        $grossAmount = 0;

// Payment amount
if ($paymentdata) {
    $grossAmount += $paymentdata->amount;
}

// Junior Amount × Running Meter
$roadRepairTotal = 0;
if (!empty($data->jramount) && !empty($data->running_meter)) {
    $roadRepairTotal = $data->jramount * $data->running_meter;
    $grossAmount += $roadRepairTotal; // add to gross
}

// Any other roadAmount if exists
if (!empty($roadAmount)) {
    $grossAmount += $roadAmount;
}



        // if($data->water_connection_use == 'अनिवासी व्यवसाय'){
        //     $sizeInInch = $data->pipe_size / 25.4;
        //     $roadAmount = ($data->road_repair_length * 12024);
        //     $amount = round(($sizeInInch * 78070), 2);
        // }





        $pdf = SnappyPdf::loadView('water-supply-department.new-water-connection.receipt', ['data' => $data,
           'paymentdata' => $paymentdata, 'roadAmount' => $roadAmount ?? null, 'amount' => $amount,'grossAmount'=>$grossAmount,'roadRepairTotal'=>$roadRepairTotal]);

        $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');
    }
}
