<?php

namespace App\Commands;

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

/**
 * تشغيل: php spark app:check-renewals
 * أضفها في cron يومياً.
 */
class CheckServiceRenewals extends BaseCommand
{
    protected $group = 'App';
    protected $name = 'app:check-renewals';
    protected $description = 'فحص مواعيد تجديد الاستضافات والنطاقات وإرسال تنبيه بريد';

    public function run(array $params)
    {
        $companyModel = new CompanyModel();
        $settingModel = new NotificationSettingModel();
        $serviceModel = new ServiceModel();
        $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, 'renewal_days_before');

            foreach ($days as $d) {
                $services = $serviceModel->dueForRenewalIn($company['id'], $d);

                foreach ($services as $service) {
                    if ($logModel->alreadySentToday('renewal', $service['id'])) continue;

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

                    $this->sendRenewalEmail($client, $service, $d);
                    $this->notifyAdmin($company, $setting, $service, $d, 'renewal');

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

                    CLI::write("تم إرسال تنبيه تجديد للخدمة #{$service['id']}", 'green');
                }
            }
        }
    }

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

        $subject = renewal_email_subject($service['name'], $locale);
        $body = renewal_email_body($service, $days, $locale);

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

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

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

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