<?php

namespace App\Http\Controllers\Admin;

use App\Models\Role;
use App\Models\User;
use App\Models\Status;
use App\Models\Department;
use App\Models\SbiPayment;
use App\Models\Multifactor;
use App\Models\ServiceName;
use Illuminate\Http\Request;
use App\Models\ServiceCredential;
use Illuminate\Support\Facades\DB;
use App\Models\ApprovalHierarchies;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Barryvdh\Snappy\Facades\SnappyPdf;
use App\Models\Trade\TradeNocForMandap;
use Illuminate\Support\Facades\Storage;
use App\Models\ApprovalRequestHierarchy;

use App\Models\WaterDepartment\WaterPressureComplaint;
use App\Models\ConstructionDepartment\ConstructionRoadCutting;
use App\Models\Pwd\GrantingTelecom;

use App\Services\CommonService;
class PendingListController extends Controller
{

    protected $commonservice;

    public function __construct(CommonService $commonservice)
    {
        $this->middleware('permission:application.pending-list')->only('pending_list');
        $this->middleware('permission:application.approval-list')->only('approve_list');
        $this->middleware('permission:application.rejected-list')->only('rejected_list');
        $this->commonservice = $commonservice;
    }
    public function pending_list($serviceId = null)
    {
        $user = Auth::user();
        $userRoles = $user->getRoleNames();
        $services = ServiceName::pluck('model', 'service_id')->toArray();
        $department = Department::get();
        $pendingItems = collect();

        $targetServices = $serviceId ? [$serviceId => $services[$serviceId] ?? null] : $services;
        // dd($targetServices);
        foreach ($targetServices as $serviceId => $modelClass) {
            // Logger($modelClass);
            if ($modelClass) {
                $pendingItems = $pendingItems->merge(
                    $modelClass::withWhereHas('status', function ($query) use ($serviceId) {
                        $query->where('service_id', $serviceId);
                    })
                    ->whereHas('status.approvalhierarchies', function ($query) use ($serviceId) {
                            $query->where('approver_user_id', Auth::user()->id)->where('status', 0)->where('next_approval_flag', 1)->where('service_id', $serviceId);
                        })
                        ->orderBy('id', 'desc')
                        ->get()
                );
            }
        }

        $serviceName = ServiceName::select('model', 'service_id', 'service_name')->get();

        $editRoute = ServiceName::pluck('edit_route', 'service_id')->toArray();

        $demandnote = ServiceName::pluck('demandnote', 'service_id')->toArray();

        $serviceCredentials = ServiceCredential::select('dept_service_id', 'id', 'service_id', 'is_paid_service', 'is_paid_service_by_aapale_sarkar', 'service_charge')->get();
        $tables = [
            'city_structure_part_maps',
            'city_structure_zone_certificates',
            'construction_drainage_connections',
            'construction_road_cuttings',
            'fire_final_no_objections',
            'fire_no_objections',
            'illegalwaterconnections',
            'marriage_reg_forms',
            'trade_auto_renewal_license_permissions',
            'trade_change_license_names',
            'trade_change_license_types',
            'trade_change_owner_counts',
            'trade_change_owner_names',
            'trade_license_cancellations',
            'trade_license_transfers',
            'trade_new_license_permissions',
            'trade_noc_for_mandaps',
            'trade_per_licenses',
            'trade_renewal_license_permissions',
            'waternewconnections',
            'water_change_connection_sizes',
            'water_change_in_uses',
            'water_change_ownerships',
            'water_defective_meters',
            'water_disconnect_supplies',
            'water_plumber_licenses',
            'water_pressure_complaints',
            'water_quality_complaints',
            'water_reconnections',
            'water_renewal_of_plumbers',
            'water_unavailability_supplies',
            'newtaxations',
            'no_due_certificates',
            'property_tax_issuance_of_property_tax_assessments',
            'registration_of_objections',
            're_taxations',
            'self_assessments',
            'tax_demands',
            'tax_exemptions',
            'tax_exemption_non_resident_properties',
            'transfer_property_certificates',
            "water_no_dues",
            "water_tax_bills",
            'occupancy_certificates',
            'plinth_certificates',
            'advertisement_permissions',
            'abattoir_licenses',
            'gardens_filmings',
            'health_licenses',
            'hoarding_permissions',
            'park_culture_permissions',
            'permission_shootings',
            'permission_for_pmc_owns',
            'stall_board_licenses',
            'tents_permissions',
            'classrooms_for_rents',
            'procession_and_parades',
            'record_objections',
            'mobile_towers',
            'state_licenses',
            'health_noc_muncis',
            'movable_advertisement_permissions',
            'cfcs',
            'advertisement_permissions',
            'new_tax_assessments',
            'div_sub_divisions',
            'demolishing_properties',
            'trade_nocs',
            'grant_nursing_licenses',
            'renewal_nursing_licenses',
            'change_nursing_licenses',
            'license_loadging_houses',
            'renew_license_loadgings',
            'issuance_license_marriages',
            'renew_marriage_licenses',
            'hawker_registers',
            'granting_telecoms',
            'tree_protections',
            'movie_shooting',
            'building_permissions',
            'issue_occupancy_certificates',
            'business_partner_changes',
            'drainages',
            'property_division_into_sub_divisions',
            // 'transfer-selfproperty',
            'newtaxations',
        ];
        $data = [];

        foreach ($tables as $table) {
            $tableData = DB::table($table)->select('id', 'application_no', 'created_at', 'payment_date', 'is_payment_paid', 'is_payment_paid_aapale_sarkar', 'aapale_sarkar_payment_date', 'service_id', 'status')->where('user_id', Auth::user()->id)->get()->toArray();

            $data = array_merge($data, $tableData);
        }

        usort($data, function ($a, $b) {
            return strtotime($b->created_at) - strtotime($a->created_at);
        });

        $user = User::get();
        $statusdata = Status::get();

        return view('admin.pending_list')->with(compact('pendingItems', 'serviceName', 'editRoute', 'serviceCredentials', 'user', 'statusdata', 'demandnote'));
    }

