<?php

namespace App\Observers;

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

class StatusObserver
{
    /**
     * When a new Status record is created.
     */

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


    public function created(Status $status)
    {
        try {
            // Get application_no dynamically
            [$applicationNo, $serviceName] = $this->getApplicationAndServiceName($status);

            $mobile = optional($status->user)->mobile ?? null;
            if (!$mobile) {
                Log::info('No mobile found for Status ID: ' . $status->id);
                return;
            }

            // Send "Application received" SMS (status = 0)
            if ($status->status == 0) {
                 $this->sendSmsOnlyInAllowedEnv(function () use ($serviceName, $applicationNo, $mobile) {
                 SmsHelper::sendApprovalSMS(0, $serviceName, $applicationNo, null, $mobile);
                 });
            }
        } catch (\Exception $e) {
            Log::error('StatusObserver@created error: ' . $e->getMessage());
        }
    }

    /**
     * When Status is updated.
     */
    public function updated(Status $status)
    {
        try {
            // 🔹 Get application_no dynamically
            [$applicationNo, $serviceName] = $this->getApplicationAndServiceName($status);

            $mobile = optional($status->user)->mobile ?? null;
            Log::info('StatusObserver@updated triggered for ID: ' . $status->id . ', Status: ' . $status->status);

            if (!$mobile) return;

            // Only when final approval is reached
            if ($status->status == 1 && $status->wasChanged('status')) {
                SmsHelper::sendApprovalSMS(4, $serviceName, $applicationNo, null, $mobile);
            }
        } catch (\Exception $e) {
            Log::error('StatusObserver@updated error: ' . $e->getMessage());
        }
    }

    /**
     * 🔹 Common helper to get application_no & truncated service name.
     */
    protected function getApplicationAndServiceName(Status $status): array
    {
        $applicationId = $status->table_id;
        $rawServiceName = optional($status->serviceName)->service_name ?? 'Service';

        // Truncate service name to 30 chars
        $serviceName = mb_substr($rawServiceName, 0, 30) . (mb_strlen($rawServiceName) > 30 ? '...' : '');

        // Try to fetch model from service_names table
        $service = ServiceName::where('service_id', $status->service_id)->first();
        $applicationNo = $applicationId;

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

            if ($record) {
                // Try to detect the field name automatically
                $possibleFields = ['application_no', 'application_number', 'app_no'];
                foreach ($possibleFields as $field) {
                    if (isset($record->{$field})) {
                        $applicationNo = $record->{$field};
                        Log::info("Fetched application_no '{$applicationNo}' from {$modelClass}");
                        break;
                    }
                }
            } else {
                Log::warning("No record found for table_id: {$status->table_id} in model {$modelClass}");
            }
        } else {
            Log::warning("Invalid or missing model for service_id: {$status->service_id}");
        }

        return [$applicationNo, $serviceName];
    }
}
