<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Status;
use App\Models\Service;
use App\Models\ServiceName;
use Illuminate\Http\Request;
use App\Models\ServiceCredential;
use Illuminate\Support\Facades\DB;
use App\Models\ApprovalRequestHierarchy;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use App\Models\AapaleSarkarPaymentDetails;
use App\Models\ApprovalHierarchies;

use App\Models\ConstructionRoadCutting;
use App\Models\Role;
use App\Models\SbiPayment;
use App\Services\AapaleSarkarLoginCheckService;
use Carbon\Carbon;


class DashboardController extends Controller
{
    protected $aapaleSarkarLoginCheckService;

    public function __construct(AapaleSarkarLoginCheckService $aapaleSarkarLoginCheckService)
    {
        $this->aapaleSarkarLoginCheckService = $aapaleSarkarLoginCheckService;
        // $this->middleware('application.my-application')->only('myApplication');
    }


    public function index()
    {
        $user = Auth::user();

        // 1. SUPER ADMIN DASHBOARD
        if ($user->hasRole('Super Admin')) {
            $services = Service::with('services')->where('is_parent', 0)->get();
            $data = [];

            foreach ($services as $mainService) {
                foreach ($mainService->services as $subService) {
                    if (!$subService->table_name) continue;

                    $tableName = $subService->table_name;
                    $mainServiceId = $mainService->id;
                    $serviceId = $subService->id;
                    $name = $subService->name;

                    $tableData = DB::table($tableName)
                        ->select(
                            'user_id',
                            'status',
                            DB::raw('DATE(created_at) as created_at'),
                            DB::raw('DATE_FORMAT(created_at, "%Y-%m") as yearmonth'),
                            DB::raw("'$mainServiceId' as main_service_id"),
                            DB::raw("'$serviceId' as service_id"),
                            DB::raw("'$name' as name")
                        )
                        ->get();

                    foreach ($tableData as $record) {
                        $recordArray = (array) $record;
                        $recordArray['is_aapale_sarkar_user'] = DB::table('users')
                            ->where('id', $record->user_id)
                            ->value('is_aapale_sarkar_user');

                        $data[] = $recordArray;
                    }
                }
            }

            return view('home.dashboard', [
                'services' => $services,
                'data' => collect($data)
            ]);
        }

        // 2. REGULAR USER DASHBOARD
        elseif ($user->hasRole('User')) {
            $services = Service::where('is_parent', 0)
                ->where('servicetype', 'RTS')
                ->withCount('services')
                ->get();

            $servicesnonrts = Service::where('is_parent', 0)
                ->where('servicetype', 'NONRTS')
                ->withCount('services')
                ->get();

            return view('home.user-dashboard', [
                'services' => $services,
                'servicesnonrts' => $servicesnonrts
            ]);
        }

        // 3. OTHER ROLES (Department Head, Clerk, etc.)
        else {
            $pendingCount = 0;
            $approvalCount = 0;
            $todaysdatecount = 0;
            $todaysDateApproval = 0;
            $deparatmentrecord = collect();

            $departmentId = DB::table('department_user')
                ->where('user_id', $user->id)
                ->value('department_id');

            $department = DB::table('departments')
                ->where('id', $departmentId)
                ->value('name');

            if ($departmentId) {
                $statusesQuery = DB::table('statuses')
                    ->where('department_id', $departmentId);

                $pendingCount = (clone $statusesQuery)->where('status', 0)->count();
                $approvalCount = (clone $statusesQuery)->where('status', 1)->count();
                $todaysdatecount = (clone $statusesQuery)->whereDate('created_at', Carbon::today())->count();
                $todaysDateApproval = (clone $statusesQuery)->where('status', 1)->whereDate('created_at', Carbon::today())->count();
                $deparatmentrecord = (clone $statusesQuery)->whereDate('created_at', Carbon::today())->get(); // all statuses
            }

            $services = Service::with('services')->where('is_parent', 0)->get();
            $serviceName = ServiceName::select('model', 'service_id', 'service_name')->get();



            return view('home.common-dashboard', compact(
                'pendingCount',
                'approvalCount',
                'department',
                'todaysDateApproval',
                'todaysdatecount',
                'deparatmentrecord',
                'services',
                'serviceName'
            ));
        }
    }





