<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\Database;
use App\Core\Logger;

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

    public function shouldRun(): bool
    {
        // Run in July only
        return (int) date('n') === 7 && (int) date('j') <= 7;
    }

    public function run(): array
    {
        $year = (int) date('Y');
        $financialYear = $year . '/' . ($year + 1);
        $processed = 0;

        // Check if already generated
        $existing = $this->db->selectOne("SELECT COUNT(*) as c FROM subscriptions WHERE financial_year = ?", [$financialYear]);
        if ((int) ($existing['c'] ?? 0) > 0) {
            return ['processed' => 0]; // Already generated
        }

        // Get all active members
        $members = $this->db->select("SELECT id, full_name_ar, membership_type FROM members WHERE status = 'active' AND is_archived = 0");
        $devFee = '35.00';
        $ts = date('Y-m-d H:i:s');

        foreach ($members as $m) {
            $memberRate = '492.00'; // Default 2025/2026

            // Generate for member
            $this->db->insert('subscriptions', [
                'member_id'      => (int) $m['id'],
                'financial_year' => $financialYear,
                'person_type'    => 'member',
                'person_id'      => (int) $m['id'],
                'person_name'    => $m['full_name_ar'],
                'base_amount'    => $memberRate,
                'development_fee'=> $devFee,
                'total_amount'   => bcadd($memberRate, $devFee, 2),
                'status'         => 'pending',
                'created_at'     => $ts,
                'updated_at'     => $ts,
            ]);
            $processed++;

            // Generate for spouses
            $spouses = $this->db->select("SELECT id, full_name_ar FROM spouses WHERE member_id = ? AND is_archived = 0 AND status = 'active'", [(int) $m['id']]);
            foreach ($spouses as $sp) {
                $this->db->insert('subscriptions', [
                    'member_id'      => (int) $m['id'],
                    'financial_year' => $financialYear,
                    'person_type'    => 'spouse',
                    'person_id'      => (int) $sp['id'],
                    'person_name'    => $sp['full_name_ar'],
                    'base_amount'    => $memberRate,
                    'development_fee'=> $devFee,
                    'total_amount'   => bcadd($memberRate, $devFee, 2),
                    'status'         => 'pending',
                    'created_at'     => $ts,
                    'updated_at'     => $ts,
                ]);
                $processed++;
            }

            // Generate for children
            $children = $this->db->select("SELECT id, full_name_ar FROM children WHERE member_id = ? AND is_archived = 0 AND status = 'active'", [(int) $m['id']]);
            $childRate = '222.00';
            foreach ($children as $ch) {
                $this->db->insert('subscriptions', [
                    'member_id'      => (int) $m['id'],
                    'financial_year' => $financialYear,
                    'person_type'    => 'child',
                    'person_id'      => (int) $ch['id'],
                    'person_name'    => $ch['full_name_ar'],
                    'base_amount'    => $childRate,
                    'development_fee'=> $devFee,
                    'total_amount'   => bcadd($childRate, $devFee, 2),
                    'status'         => 'pending',
                    'created_at'     => $ts,
                    'updated_at'     => $ts,
                ]);
                $processed++;
            }

            // Generate for temporary members
            $temps = $this->db->select("SELECT id, full_name_ar FROM temporary_members WHERE member_id = ? AND is_archived = 0 AND status = 'active'", [(int) $m['id']]);
            foreach ($temps as $tmp) {
                $this->db->insert('subscriptions', [
                    'member_id'      => (int) $m['id'],
                    'financial_year' => $financialYear,
                    'person_type'    => 'temporary',
                    'person_id'      => (int) $tmp['id'],
                    'person_name'    => $tmp['full_name_ar'],
                    'base_amount'    => $childRate,
                    'development_fee'=> $devFee,
                    'total_amount'   => bcadd($childRate, $devFee, 2),
                    'status'         => 'pending',
                    'created_at'     => $ts,
                    'updated_at'     => $ts,
                ]);
                $processed++;
            }
        }

        Logger::info("Subscription generation complete for {$financialYear}: {$processed} records");
        return ['processed' => $processed];
    }
}