<?php

namespace App\Services\Sms;

use Carbon\Carbon;
use App\Jobs\SendSmsJob;
use App\Constants\Settings;
use App\Models\Student\StudentInfo;
use Illuminate\Support\Facades\Log;

class BirthdaySmsService
{

    public static function sendBirthdayWishes()
    {
        $today = Carbon::today()->format('m-d');
        
        // sms send
        $successCount = 0;
        $failCount = 0;
        $invalidNumbers = [];



        $students = StudentInfo::where('status','active')->whereRaw("DATE_FORMAT(date_of_birth, '%m-%d') = ?", [$today])->get();

        if ($students->isEmpty()) {
            Log::info("No students found with today's birthday: $today");
            return;
        }
        
        foreach ($students as $student) {

            $birthday_sms = get_setting_value(get_setting_value(Settings::BIRTHDAY_SMS, $student->branch_id)) ? get_setting_value(get_setting_value(Settings::BIRTHDAY_SMS, $student->branch_id)) : '0';
            
            $school_short_name = get_setting_value(Settings::SCHOOL_SHORT_NAME,$student->branch_id) ? get_setting_value(Settings::SCHOOL_SHORT_NAME,$student->branch_id) : 'N/A';

            if ($birthday_sms !== '1') {
                Log::info("Birthday SMS feature is disabled for branch: {$student->branch_id}");
                continue;
            }

            $number = $student->mobile_no;
            if ($number) {

                $smsBody = "Dear ".$student->name.",\n";
                $smsBody .= "Happy Birthday to you!\n";
                $smsBody .= "Wishing you a wonderful year ahead.\n";
                $smsBody .= "Regards,\n";
                $smsBody .= $school_short_name;

                if (isValidBangladeshiNumber($number)) {
                    try {
                        SendSmsJob::dispatch($number, $smsBody, 'general', ['branch_id' => $student->branch_id]);
                        $successCount++;
                    } catch (\Exception $e) {
                        Log::error("Failed to dispatch SMS for $number: " . $e->getMessage());
                        $failCount++;
                    }
                } else {
                    $invalidNumbers[] = $number;
                    $failCount++;
                }
                Log::info("Sending birthday SMS to $number");
            }
        }

        Log::info("Birthday SMS Summary: Success = $successCount, Failed = $failCount");

        if (!empty($invalidNumbers)) {
            Log::warning('Invalid numbers: ' . implode(', ', $invalidNumbers));
        }

    }

}
