<?php

namespace App\Commands;

use App\Models\ClientModel;
use App\Models\CompanyModel;
use App\Models\InvoiceModel;
use App\Models\NotificationLogModel;
use App\Models\NotificationSettingModel;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;

/**
 * تشغيل: php spark app:check-invoice-due-dates
 */
class CheckInvoiceDueDates extends BaseCommand
{
    protected $group = 'App';
    protected $name = 'app:check-invoice-due-dates';
    protected $description = 'فحص الفواتير المستحقة قريباً وإرسال تنبيه بقيمتها';

    public function run(array $params)
    {
        $companyModel = new CompanyModel();
        $settingModel = new NotificationSettingModel();
        $invoiceModel = new InvoiceModel();
        $logModel = new NotificationLogModel();
        $clientModel = new ClientModel();

        $companies = $companyModel->where('is_active', 1)->findAll();

        foreach ($companies as $company) {
            $setting = $settingModel->where('company_id', $company['id'])->first();
            $days = $settingModel->daysArray($setting, 'invoice_due_days_before');

            foreach ($days as $d) {
                $invoices = $invoiceModel->dueIn($company['id'], $d);

                foreach ($invoices as $invoice) {
                    if ($logModel->alreadySentToday('invoice_due', $invoice['id'])) continue;

                    $client = $clientModel->find($invoice['client_id']);
                    if (! $client) continue;

                    $this->sendInvoiceEmail($client, $invoice, $d);
                    $this->notifyAdmin($company, $setting, $invoice, $d);

                    $logModel->insert([
                        'company_id' => $company['id'],
                        'type' => 'invoice_due',
                        'related_id' => $invoice['id'],
                        'channel' => 'mail',
                        'sent_at' => date('Y-m-d H:i:s'),
                    ]);

                    CLI::write("تم إرسال تنبيه فاتورة #{$invoice['invoice_number']}", 'green');
                }
            }
        }
    }

    private function sendInvoiceEmail(array $client, array $invoice, int $days): void
    {
        $locale = $client['preferred_locale'] ?? 'ar';
        helper('email_locale');

        $subject = invoice_email_subject($invoice['invoice_number'], $locale);
        $body = invoice_email_body($invoice, $days, $locale);

        $email = \Config\Services::email();
        $email->setTo($client['email']);
        $email->setSubject($subject);
        $email->setMessage($body);
        $email->send();
    }

    /**
     * إرسال نسخة من التنبيه لبريد الأدمن الخاص بالشركة، أو بريد الشركة نفسها كاحتياط.
     */
    private function notifyAdmin(array $company, ?array $setting, array $invoice, int $days): void
    {
        $adminEmail = $setting['admin_notification_email'] ?? $company['email'] ?? null;
        if (! $adminEmail) return;

        helper('email_locale');
        $subject = '[نسخة للإدارة] ' . invoice_email_subject($invoice['invoice_number'], 'ar');
        $body = "تنبيه بخصوص فاتورة عميل:\n\n" . invoice_email_body($invoice, $days, 'ar');

        $email = \Config\Services::email();
        $email->setTo($adminEmail);
        $email->setSubject($subject);
        $email->setMessage($body);
        $email->send();
    }
}
