<?php

namespace App\Observers;

use App\Models\PaymentStatus;
use App\Helpers\SmsHelper;
use App\Models\Service;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class PaymentStatusObserver
{
    /**
     * Handle the PaymentStatus "created" event.
     */
    public function created(PaymentStatus $payment): void
    {
        $this->sendPaymentSMS($payment);
    }

    /**
     * Handle the PaymentStatus "updated" event.
     */
    public function updated(PaymentStatus $payment): void
    {
        if ($payment->isDirty('status')) {
            $this->sendPaymentSMS($payment);
        }
    }

    /**
     * Send payment related SMS
     */
    private function sendPaymentSMS(PaymentStatus $payment): void
    {
        // Get service and application details
        $service = Service::find($payment->service_id);
        
        if ($service && $service->table_name) {
            $application = DB::table($service->table_name)
                ->where('id', $payment->table_id)
                ->first();

            if ($application) {
                $user = User::find($application->user_id);
                $mobile = $user?->mobile;
                $applicationId = $application->application_no;

                // If payment is required/pending
                if ($payment->status === 0) {
                    $paymentLink = route('payment-options', [
                        'serviceId' => $service->id,
                        'id' => $application->id
                    ]);
                    
                    SmsHelper::sendPaymentLinkSMS($mobile, $applicationId, $paymentLink);
                }
            }
        }
    }
}