<?php

namespace App\Console\Commands;

use App\Jobs\SendSmsJob;
use App\Constants\Settings;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class StudentBirthdayWishes extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:student-birthday-wishes';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send SMS wishes to students on their birthday';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Birthday SMS job started');

        $today = Carbon::now()->format('m-d'); // Prefer Carbon over raw date()
        

        $successCount = 0;
        $failCount = 0;
        $invalidNumbers = [];

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

        $this->info("Found " . $students->count() . " students with birthday today: $today");

        if ($students->isEmpty()) {
            $this->info("No students have birthday today: $today");
            Log::info("No birthday SMS sent. No students found for $today.");
            return;
        }

        foreach ($students as $student) {

            $birthday_sms = get_setting_value(Settings::BIRTHDAY_SMS,$student->branch_id) ? 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{$school_short_name}";

                if (function_exists('isValidBangladeshiNumber') && isValidBangladeshiNumber($number)) {
                    try {
                        SendSmsJob::dispatch($number, $smsBody, 'general', ['branch_id' => $student->branch_id]);
                        $successCount++;
                        $this->info("Birthday SMS dispatched to: {$student->name} ($number)");
                    } catch (\Exception $e) {
                        Log::error("SMS failed for {$number}: " . $e->getMessage());
                        $failCount++;
                    }
                } else {
                    $invalidNumbers[] = $number;
                    $failCount++;
                    $this->warn(" Invalid mobile number: $number");
                }
            }
        }

        // Final logging
        $this->info("SMS Sent: $successCount, Failed: $failCount");
        Log::info("Birthday SMS Summary: Success = $successCount, Failed = $failCount");

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

        $this->info('Birthday SMS job completed');
    }
}