<?php
namespace App\Http\Controllers\TreeAuth;
use Exception;
use App\Models\Status;
use App\Models\SbiPayment;
use App\Models\VrukshType;
use Illuminate\Http\Request;
use App\Services\CommonService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Barryvdh\Snappy\Facades\SnappyPdf;
use App\Models\TreeAuth\TreeProtection;
use App\Services\TreeAuth\TreeProtectionService;
use App\Http\Requests\TreeAuth\TreeProtection\CreateRequest;
use App\Http\Requests\TreeAuth\TreeProtection\UpdateRequest;

class TreeProtectionController extends Controller
{
    protected $commonService;
    protected $treeProtection;



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


    public function create()
    {
        $wards = $this->commonService->getActiveWard();
        $zones = $this->commonService->getActiveZone();
        $vrukshtypes = $this->commonService->getActiveVruksh();


        return view('tree-auth.tree-protection.create')->with([
            'wards' => $wards,
            'zones' => $zones,
            'vrukshtypes' => $vrukshtypes,
        ]);
    }

    public function store(CreateRequest $request)
    {
        try {

            $treeProtection = $this->treeProtection->store($request);
            if ($treeProtection[0]) {
                return response()->json([
                    'success' => 'Tree Protection saved successfully'
                ]);
            } else {
                return response()->json([
                    'error' => $treeProtection[1]
                ]);
            }
        } catch (Exception $e) {
            Log::info('error while storing tree protect form', [$e->getMessage()]);
        }
    }



    public function edit($id)
    {

        $id = decrypt($id);
        $treeProtection = TreeProtection::findOrFail($id);

        $status = Status::where('table_id', $id)
            ->where('service_id', $treeProtection->service_id)
            ->first();
        $wards = $this->commonService->getActiveWard();

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

        // $data = AdvertisementPermission::findOrFail($id);

        return view('tree-auth.tree-protection.update')->with([
            'treeProtection' =>  $treeProtection,
            'wards' => $wards,
            'zones' => $zones,
            // 'data' => '$data',
            'status' => $status,
            'advertisemenent' => $treeProtection
        ]);
    }
    public function update(UpdateRequest $request, $id)
    {
        $treeProtection = $this->treeProtection->update($request, $id);
        if ($treeProtection) {
            return response()->json([
                'success' => 'Tree Protection updated successfully'
            ]);
        } else {
            return response()->json([
                'error' => 'Something went wrong, please try again'
            ]);
        }
    }

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

