<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\Database;
use App\Core\Logger;
use App\Modules\Notifications\Services\SmsService;

class AgeMonitorJob
{
    private Database $db;
    public function __construct(Database $db) { $this->db = $db; }

    public function shouldRun(): bool
    {
        // Daily at any hour
        return true;
    }

    public function run(): array
    {
        $processed = 0;

        // Update all children ages from DOB
        $this->db->query(
            "UPDATE children SET age_years = TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE()), age_months = TIMESTAMPDIFF(MONTH, date_of_birth, CURDATE()) % 12 WHERE date_of_birth IS NOT NULL AND date_of_birth > '1950-01-01' AND is_archived = 0"
        );

        // Children approaching 18 (3 months ahead)
        $approaching18 = $this->db->select(
            "SELECT c.id, c.full_name_ar, c.date_of_birth, m.id as member_id, m.full_name_ar as member_name, m.phone_mobile
             FROM children c JOIN members m ON m.id = c.member_id
             WHERE c.is_archived = 0 AND c.status = 'active'
             AND c.date_of_birth = DATE_SUB(CURDATE(), INTERVAL 18 YEAR) + INTERVAL 90 DAY"
        );
        foreach ($approaching18 as $child) {
            SmsService::sendFromTemplate('CHILD_AGE_18_ALERT', $child['phone_mobile'], [
                'member_name' => $child['member_name'],
                'child_name'  => $child['full_name_ar'],
                'date'        => date('Y-m-d', strtotime($child['date_of_birth'] . ' +18 years')),
            ], (int) $child['member_id']);
            $processed++;
        }

        // Children approaching 25 (3 months ahead)
        $approaching25 = $this->db->select(
            "SELECT c.id, c.full_name_ar, c.date_of_birth, c.gender, m.id as member_id, m.full_name_ar as member_name, m.phone_mobile
             FROM children c JOIN members m ON m.id = c.member_id
             WHERE c.is_archived = 0 AND c.status = 'active' AND c.gender = 'male'
             AND c.date_of_birth = DATE_SUB(CURDATE(), INTERVAL 25 YEAR) + INTERVAL 90 DAY"
        );
        foreach ($approaching25 as $child) {
            SmsService::sendFromTemplate('CHILD_AGE_25_ALERT', $child['phone_mobile'], [
                'member_name' => $child['member_name'],
                'child_name'  => $child['full_name_ar'],
                'date'        => date('Y-m-d', strtotime($child['date_of_birth'] . ' +25 years')),
            ], (int) $child['member_id']);
            $processed++;
        }

        // Auto-separate children at 25 (mandatory separation)
        $toSeparate = $this->db->select(
            "SELECT c.id, c.full_name_ar FROM children c
             WHERE c.is_archived = 0 AND c.status = 'active'
             AND c.date_of_birth <= DATE_SUB(CURDATE(), INTERVAL 25 YEAR)"
        );
        foreach ($toSeparate as $child) {
            $this->db->update('children', [
                'status'         => 'separated',
                'classification' => 'separated',
                'is_frozen'      => 1,
                'frozen_at'      => date('Y-m-d H:i:s'),
                'frozen_reason'  => 'فصل وجوبي — بلوغ سن 25',
                'updated_at'     => date('Y-m-d H:i:s'),
            ], '`id` = ?', [(int) $child['id']]);
            Logger::info("Auto-separated child #{$child['id']}: {$child['full_name_ar']}");
            $processed++;
        }

        // Auto-remove temporary members at 25
        $tempToRemove = $this->db->select(
            "SELECT t.id, t.full_name_ar FROM temporary_members t
             WHERE t.is_archived = 0 AND t.status = 'active'
             AND t.date_of_birth <= DATE_SUB(CURDATE(), INTERVAL 25 YEAR)"
        );
        foreach ($tempToRemove as $temp) {
            $this->db->update('temporary_members', [
                'status'      => 'inactive',
                'is_archived' => 1,
                'archived_at' => date('Y-m-d H:i:s'),
                'updated_at'  => date('Y-m-d H:i:s'),
            ], '`id` = ?', [(int) $temp['id']]);
            Logger::info("Auto-removed temp member #{$temp['id']}: {$temp['full_name_ar']}");
            $processed++;
        }

        return ['processed' => $processed];
    }
}