    public function rejected_list($serviceId = null)
    {
        $user = Auth::user();
        $services = ServiceName::pluck('model', 'service_id')->toArray();
        $approvedItems = collect();

        $targetServices = $serviceId ? [$serviceId => $services[$serviceId] ?? null] : $services;

        foreach ($targetServices as $serviceId => $modelClass) {
            if ($modelClass) {
                $approvedItems = $approvedItems->merge(
                    $modelClass::withWhereHas('status', function ($query) use ($serviceId) {
                        $query->where('service_id', $serviceId);
                    })
                        ->withWhereHas('status.approvalhierarchies', function ($query) use ($serviceId) {
                            $query->where('approver_user_id', Auth::user()->id)->where('status', 2)->where('next_approval_flag', 0)->where('service_id', $serviceId);
                        })
                        ->get()
                );
            }
        }

        $serviceName = ServiceName::select('model', 'service_id', 'service_name')->get();

        $editRoute = ServiceName::pluck('edit_route', 'service_id')->toArray();

        $serviceCredentials = ServiceCredential::select('dept_service_id', 'id', 'service_id', 'is_paid_service', 'is_paid_service_by_aapale_sarkar', 'service_charge')->get();
        $tables = [
            'city_structure_part_maps',
            'city_structure_zone_certificates',
            'construction_drainage_connections',
            'construction_road_cuttings',
            'fire_final_no_objections',
            'fire_no_objections',
            'illegalwaterconnections',
            'marriage_reg_forms',
            'trade_auto_renewal_license_permissions',
            'trade_change_license_names',
            'trade_change_license_types',
            'trade_change_owner_counts',
            'trade_change_owner_names',
            'trade_license_cancellations',
            'trade_license_transfers',
            'trade_new_license_permissions',
            'trade_noc_for_mandaps',
            'trade_per_licenses',
            'trade_renewal_license_permissions',
            'waternewconnections',
            'water_change_connection_sizes',
            'water_change_in_uses',
            'water_change_ownerships',
            'water_defective_meters',
            'water_disconnect_supplies',
            'water_plumber_licenses',
            'water_pressure_complaints',
            'water_quality_complaints',
            'water_reconnections',
            'water_renewal_of_plumbers',
            'water_unavailability_supplies',
            'newtaxations',
            'no_due_certificates',
            'property_tax_issuance_of_property_tax_assessments',
            'registration_of_objections',
            're_taxations',
            'self_assessments',
            'tax_demands',
            'tax_exemptions',
            'tax_exemption_non_resident_properties',
            'transfer_property_certificates',
            "water_no_dues",
            "water_tax_bills",
            'occupancy_certificates',
            'plinth_certificates',
            'advertisement_permissions',
            'abattoir_licenses',
            'gardens_filmings',
            'health_licenses',
            'hoarding_permissions',
            'park_culture_permissions',
            'permission_shootings',
            'permission_for_pmc_owns',
            'stall_board_licenses',
            'tents_permissions',
            'classrooms_for_rents',
            'procession_and_parades',
            'record_objections',
            'mobile_towers',
            'state_licenses',
            'health_noc_muncis',
            'movable_advertisement_permissions',
            'cfcs',
            'advertisement_permissions',
            'new_tax_assessments',
            'div_sub_divisions',
            'demolishing_properties',
            'trade_nocs',
            'grant_nursing_licenses',
            'renewal_nursing_licenses',
            'change_nursing_licenses',
            'license_loadging_houses',
            'renew_license_loadgings',
            'issuance_license_marriages',
            'renew_marriage_licenses',
            'hawker_registers',
            'granting_telecoms',
            'tree_protections',
            'movie_shooting',
            'building_permissions',
            'issue_occupancy_certificates',
            'business_partner_changes',
            'drainages',
        ];
        $data = [];

        foreach ($tables as $table) {
            $tableData = DB::table($table)->select('id', 'application_no', 'created_at', 'service_id', 'payment_date', 'is_payment_paid', 'is_payment_paid_aapale_sarkar', 'aapale_sarkar_payment_date', 'status')->where('user_id', Auth::user()->id)->get()->toArray();

            $data = array_merge($data, $tableData);
        }
        $statusdata = Status::get();

        usort($data, function ($a, $b) {
            return strtotime($b->created_at) - strtotime($a->created_at);
        });

        $user = User::get();

        return view('admin.rejected_list')->with(['approvedItems' => $approvedItems, 'serviceName' => $serviceName, 'editRoute' => $editRoute, 'serviceCredentials' => $serviceCredentials, 'statusdata' => $statusdata, 'user' => $user]);
    }

