<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\Database;
use App\Core\Logger;
use App\Modules\ServiceCatalog\Models\ServicePrice;
use App\Modules\Rules\Services\RuleEngine;

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");
        $devFeeData = RuleEngine::get('DEVELOPMENT_FEE');
        $devFee = $devFeeData['amount'] ?? '35.00';
        $memberRate = ServicePrice::getPrice('SVC_ANNUAL_MEMBER', '492.00');
        $spouseRate = ServicePrice::getPrice('SVC_ANNUAL_SPOUSE', '492.00');
        $childRate = ServicePrice::getPrice('SVC_ANNUAL_CHILD', '222.00');
        $tempRate = ServicePrice::getPrice('SVC_ANNUAL_TEMP', '222.00');
        $ts = date('Y-m-d H:i:s');

        foreach ($members as $m) {
            // 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'    => $spouseRate,
                    'development_fee'=> $devFee,
                    'total_amount'   => bcadd($spouseRate, $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']]);
            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'    => $tempRate,
                    'development_fee'=> $devFee,
                    'total_amount'   => bcadd($tempRate, $devFee, 2),
                    'status'         => 'pending',
                    'created_at'     => $ts,
                    'updated_at'     => $ts,
                ]);
                $processed++;
            }
        }

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