    public function myApplication($serviceId = null)
    {
        $serviceName = ServiceName::select('model', 'service_id', 'service_name')->get();
        $items = collect();
        $targetServices = $serviceName;
        foreach ($targetServices as  $modelClass) {
            $service_id = $modelClass->service_id;
            if ($modelClass) {
                $modelData = $modelClass->model::withWhereHas('statuses', function ($query) use ($service_id) {
                    $query->where('service_id', $service_id)
                        ->with([
                            'approvalhierarchies.approver',
                            'serviceName'
                        ]);
                })
                ->where('user_id', Auth::id())
                ->get();

                //kishori add the code for certificate Add a flag to each record if it's ConstructionRoadCutting & service_id 187
                // $modelData->transform(function ($record) use ($service_id) {
                //     if ($service_id == 187 && isset($record->is_generated) && $record->is_generated == 1) {
                //         $record->show_certificate = true;
                //     } else {
                //         $record->show_certificate = false;
                //     }
                //     return $record;
                // });

                $modelData->transform(function ($record) use ($service_id) {
                        if (($service_id == 187 || $service_id == 2032) 
                            && isset($record->is_generated) 
                            && $record->is_generated == 1) 
                        {
                            $record->show_certificate = true;
                        } else {
                            $record->show_certificate = false;
                        }

                        return $record;
                    });
                //kishori add the code for certificate Add a flag to each record if it's ConstructionRoadCutting & service_id 187

                $items = $items->merge($modelData);
            }
        }
        $items = $items->sortByDesc('created_at')->values();
        $paydata = new SbiPayment;
        return view('home.my-application')->with([
            'datas' => $items,
            'serviceName' => $serviceName,
            'paydata' => $paydata
        ]);
    }




    // public function myApplication(Request $request)
    // {


    //     if (isset($request->str) && $request->str != "") {
    //         $str = $request->str;

    //         $strKeys = "@pn@PNM@m@h@0nl!ne@23523";
    //         $strIVs = "PNM@05@3";

    //         // decrypt data and get the reponse data from aapale sarkar
    //         $check = $this->aapaleSarkarLoginCheckService->decryptTripleDES($str, $strKeys, $strIVs);

    //         $rowData = explode('|', $check);

    //         if (count($rowData) > 0) {
    //             if (count($rowData) == 10) {
    //                 if ($rowData[8] == "True") {
    //                     AapaleSarkarPaymentDetails::create([
    //                         'client_code' => $rowData[0],
    //                         'service_id' => $rowData[1],
    //                         'application_no' => $rowData[2],
    //                         'payment_transaction_id' => $rowData[3],
    //                         'bank_ref_id' => $rowData[4],
    //                         'bank_ref_no' => $rowData[5],
    //                         'bank_id' => $rowData[6],
    //                         'payment_date' => $rowData[7],
    //                         'payment_status' => $rowData[8],
    //                         'total_amount' => $rowData[9],
    //                     ]);

    //                     $serviceDeptId = ServiceCredential::where('service_id', $rowData[1])->value('dept_service_id');
    //                     $model = ServiceName::where('service_id', $serviceDeptId)->value('model');

    //                     $model::where('application_no', $rowData[2])->update([
    //                         'is_payment_paid_aapale_sarkar' => 1,
    //                         'aapale_sarkar_payment_date' => date('Y-m-d')
    //                     ]);


    //                     $aapaleSarkarCredential = ServiceCredential::where('dept_service_id', $serviceDeptId)->first();
    //                     $serviceDay = ($aapaleSarkarCredential->service_day) ? $aapaleSarkarCredential->service_day : 20;

    //                     $send = $this->aapaleSarkarLoginCheckService->encryptAndSendRequestToAapaleSarkar(Auth::user()->trackid, $aapaleSarkarCredential->client_code, Auth::user()->user_id, $aapaleSarkarCredential->service_id, $rowData[2], 'N', 'NA', 'N', 'NA', $serviceDay, date('Y-m-d', strtotime("+$serviceDay days")), config('rtsapiurl.amount'), config('rtsapiurl.requestFlag'), 3, "Under Scrutiny", $aapaleSarkarCredential->ulb_id, $aapaleSarkarCredential->ulb_district, 'NA', 'NA', 'NA', $aapaleSarkarCredential->check_sum_key, $aapaleSarkarCredential->str_key, $aapaleSarkarCredential->str_iv, $aapaleSarkarCredential->soap_end_point_url, $aapaleSarkarCredential->soap_action_app_status_url);

    //                     if ($send) {
    //                         return redirect()->route('my-application');
    //                     } else {
    //                         \Log::error('Payment verification failed for Aapale Sarkar');
    //                     }
    //                 }
    //             } elseif (isset($request->Appid) && $request->Appid != "") {
    //                 $serviceCredential = DB::table('service_credentials')->where([
    //                     'ulb_id' => $request->ULBID,
    //                     'ulb_district' => $request->ULBDistrict,
    //                     'service_id' => $request->ns
    //                 ])->first();

    //                 // return redirect($serviceCredential->service_url);

    //                 // decrypt data and get the reponse data from aapale sarkar

    //                 $check = $this->aapaleSarkarLoginCheckService->checkDecryptData(
    //                     $serviceCredential->soap_end_point_url,
    //                     $serviceCredential->soap_action_url,
    //                     $serviceCredential->check_sum_key,
    //                     $serviceCredential->client_code,
    //                     $request->str,
    //                     $serviceCredential->str_key,
    //                     $serviceCredential->str_iv
    //                 );

    //                 // condition for logic if we get success
    //                 if ($check[0]) {
    //                     $data = $check[1];
    //                     // return $data;
    //                     if (isset($data['UserID']) && !empty($data['UserID'])) {
    //                         // Query the database to check if the user exists
    //                         $existingUser = User::where('user_id', $data['UserID'])->first();

    //                         if ($existingUser) {
    //                             Auth::login($existingUser);