    public function approve_list($serviceId = null)
    {
        $user = Auth::user();

        $services = ServiceName::pluck('model', 'service_id')->toArray();
        $approvedItems = collect();

        

        $targetServices = $serviceId ? [$serviceId => $services[$serviceId] ?? null] : $services;

        foreach ($targetServices as $serviceId => $modelClass) {
            if ($modelClass) {
                if (Auth::check() && Auth::user()->hasRole('CityEngineer')) {
                    $approvedItems = $approvedItems->merge(
                        $modelClass::withWhereHas('status', function ($query) use ($serviceId) {
                            $query->where('service_id', $serviceId)
                                ->where('status', 1);
                        })
                            ->withWhereHas('status.approvalhierarchies', function ($query) use ($serviceId) {
                                $query->where('service_id', $serviceId);
                            })
                            ->get()
                    );
                } else {
                    $approvedItems = $approvedItems->merge(
                        $modelClass::withWhereHas('status', function ($query) use ($serviceId) {
                            $query->where('service_id', $serviceId);
                        })
                            ->withWhereHas('status.approvalhierarchies', function ($query) use ($serviceId) {
                                $query->where('approver_user_id', Auth::user()->id)
                                    ->where('status', 1)
                                    ->where('next_approval_flag', 1)
                                    ->where('service_id', $serviceId);
                            })
                            ->get()
                    );
                }
            }
        }
        $serviceName = ServiceName::select('model', 'service_id', 'service_name')->get();
        $demandnote = ServiceName::pluck('demandnote', 'service_id')->toArray();
        $editRoute = ServiceName::pluck('edit_route', 'service_id')->toArray();

        $certificateRoute = ServiceName::pluck('certificate_route', 'service_id')->toArray();
        $receiptroute = ServiceName::pluck('receipt_route', 'service_id')->toArray();

        $serviceCredentials = ServiceCredential::select('dept_service_id', 'id', 'service_id', 'is_paid_service', 'is_paid_service_by_aapale_sarkar', 'service_charge')->get();
        $tables = [
            'city_structure_part_maps',
            'city_structure_zone_certificates',
            'construction_drainage_connections',
            'construction_road_cuttings',
            'fire_final_no_objections',
            'fire_no_objections',
            'illegalwaterconnections',
            'marriage_reg_forms',
            'trade_auto_renewal_license_permissions',
            'trade_change_license_names',
            'trade_change_license_types',
            'trade_change_owner_counts',
            'trade_change_owner_names',
            'trade_license_cancellations',
            'trade_license_transfers',
            'trade_new_license_permissions',
            'trade_noc_for_mandaps',
            'trade_per_licenses',
            'trade_renewal_license_permissions',
            'waternewconnections',
            'water_change_connection_sizes',
            'water_change_in_uses',
            'water_change_ownerships',
            'water_defective_meters',
            'water_disconnect_supplies',
            'water_plumber_licenses',
            'water_pressure_complaints',
            'water_quality_complaints',
            'water_reconnections',
            'water_renewal_of_plumbers',
            'water_unavailability_supplies',
            'newtaxations',
            'no_due_certificates',
            'property_tax_issuance_of_property_tax_assessments',
            'registration_of_objections',
            're_taxations',
            'self_assessments',
            'tax_demands',
            'tax_exemptions',
            'tax_exemption_non_resident_properties',
            'transfer_property_certificates',
            "water_no_dues",
            "water_tax_bills",
            'occupancy_certificates',
            'plinth_certificates',
            'advertisement_permissions',
            'abattoir_licenses',
            'health_licenses',
            'hoarding_permissions',
            'park_culture_permissions',
            'permission_shootings',
            'permission_for_pmc_owns',
            'stall_board_licenses',
            'tents_permissions',
            'classrooms_for_rents',
            'procession_and_parades',
            'record_objections',
            'mobile_towers',
            'state_licenses',
            'health_noc_muncis',
            'movable_advertisement_permissions',
            'cfcs',
            'advertisement_permissions',
            'new_tax_assessments',
            'div_sub_divisions',
            'demolishing_properties',
            'trade_nocs',
            'grant_nursing_licenses',
            'renewal_nursing_licenses',
            'change_nursing_licenses',
            'license_loadging_houses',
            'renew_license_loadgings',
            'issuance_license_marriages',
            'renew_marriage_licenses',
            'hawker_registers',
            'granting_telecoms',
            'tree_protections',
            'movie_shooting',
            'building_permissions',
            'issue_occupancy_certificates',
            'business_partner_changes',
            'drainages'
        ];
        $data = [];

        foreach ($tables as $table) {
            $tableData = DB::table($table)->select('id', 'application_no', 'created_at', 'service_id', 'payment_date', 'is_payment_paid', 'is_payment_paid_aapale_sarkar', 'aapale_sarkar_payment_date', 'status')->where('user_id', Auth::user()->id)->get()->toArray();

            $data = array_merge($data, $tableData);
        }

        usort($data, function ($a, $b) {
            return strtotime($b->created_at) - strtotime($a->created_at);
        });

        $user = User::get();
        $multifactor = Multifactor::get();
        $paydata = SbiPayment::get();
        $statusdata = Status::get();
        $roadCuttingData = ConstructionRoadCutting::select('id', 'is_generated')->get()->keyBy('id');
        $GrantingData = GrantingTelecom::select('id', 'is_generated')->get()->keyBy('id');

        


        return view('admin.approve_list')->with(['approvedItems' => $approvedItems, 'serviceName' => $serviceName, 'editRoute' => $editRoute, 'serviceCredentials' => $serviceCredentials,  'user' => $user, 'multifactor' => $multifactor, 'demandnote' => $demandnote, 'certificateRoute' => $certificateRoute, 'receiptroute' => $receiptroute, 'paydata' => $paydata, 'statusdata' => $statusdata,'roadCuttingData' => $roadCuttingData,'GrantingData'=>$GrantingData]);
    }

