<?php

namespace App\Observers;

use App\Models\ApprovalHierarchies;
use App\Models\ServiceName;
use App\Helpers\SmsHelper;
use Illuminate\Support\Facades\Log;

class ApprovalHierarchiesObserver
{
    public function created(ApprovalHierarchies $approval)
    {
        $this->handleApprovalSMS($approval);
    }

    public function updated(ApprovalHierarchies $approval)
    {
        $this->handleApprovalSMS($approval);
    }

    protected function sendSmsOnlyInAllowedEnv($callback)
    {
        if (app()->environment('production')) {
            return $callback();
        }
        Log::info("SMS Skipped - Environment: " . app()->environment());
        return false;
    }


    protected function handleApprovalSMS(ApprovalHierarchies $approval)
    {
        try {
            // Step 1: Get basic info
            $applicationId = $approval->table_id;
            $serviceName = optional($approval->serviceName)->service_name ?? 'Service';
            $mobile = optional($approval->citizen)->mobile ?? null;
            $approverName = optional($approval->approver)->name ?? null;

            if (!$mobile) {
                Log::warning("No mobile found for approval ID: {$approval->id}");
                return;
            }
            // Step 2: Dynamically get the model class from service_names table
            $service = ServiceName::where('service_id', $approval->service_id)->first();

            $applicationNo = null;

            if ($service && $service->model && class_exists($service->model)) {
                $modelClass = $service->model;
                $record = $modelClass::find($approval->table_id);

                if ($record && isset($record->application_no)) {
                    $applicationNo = $record->application_no;
                    Log::info("Fetched application_no: {$applicationNo} for table_id {$approval->table_id}");
                } else {
                    Log::warning("Application number not found for table_id: {$approval->table_id}");
                }
            } else {
                Log::warning("Model not found or invalid for service_id: {$approval->service_id}");
            }

            //Step 3: Concatenate service name safely (max 30 chars)
            $serviceName = mb_substr($serviceName, 0, 30) . (mb_strlen($serviceName) > 30 ? '..' : '');

            //Step 4: Send SMS based on status
            if ($approval->status == 1) {
                // Check if any approvals are still pending
                $pendingCount = ApprovalHierarchies::where('table_id', $approval->table_id)
                    ->where('service_id', $approval->service_id)
                    ->where('status', 0)
                    ->count();

                if ($pendingCount > 0) {
                    // Current-level approval
                    // SmsHelper::sendApprovalSMS(1, $serviceName, $applicationNo ?? $applicationId, $approverName, $mobile);
                    $this->sendSmsOnlyInAllowedEnv(function () use ($serviceName, $applicationNo, $applicationId, $approverName, $mobile) {
                        SmsHelper::sendApprovalSMS(1, $serviceName, $applicationNo ?? $applicationId, $approverName, $mobile);
                    });

                } else {
                    // Final approval
                    // SmsHelper::sendApprovalSMS(4, $serviceName, $applicationNo ?? $applicationId, null, $mobile);
                     $this->sendSmsOnlyInAllowedEnv(function () use ($serviceName, $applicationNo, $applicationId, $mobile) {
                            SmsHelper::sendApprovalSMS(4, $serviceName, $applicationNo ?? $applicationId, null, $mobile);
                      });
                   $this->setRegNumber($record);
                }
            } elseif ($approval->status == 2) {
                // Rejected
                // SmsHelper::sendApprovalSMS(2, $serviceName, $applicationNo ?? $applicationId, $approverName, $mobile);
                $this->sendSmsOnlyInAllowedEnv(function () use ($serviceName, $applicationNo, $applicationId, $approverName, $mobile) {
                    SmsHelper::sendApprovalSMS(2, $serviceName, $applicationNo ?? $applicationId, $approverName, $mobile);
                });
            }

        } catch (\Exception $e) {
            Log::error('ApprovalHierarchiesObserver error: ' . $e->getMessage());
        }
    }


    //Function for give reg_no for that application after final approval
    protected function setRegNumber($data)
    {
        if (!empty($data)) {
            $sequence_service_ids = config('services_config.sequence_service_ids', []);
            if (in_array($data->service_id, $sequence_service_ids)) {
                $year = date('Y');
                $seq = \App\Models\RegistrationSequence::nextSequence($data->service_id, $year);
                $regNo = sprintf('MH/THN/MBMC/%d-%03d', $year, $seq);

                Log::info("Generating reg_no for service_id {$data->service_id}: {$regNo}");

                $data->reg_no = $regNo;
                $data->save();
            } else {
                Log::info("Service ID {$data->service_id} not in sequence_service_ids array.");
            }
        } else {
            Log::warning("setRegNumber called but data is empty.");
        }
    }
}
