<?php
declare(strict_types=1);

namespace CronJobs;

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

/**
 * Daily: scans vendor invoices and AP records past due date,
 * updates status to 'overdue' and dispatches alerts.
 */
class OverdueInvoiceAlertJob
{
    private Database $db;
    public function __construct(Database $db) { $this->db = $db; }

    public function shouldRun(): bool
    {
        return true; // Runs daily
    }

    public function run(): array
    {
        $today = date('Y-m-d');
        $overdueCount = 0;

        // Update AP records that are past due
        $overdueAP = $this->db->select(
            "SELECT ap.*, s.`name_ar` as supplier_name
             FROM `accounts_payable` ap
             JOIN `suppliers` s ON s.`id` = ap.`supplier_id`
             WHERE ap.`due_date` < ?
               AND ap.`status` IN ('pending', 'partial')
               AND ap.`is_archived` = 0",
            [$today]
        );

        foreach ($overdueAP as $ap) {
            // Update status to overdue
            $this->db->update('accounts_payable', [
                'status'     => 'overdue',
                'updated_at' => date('Y-m-d H:i:s'),
            ], '`id` = ? AND `status` IN (\'pending\', \'partial\')', [(int) $ap['id']]);

            EventBus::dispatch('procurement.invoice_overdue', [
                'ap_id'          => (int) $ap['id'],
                'supplier_id'    => (int) $ap['supplier_id'],
                'supplier_name'  => $ap['supplier_name'] ?? '',
                'invoice_number' => $ap['invoice_number'] ?? '',
                'due_date'       => $ap['due_date'],
                'balance'        => (string) $ap['balance'],
                'days_overdue'   => (int) ((strtotime($today) - strtotime($ap['due_date'])) / 86400),
            ]);

            $overdueCount++;
        }

        // Also update vendor_invoices that are approved but past due
        $this->db->query(
            "UPDATE `vendor_invoices` SET `status` = 'overdue'
             WHERE `due_date` < ? AND `status` IN ('approved', 'partial_paid') AND `is_archived` = 0",
            [$today]
        );

        if ($overdueCount > 0) {
            Logger::info("Overdue invoice alert: {$overdueCount} AP record(s) marked overdue");
        }

        return ['overdue_invoices' => $overdueCount];
    }
}