    // public function approveItem_old(Request $request, $statusId)
    // {
    //     $remark = $request->input('remark');



    //     DB::beginTransaction();
    //     try {
    //         $currentApproval = ApprovalHierarchies::where('status_id', $statusId)
    //             ->where('status', 0)
    //             ->where('next_approval_flag', 1)
    //             ->first();








    //         if ($currentApproval) {
    //             $currentApproval->update([
    //                 'status' => 1,
    //                 'next_approval_flag' => 1,
    //                 'remark' => $remark,
    //             ]);
    //         }





    //         if(!isset($request->stop_next_approval)){
    //         $nextApproval = ApprovalHierarchies::where('status_id', $statusId)
    //             ->where('status', 0)
    //             ->where('next_approval_flag', 0)
    //             ->first();

    //         if ($nextApproval) {
    //             $nextApproval->update([
    //                 'next_approval_flag' => 1,
    //             ]);
    //         } else {
    //             Status::where('id', $statusId)->update(['status' => 1]);
    //         }
    //     }

    //         DB::commit();

    //         return response()->json([
    //             'message' => 'Approval successful.',
    //             'redirect_url' => url('approvelist')
    //         ]);
    //     } catch (\Exception $e) {
    //         DB::rollBack();
    //         return response()->json(['error' => $e->getMessage()], 500);
    //     }
    // }

