<?php

namespace App\Http\Controllers\WaterSupplyDepartment;

use App\Models\Status;
use App\Models\SbiPayment;
use Illuminate\Http\Request;
use App\Services\CommonService;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Barryvdh\Snappy\Facades\SnappyPdf;
use App\Models\WaterDepartment\WaterPressureComplaint;
use App\Services\WaterDepartment\WaterPressureService;
use App\Http\Requests\WaterDepartment\WaterPressure\CreateRequest;
use App\Http\Requests\WaterDepartment\WaterPressure\UpdateRequest;


class WaterPressureController extends Controller
{
    protected $waterPressureService;
    protected $commonService;

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

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

        $zones = $this->commonService->getActiveZone();
        $user = Auth::user();


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

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

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

    public function edit(string $id)
    {
        $data = WaterPressureComplaint::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();

        return view('water-supply-department.water-pressure.edit')->with([
            'data' => $data,
            'wards' => $wards,
            'zones' => $zones,
            'status' => $status,
        ]);
    }

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

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

     public function show($id)
    {
        $data = WaterPressureComplaint::with('user')->findOrFail(decrypt($id));
       $paymentdata = SbiPayment::Where('table_id',$data->id)->where('service_id', $data->service_id)->first();
       
        $pdf = SnappyPdf::loadView('water-supply-department.water-pressure.waterpressure', ['data' => $data,'paymentdata'=>$paymentdata]);
        $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 = WaterPressureComplaint::with('user')->findOrFail(decrypt($id));
        $paymentdata = SbiPayment::Where('table_id',$data->id)->where('service_id', $data->service_id)->first();
        //dd($data);

// // initialize defaults
// $grossAmountone = 0;
// $roadAmount = 0;
// $roadRepairTotal = 0; // <-- yeh line add karo

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

// // Junior Amount × Running Meter
// if (!empty($data->jramountone) && !empty($data->running_meterone)) {
//     $roadRepairTotal = $data->jramountone * $data->running_meterone;
//     $grossAmountone += $roadRepairTotal;
// }

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

// Initialize defaults
// $grossAmountone = 0;
// $roadAmount = 0;
// $roadRepairTotal = 0;

// // Payment amount
// $paymentAmount = !empty($paymentdata->amount) ? (float)$paymentdata->amount : 0;

// // Junior Amount × Running Meter (Dynamic Calculation)
// if (!empty($data->jramountone) && !empty($data->running_meterone)) {
//     $roadRepairTotal = (float)$data->jramountone * (float)$data->running_meterone;
// }

// // ✅ Final gross = payment amount + road repair total (+ optional roadAmount)
// $grossAmountone = $paymentAmount + $roadRepairTotal + $roadAmount;

// // Final formatted gross amount (for display)
// $grossAmountFormatted = number_format($grossAmountone, 2);


// 💥 Always reset to 0 before calculation
// Initialize defaults
$paymentAmount = isset($paymentdata->amount) ? (float)$paymentdata->amount : 0;
$roadRepairTotal = 0;
$roadAmount = 0;
$grossAmountone = 0;

// Step 1: Calculate Road Repair Total (Dynamic)
if (!empty($data->jramountone) && !empty($data->running_meterone)) {
    $roadRepairTotal = (float)$data->jramountone * (float)$data->running_meterone;
}

// Step 2: Calculate Road Amount (Certificate Charges)
$roadAmount = $paymentAmount - $roadRepairTotal;

// Step 3: Calculate Gross Amount
$grossAmountone = $roadAmount + $roadRepairTotal;

// Step 4: Format for display
$grossAmountFormatted = number_format($grossAmountone, 2);

// Debug check
// dd([
//     'payment' => $paymentAmount,
//     'road_repair' => $roadRepairTotal,
//     'road_amount' => $roadAmount,
//     'gross' => $grossAmountone,
// ]);









        
        
        $pdf = SnappyPdf::loadView('water-supply-department.water-pressure.receipt', ['data' => $data , 'paymentdata'=>$paymentdata, 'grossAmountone'=>$grossAmountone, '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');
    }

}