        $pdf = SnappyPdf::loadView('tree-auth.tree-protection.certificate', ['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 generateReceipt_old($id)
    // {
    //     $data = TreeProtection::with('user')->findOrFail(decrypt($id));

    //     $paymentdata = SbiPayment::Where('table_id', $data->id)->where('service_id', $data->service_id)->first();
    //     $pdf = SnappyPdf::loadView('tree-auth.tree-protection.receipt', ['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('receipt.pdf');
    // }



// public function generateReceiptfinalilly($id)
// {
//     $data = TreeProtection::with('user')->findOrFail(decrypt($id));

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

//     // Fetch matching rate from vrukshtypes
//     $vrukshType = DB::table('vrukshtypes')
//         ->where('service_id', $data->service_id)
//         ->where('type', $data->type_application)
//         ->where('name', $data->reason_trim)
//         ->first();

//     if (!$vrukshType) {
//         abort(404, 'Matching vruksh type not found');
//     }

//     $treeCount = (int)($data->type_of_tree ?? 0);

//     // Base amounts
//     $yesAmount = (float)($vrukshType->yes_amount ?? 0);
//     $noAmount = (float)($vrukshType->no_amount ?? 0);
//     $pahaniFeeRate = (float)($vrukshType->amount ?? 0);
//     $rate = (float)($vrukshType->rate ?? 0); // for trimming cases

//     // Initialize variables
//     $vrukshaNidhiRate = 0;
//     $yesPart = 0;
//     $noPart = 0;
//     $vrukshaNidhi = 0;
//     $pahaniFee = 0;
//     $total = 0;

//     // =========================
//     // CASE 1: Society or Development Tree Cutting / Replanting
//     // =========================
//     if (in_array($data->type_application, [
//         'सोसायटी / घरांच्या परिसरातील झाडे तोडणे / पुर्नरोपण / छाटणी करणे.',
//         'विकासकामातील झाडे तोडणे/ पुर्नरोपण करणे.'
//     ])) {

//         // ---- A: वृक्ष तोडणे ----
//         if ($data->reason_trim === 'वृक्ष तोडणे') {
//             if (!empty($data->space_available)) {
//                 $vrukshaNidhiRate = $yesAmount + $noAmount;
//                 $yesPart = $treeCount * $yesAmount;
//                 $noPart = $treeCount * $noAmount;
//             } elseif ($data->new_plant === 'होय') {
//                 $vrukshaNidhiRate = $yesAmount;
//                 $yesPart = $treeCount * $yesAmount;
//             } else {
//                 $vrukshaNidhiRate = $noAmount;
//                 $noPart = $treeCount * $noAmount;
//             }

//             $vrukshaNidhi = $treeCount * $vrukshaNidhiRate;
//             $pahaniFee = $treeCount * $pahaniFeeRate;
//             $total = $vrukshaNidhi + $pahaniFee;
//         }

//         // ---- B: वृक्ष पुनःरोपण ----
//         elseif ($data->reason_trim === 'वृक्ष पुनःरोपण') {
//             if (!empty($data->space_replant)) {
//                 $vrukshaNidhiRate = $yesAmount + $noAmount;
//                 $yesPart = $treeCount * $yesAmount;
//                 $noPart = $treeCount * $noAmount;
//             } elseif ($data->new_replant === 'होय') {
//                 $vrukshaNidhiRate = $yesAmount;
//                 $yesPart = $treeCount * $yesAmount;
//             } else {
//                 $vrukshaNidhiRate = $noAmount;
//                 $noPart = $treeCount * $noAmount;
//             }

//             $vrukshaNidhi = $treeCount * $vrukshaNidhiRate;
//             $pahaniFee = $treeCount * $pahaniFeeRate;
//             $total = $vrukshaNidhi + $pahaniFee;
//         }

//         // ---- C: वृक्षाची छाटणी करणे / वृक्षांची छाटणी (फांद्या) उचलणे ----
//         elseif (in_array($data->reason_trim, [
//             'वृक्षाची छाटणी करणे',
//             'वृक्षांची छाटणी (फांद्या) उचलणे'
//         ])) {
//             $vrukshaNidhi = $treeCount * $rate;
//             $pahaniFee = $treeCount * $pahaniFeeRate;
//             $total = $vrukshaNidhi + $pahaniFee;
//         }
//     }

//     // 🧾 Debug before generating PDF
//     // dd([
//     //     'Application Type' => $data->type_application,
//     //     'Reason Trim' => $data->reason_trim,
//     //     'Tree Count' => $treeCount,
//     //     'Yes Amount' => $yesAmount,
//     //     'No Amount' => $noAmount,
//     //     'Rate (from vrukshtypes)' => $rate,
//     //     'Pahani Fee Rate (amount)' => $pahaniFeeRate,
//     //     'Calculated Vruksha Nidhi' => $vrukshaNidhi,
//     //     'Calculated Pahani Fee' => $pahaniFee,
//     //     'Total' => $total,
//     //     'Yes Part' => $yesPart,
//     //     'No Part' => $noPart,
//     //     'Vruksha Nidhi Rate' => $vrukshaNidhiRate,
//     //     'Payment Data' => $paymentdata,
//     //     'Vruksh Type Row' => $vrukshType,
//     // ]);

//     // ---- PDF (disabled while debugging)
//     $pdf = SnappyPdf::loadView('tree-auth.tree-protection.receipt', [
//         'data' => $data,
//         'paymentdata' => $paymentdata,
//         'treeCount' => $treeCount,
//         'yesAmount' => $yesAmount,
//         'noAmount' => $noAmount,
//         'yesPart' => $yesPart,
//         'noPart' => $noPart,
//         'rate' => $rate,
//         'vrukshaNidhi' => $vrukshaNidhi,
//         'vrukshaNidhiRate' => $vrukshaNidhiRate,
//         'pahaniFee' => $pahaniFee,
//         'pahaniFeeRate' => $pahaniFeeRate,
//         'total' => $total,
//     ]);

//     $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 generateReceipt($id)
{
    $data = TreeProtection::with('user')->findOrFail(decrypt($id));

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

    // Default vrukshtype fetch
    $vrukshType = DB::table('vrukshtypes')
        ->where('service_id', $data->service_id)
        ->where('type', $data->type_application)
        ->where('name', $data->reason_trim)
        ->first();

    if (!$vrukshType) {
        abort(404, 'Matching vruksh type not found');
    }

    $treeCount = (int)($data->type_of_tree ?? 0);
    $yesAmount = (float)($vrukshType->yes_amount ?? 0);
    $noAmount = (float)($vrukshType->no_amount ?? 0);
    $pahaniFeeRate = (float)($vrukshType->amount ?? 0);
    $rate = (float)($vrukshType->rate ?? 0);

    $vrukshaNidhiRate = 0;
    $yesPart = $noPart = 0;
    $vrukshaNidhi = $pahaniFee = $total = 0;

   
    // CASE 1: Society or Development Tree Cutting / Replanting
   
    if (in_array($data->type_application, [
        'सोसायटी / घरांच्या परिसरातील झाडे तोडणे / पुर्नरोपण / छाटणी करणे.',
        'विकासकामातील झाडे तोडणे/ पुर्नरोपण करणे.'
    ])) {

        // ---- A: वृक्ष तोडणे ----
        if ($data->reason_trim === 'वृक्ष तोडणे') {
            if (!empty($data->space_available)) {
                $vrukshaNidhiRate = $yesAmount + $noAmount;
                $yesPart = $treeCount * $yesAmount;
                $noPart = $treeCount * $noAmount;
            } elseif ($data->new_plant === 'होय') {
                $vrukshaNidhiRate = $yesAmount;
                $yesPart = $treeCount * $yesAmount;
            } else {
                $vrukshaNidhiRate = $noAmount;
                $noPart = $treeCount * $noAmount;
            }

            $vrukshaNidhi = $treeCount * $vrukshaNidhiRate;
            $pahaniFee = $treeCount * $pahaniFeeRate;
            $total = $vrukshaNidhi + $pahaniFee;
        }

        // ---- B: वृक्ष पुनःरोपण ----
        elseif ($data->reason_trim === 'वृक्ष पुनःरोपण') {
            if (!empty($data->space_replant)) {
                $vrukshaNidhiRate = $yesAmount + $noAmount;
                $yesPart = $treeCount * $yesAmount;
                $noPart = $treeCount * $noAmount;
            } elseif ($data->new_replant === 'होय') {
                $vrukshaNidhiRate = $yesAmount;
                $yesPart = $treeCount * $yesAmount;
            } else {
                $vrukshaNidhiRate = $noAmount;
                $noPart = $treeCount * $noAmount;
            }

            $vrukshaNidhi = $treeCount * $vrukshaNidhiRate;
            $pahaniFee = $treeCount * $pahaniFeeRate;
            $total = $vrukshaNidhi + $pahaniFee;
        }

        // ---- C: वृक्षाची छाटणी करणे / वृक्षांची छाटणी (फांद्या) उचलणे ----
        elseif (in_array($data->reason_trim, [
            'वृक्षाची छाटणी करणे',
            'वृक्षांची छाटणी (फांद्या) उचलणे'
        ])) {
            $vrukshaNidhi = $treeCount * $rate;
            $pahaniFee = $treeCount * $pahaniFeeRate;
            $total = $vrukshaNidhi + $pahaniFee;
        }

        // ---- D: धोकादायक झाडे मुळासहित काढणे ----
        elseif ($data->reason_trim === 'धोकादायक झाडे मुळासहित काढणे') {
            $heightConditions = [
                'उंची (Height) - ३५ ते ५० फुट किंवात्यापेक्षा जास्त बुंध्याची जाडी (Girth) - २.५० फुटापेक्षा जास्त',
                'उंची (Height) - २० ते ३५ फुटापर्यंत बुंध्याची जाडी (Girth) - १ ते २.५० फुट',
                'उंची (Height) - २० फुटापर्यंत बुंध्याची जाडी (Girth) - १ फुटापर्यंत'
            ];

            if (in_array($data->tree_height, $heightConditions)) {
                $vrukshTypeSub = DB::table('vrukshtypes')
                    ->where('service_id', $data->service_id)
                    ->where('type', $data->type_application)
                    ->where('name', $data->reason_trim)
                    ->where('sub_name', $data->tree_height)
                    ->first();

                if ($vrukshTypeSub) {
                    $rate = (float)($vrukshTypeSub->rate ?? 0);
                    $pahaniFeeRate = (float)($vrukshTypeSub->amount ?? 0);

                    $vrukshaNidhi = $treeCount * $rate;
                    $pahaniFee = $treeCount * $pahaniFeeRate;
                    $total = $vrukshaNidhi + $pahaniFee;
                }
            }
        }
    }

    // ---- PDF View
    $pdf = SnappyPdf::loadView('tree-auth.tree-protection.receipt', [
        'data' => $data,
        'paymentdata' => $paymentdata,
        'treeCount' => $treeCount,
        'yesAmount' => $yesAmount,
        'noAmount' => $noAmount,
        'yesPart' => $yesPart,
        'noPart' => $noPart,
        'rate' => $rate,
        'vrukshaNidhi' => $vrukshaNidhi,
        'vrukshaNidhiRate' => $vrukshaNidhiRate,
        'pahaniFee' => $pahaniFee,
        'pahaniFeeRate' => $pahaniFeeRate,
        'total' => $total,
    ]);

    $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('footer-left', 'Page: [page] of [toPage]');

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

public function getVrukshNames(Request $request)
{
    $type = $request->query('type');

    $names = VrukshType::where('type', $type)
        ->pluck('name')
        ->unique()
        ->values();

    return response()->json($names ?: []);
}

public function getVrukshSubnames(Request $request)
{
    $name = $request->query('name');

    $subnames = VrukshType::where('name', $name)
        ->pluck('sub_name')
        ->unique()
        ->values();

    return response()->json($subnames ?: []);
}



}