    public function approveItem(Request $request, $statusId)
    {
        $remark = $request->input('remark');
        $jramountone = $request->input('jramountone');
        $running_meterone = $request->input('running_meterone');

        DB::beginTransaction();

        try {
            $currentApproval = ApprovalHierarchies::where('status_id', $statusId)
                ->where('status', 0)
                ->where('next_approval_flag', 1)
                ->first();

               
                

            if ($currentApproval) {

                // Step 1️⃣: Update current approval
                $currentApproval->update([
                    'status' => 1,
                    'next_approval_flag' => 1,
                    'remark' => $remark,
                ]);

                // Step 2️⃣: Update Complaint table (sirf JE ke liye)
                $complaint = WaterPressureComplaint::where('id', $currentApproval->table_id)->first();

                if ($complaint) {
                    // Agar logged-in user Junior Engineer hai to hi update karna hai
                    if (auth()->user()->hasRole('JuniorEngineer')) {
                        $complaint->update([
                            'jramountone' => $jramountone,
                            'running_meterone' => $running_meterone,
                        ]);
                    } else {
                        // Baaki roles ke liye existing value preserve rakhni hai
                        $complaint->update([
                            'jramountone' => $complaint->jramountone,
                            'running_meterone' => $complaint->running_meterone,
                        ]);
                    }
                }
            }

            // Step 3️⃣: Handle next approval
            if (!isset($request->stop_next_approval)) {
                $nextApproval = ApprovalHierarchies::where('status_id', $statusId)
                    ->where('status', 0)
                    ->where('next_approval_flag', 0)
                    ->first();

                if ($nextApproval) {
                    $nextApproval->update(['next_approval_flag' => 1]);
                } else {
                    Status::where('id', $statusId)->update(['status' => 1]);
                }
            }

            DB::commit();

            return response()->json([
                'message' => 'Approval successful.',
                'redirect_url' => url('approvelist')
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Approval Error: ' . $e->getMessage());
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    public function rejectItem(Request $request, $statusId)
    {
        $remark = $request->input('remark');

        DB::beginTransaction();

        try {

            $currentApproval = ApprovalHierarchies::where('status_id', $statusId)
                ->where('status', 0)
                ->where('next_approval_flag', 1)
                ->first();

            if ($currentApproval) {
                $currentApproval->update([
                    'status' => 2,
                    'next_approval_flag' => 0,
                    'remark' => $remark,
                ]);
            }

            Status::where('id', $statusId)->update([
                    'status' => 2,
            ]);


            // $nextApproval = ApprovalHierarchies::where('status_id', $statusId)
            //     ->where('status', 0)
            //     ->where('next_approval_flag', 0)
            //     ->first();

            // if ($nextApproval) {
            //     $nextApproval->update([
            //         'next_approval_flag' => 0,
            //     ]);
            // } else {

            //     Status::where('id', $statusId)->update([
            //         'status' => 2,
            //     ]);
            // }

            DB::commit();

            return response()->json([
                'message' => 'Rejection successful.',
                'redirect_url' => url('rejected_list')
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    public function uploadfactor(Request $request, $statusId)
    {
        $request->validate([
            'defect_factor' => 'required'
        ]);

        $status = Status::find($statusId);

        if ($status) {
            $status->defect_factor = $request->input('defect_factor');
            $status->save();
            $nextApproval = ApprovalHierarchies::where('status_id', $statusId)
                ->where('status', 0)
                ->where('next_approval_flag', 0)
                ->first();

            if ($nextApproval) {
                $nextApproval->update([
                    'next_approval_flag' => 1,
                ]);

                return response()->json([
                    'success' => true,
                    'message' => 'MultiplyingFactor Inserted successfully!',
                    'redirect_url' => url('approvelist')
                ]);
            }

            return response()->json(['success' => false, 'message' => 'MultiplyingFactor failed!']);
        }
    }


    public function upload(Request $request, $statusId)
    {

        $request->validate([
            'document_upload' => 'required|file|mimes:pdf,doc,docx,jpg,jpeg,png|max:2048',
        ]);

        $file = $request->file('document_upload');
        $serviceId = $request->input('serviceId');
        $status = Status::Where('table_id', $statusId)->Where('service_id', $serviceId)->first();

        Log::info('Upload attempt:', [
            'statusId' => $statusId,
            'serviceId' => $serviceId,
            'status_found' => $status ? 'Yes' : 'No',
            'file_name' => $file ? $file->getClientOriginalName() : 'No file',
        ]);



        if (!$file) {
            return response()->json(['success' => false, 'message' => 'No file received.']);
        }

        if (!$status) {
            return response()->json(['success' => false, 'message' => 'Invalid status ID.']);
        }

        $fileName = time() . '_' . $file->getClientOriginalName();
        $path = $file->storeAs('offlinereceipt', $fileName, 'public');
        $status->offlinereceipt = $path;
        $status->receipt_status = 0;
        $status->receipt_remark = '';
        $status->receipt_uploaded_at = now();
        // $status->fees_amount = $request->fees_amount ?? 0;
        if(empty($status->receipt_verifier_id)){
                $status->receipt_verifier_id = $this->commonservice->getFirstApproverId($status->id);
        }
        // dd($status->receipt_verifier_id );
        if ($serviceId) {
            Log::info("Service ID is: " . $serviceId);
        }

        $status->save();

        return response()->json([
            'success' => true,
            'message' => 'Receipt uploaded successfully!',
            'redirect_url' => url('my-application')
        ]);
    }


     public function upload_certitficate(Request $request, $statusId)
    {

        $request->validate([
            'document_upload' => 'required|file|mimes:pdf,doc,docx,jpg,jpeg,png|max:2048',
        ]);

        $file = $request->file('document_upload');
        $serviceId = $request->input('serviceId');
        $status = Status::Where('table_id', $statusId)->Where('service_id', $serviceId)->first();

        Log::info('Upload attempt:', [
            'statusId' => $statusId,
            'serviceId' => $serviceId,
            'status_found' => $status ? 'Yes' : 'No',
            'file_name' => $file ? $file->getClientOriginalName() : 'No file',
        ]);
        if (!$file) {
            return response()->json(['success' => false, 'message' => 'No file received.']);
        }

        if (!$status) {
            return response()->json(['success' => false, 'message' => 'Invalid status ID.']);
        }
        $path = $file->store('document_upload', 'public');
        $status->document_upload = $path;
        $status->save();

        return response()->json([
            'success' => true,
            'message' => 'Certificate uploaded successfully!',
            'redirect_url' => url('my-application')
        ]);
    }



//     public function revertBack_old(Request $request)
// {
//     $request->validate([
//         'id' => 'required',
//     ]);

//     $approval = ApprovalHierarchies::find($request->id);

//     if (!$approval) {
//         return response()->json(['message' => 'Record not found'], 404);
//     }

//     $approval->update([
//         'is_reverted' => 1,
//         'status' => 0, 
//         'next_approval_flag' => 0,
//     ]);

//     return response()->json([
//         'message' => 'Reverted successfully to Clerk.'
//     ]);
// }

public function revertBack(Request $request)
{
    $request->validate([
        'id' => 'required',
    ]);

    $approval = ApprovalHierarchies::find($request->id);
  // dd($approval);
    if (!$approval) {
        return response()->json(['message' => 'Record not found'], 404);
    }

    // First-time revert check
    // if ($approval->is_reverted != 1) {
    //     $approval->is_reverted = 1;             // mark as reverted
    //     $approval->status = 0;                   // pending at Clerk
    //     $approval->next_approval_flag = 1;       // send next approval to Clerk
    //     $approval->save();                       

    //     return response()->json([
    //         'message' => 'Reverted successfully to Clerk.'
    //     ]);
    // } else {
    //      $approval->is_reverted = 0;
    //     $approval->status = 1;                   // pending at Clerk
    //     $approval->next_approval_flag = 1; 
    //     return response()->json([
    //         'message' => 'This record has already been reverted once.'
    //     ]);
    // }
    if ($approval->is_reverted != 1) {
    // First-time revert
    $approval->is_reverted = 1;             
    $approval->status = 0;                   // pending at Clerk
    $approval->next_approval_flag = 1;       // send next approval to Clerk
    $approval->save();                       

    return response()->json([
        'message' => 'Reverted successfully to Clerk.'
    ]);
} else {
    // Already reverted once
    // If you really want to reset it, you MUST save
    $approval->is_reverted = 0;
    $approval->status = 1;                  
    $approval->next_approval_flag = 1; 
    $approval->save();  // <-- needed here

    return response()->json([
        'message' => 'This record has already been reverted once, values reset.'
    ]);
}
}


public function revertBackGranting(Request $request)
{
    $request->validate([
        'id' => 'required',
    ]);

    $approval = ApprovalHierarchies::find($request->id);
  // dd($approval);
    if (!$approval) {
        return response()->json(['message' => 'Record not found'], 404);
    }

    // First-time revert check
    // if ($approval->is_reverted != 1) {
    //     $approval->is_reverted = 1;             // mark as reverted
    //     $approval->status = 0;                   // pending at Clerk
    //     $approval->next_approval_flag = 1;       // send next approval to Clerk
    //     $approval->save();                       

    //     return response()->json([
    //         'message' => 'Reverted successfully to Clerk.'
    //     ]);
    // } else {
    //      $approval->is_reverted = 0;
    //     $approval->status = 1;                   // pending at Clerk
    //     $approval->next_approval_flag = 1; 
    //     return response()->json([
    //         'message' => 'This record has already been reverted once.'
    //     ]);
    // }
    if ($approval->is_reverted != 1) {
    // First-time revert
    $approval->is_reverted = 1;             
    $approval->status = 0;                   // pending at Clerk
    $approval->next_approval_flag = 1;       // send next approval to Clerk
    $approval->save();                       

    return response()->json([
        'message' => 'Reverted successfully to Clerk.'
    ]);
} else {
    // Already reverted once
    // If you really want to reset it, you MUST save
    $approval->is_reverted = 0;
    $approval->status = 1;                  
    $approval->next_approval_flag = 1; 
    $approval->save();  // <-- needed here

    return response()->json([
        'message' => 'This record has already been reverted once, values reset.'
    ]);
}

}

}