    //                             User::where('id', Auth::user()->id)->update(['trackid' => $data['TrackId']]);
    //                         } else {
    //                             $user = User::create([
    //                                 'name' => ($data['FullName']) ? $data['FullName'] : '',
    //                                 'email' => ($data['EmailID']) ? $data['EmailID'] : '',
    //                                 'password' => ($data['Password']) ? $data['Password'] : '',
    //                                 'mobile' => ($data['MobileNo']) ? $data['MobileNo'] : '',
    //                                 'age' => ($data['Age']) ? $data['Age'] : '',
    //                                 'gender' => ($data['Gender']) ? $data['Gender'] : '',
    //                                 'user_id' => ($data['UserID']) ? $data['UserID'] : '',
    //                                 'trackid' => ($data['TrackId']) ? $data['TrackId'] : '',
    //                                 'is_aapale_sarkar_user' => 1,
    //                             ]);

    //                             DB::table('model_has_roles')->insert(['role_id' => 2, 'model_type' => 'App\Models\User', 'model_id' => $user->id]);

    //                             Auth::login($user);
    //                         }
    //                         if (Auth::check()) {
    //                             return redirect()->route('my-application');
    //                         }
    //                     } else {
    //                         abort(500);
    //                     }
    //                 } else {
    //                     abort(500);
    //                 }
    //             }
    //         }
    //     }


    //     $serviceName = ServiceName::pluck('service_name', 'service_id')->toArray();

    //     $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();
    //     // return $serviceCredentials;
    //     $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);
    //     }

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

    //     return view('home.my-application')->with([
    //         'datas' => $data,
    //         'serviceName' => $serviceName,
    //         'editRoute' => $editRoute,
    //         'serviceCredentials' => $serviceCredentials
    //     ]);
    // }

    public function generatePaymentUrl(Request $request)
    {
        $paymentUrl = $this->aapaleSarkarLoginCheckService->makePaymentToAapaleSarkar($request);

        if ($paymentUrl) {
            return redirect($paymentUrl);
        } else {
            abort(500);
        }
    }

    public function paymentReturnUrl(Request $request)
    {
        $str = $request->str;

        $strKeys = "@pn@PNM@m@h@0nl!ne@23523";
        $strIVs = "PNM@05@3";

        // decrypt data and get the reponse data from aapale sarkar
        $check = $this->aapaleSarkarLoginCheckService->decryptTripleDES($str, $strKeys, $strIVs);

        $rowData = explode('|', $check);

        if (count($rowData) > 0) {
            if (count($rowData) == 10) {
                if ($rowData[8] == "True") {
                    AapaleSarkarPaymentDetails::create([
                        'client_code' => $rowData[0],
                        'service_id' => $rowData[1],
                        'application_no' => $rowData[2],
                        'payment_transaction_id' => $rowData[3],
                        'bank_ref_id' => $rowData[4],
                        'bank_ref_no' => $rowData[5],
                        'bank_id' => $rowData[6],
                        'payment_date' => $rowData[7],
                        'payment_status' => $rowData[8],
                        'total_amount' => $rowData[9],
                    ]);

                    $serviceDeptId = ServiceCredential::where('service_id', $rowData[1])->value('dept_service_id');
                    $model = ServiceName::where('service_id', $serviceDeptId)->value('model');

                    $model::where('application_no', $rowData[2])->update([
                        'is_payment_paid_aapale_sarkar' => 1,
                        'aapale_sarkar_payment_date' => date('Y-m-d')
                    ]);

                    $aapaleSarkarCredential = ServiceCredential::where('dept_service_id', $serviceDeptId)->first();
                    $serviceDay = ($aapaleSarkarCredential->service_day) ? $aapaleSarkarCredential->service_day : 20;

                    $send = $this->aapaleSarkarLoginCheckService->encryptAndSendRequestToAapaleSarkar(Auth::user()->trackid, $aapaleSarkarCredential->client_code, Auth::user()->user_id, $aapaleSarkarCredential->service_id, $rowData[2], 'N', 'NA', 'N', 'NA', $serviceDay, date('Y-m-d', strtotime("+$serviceDay days")), config('rtsapiurl.amount'), config('rtsapiurl.requestFlag'), 3, "Under Scrutiny", $aapaleSarkarCredential->ulb_id, $aapaleSarkarCredential->ulb_district, 'NA', 'NA', 'NA', $aapaleSarkarCredential->check_sum_key, $aapaleSarkarCredential->str_key, $aapaleSarkarCredential->str_iv, $aapaleSarkarCredential->soap_end_point_url, $aapaleSarkarCredential->soap_action_app_status_url);

                    if ($send) {
                        return redirect()->route('my-application');
                    } else {
                        \Log::error('Payment verification failed for Aapale Sarkar');
                    }
                }
            } elseif (count($rowData) == 4) {
                return redirect()->route('my-application');
            }
        } else {
            return redirect()->route('my-application');
        }

        return redirect()->route('my-application');
    }


    public function subService(Request $request, $id)
    {
        $services = Service::where('service_id', $id)->get();

        return view('home.sub-service')->with([
            'services' => $services
        ]);
    }
}
