<?php

namespace Config;

use CodeIgniter\Config\BaseService;
use App\Services\SemesterScoreService;
use App\Models\SemesterScoreModel;
use App\Models\ConfigurationModel;
use App\Services\Calculators\HomeworkCalculator;
use App\Services\Calculators\QuizCalculator;
use App\Services\Calculators\ProjectCalculator;
use App\Services\Calculators\AttendanceCalculator;
use App\Models\HomeworkModel;
use App\Models\QuizModel;
use App\Models\ProjectModel;
use App\Models\AttendanceRecordModel;
use App\Models\CalendarModel;
use PHPMailer\PHPMailer\PHPMailer;


/**
 * Services Configuration file.
 *
 * Services are simply other classes/libraries that the system uses
 * to do its job. This is used by CodeIgniter to allow the core of the
 * framework to be swapped out easily without affecting the usage within
 * the rest of your application.
 *
 * This file holds any application-specific services, or service overrides
 * that you might need. An example has been included with the general
 * method format you should use for your service methods. For more examples,
 * see the core Services file at system/Config/Services.php.
 */
class Services extends BaseService
{
    /**
     * Override CI Email service to enforce a global Reply-To.
     */
    public static function email(?array $config = null, bool $getShared = true)
    {
        if ($getShared) {
            return static::getSharedInstance('email', $config);
        }

        $config = $config ?? config('Email');
        $email  = new \CodeIgniter\Email\Email($config);
        try {
            $rtEmail = env('MAIL_DEFAULT_REPLY_TO');
            $rtNameRaw = env('MAIL_DEFAULT_REPLY_TO_NAME');
            $rtName = 'Al Rahma Sunday School';
            if (is_string($rtNameRaw)) {
                $rtNameRaw = trim($rtNameRaw);
                if ($rtNameRaw !== '' && !preg_match('/^no[- ]?repl(?:y|ay)$/i', $rtNameRaw)) {
                    $rtName = $rtNameRaw;
                }
            }
            if ($rtEmail) {
                $email->setReplyTo($rtEmail, $rtName);
            }
        } catch (\Throwable $e) {
            // Ignore; ensure service is still usable even if headers not yet setable
        }
        return $email;
    }
    public static function PHPMailer(bool $getShared = true)
    {
        if ($getShared) {
            return static::getSharedInstance('PHPMailer');
        }

        $mail = new PHPMailer(true);

        // Set up your PHPMailer configuration
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com'; // Your SMTP host
        $mail->SMTPAuth = true;
        $mail->Username = 'alrahma.sunday.school@gmail.com'; // Your email
        $mail->Password = 'psnp emdq dykw ypul'; // Your email password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = 465;

        $mail->Timeout = 10;               // ⏱ 10-second timeout max
        $mail->SMTPKeepAlive = false;     // Prevent hanging connections
        $mail->SMTPDebug = 0;             // Set to 2 temporarily for debugging

        $mail->SMTPDebug = 2; // You can set it to 1, 2, or 3 for increasing verbosity
        $mail->Debugoutput = 'html'; // You can output it to 'html' or 'error_log'

        return $mail;
    }

    /**
     * Build (or fetch a shared) SemesterScoreService instance.
     *
     * Usage:
     *   $svc = service('semesterScoreService');             // shared
     *   $svc = \Config\Services::semesterScoreService();    // shared
     *   $svc = \Config\Services::semesterScoreService(false); // NEW instance (not shared)
     */
    public static function semesterScoreService(bool $getShared = true): SemesterScoreService
    {
        if ($getShared) {
            return static::getSharedInstance('semesterScoreService');
        }

        // Core models
        $scoreModel  = new SemesterScoreModel();
        $configModel = new ConfigurationModel();

        // Calculators (inject their models)
        $homeworkCalc   = new HomeworkCalculator(new HomeworkModel());
        $quizCalc       = new QuizCalculator(new QuizModel());
        $projectCalc    = new ProjectCalculator(new ProjectModel());
        $attendanceCalc = new AttendanceCalculator(
            new AttendanceRecordModel(),
            new ConfigurationModel(),
            new CalendarModel()
        );

        // If you later add Midterm/Final/Participation calculators, plug them in here.

        return new SemesterScoreService(
            $scoreModel,
            $configModel,
            $homeworkCalc,
            $quizCalc,
            $projectCalc,
            $attendanceCalc
        );
    }

    public static function roleService($getShared = true)
    {
        if ($getShared) {
            return static::getSharedInstance('roleService');
        }
        return new \App\Services\RoleService();
    }

     public static function emailService($getShared = true)
    {
        if ($getShared) {
            return static::getSharedInstance('emailService');
        }
        // Replace with your real EmailService class + constructor args
        return new \App\Services\EmailService();
    }

    /**
     * TimeService shared builder (timezone detection + conversions).
     */
    public static function timeService(bool $getShared = true): \App\Services\TimeService
    {
        if ($getShared) {
            return static::getSharedInstance('timeService');
        }
        return new \App\Services\TimeService();
    }

    /**
     * Shared API client for outbound HTTP to external services.
     */
    public static function apiClient(bool $getShared = true): \App\Services\ApiClient
    {
        if ($getShared) {
            return static::getSharedInstance('apiClient');
        }

        $apiConfig = config('Api');
        $options = [
            'baseURI' => $apiConfig->baseURL ?: null,
            'timeout' => $apiConfig->timeout,
            'headers' => $apiConfig->defaultHeaders,
        ];
        // Remove null/empty values that may cause issues
        $options = array_filter($options, static function ($v) {
            return $v !== null && $v !== '';
        });

        $http = static::curlrequest($options);
        return new \App\Services\ApiClient($http, $apiConfig);
    }

    public static function schoolYearContext(bool $getShared = true): \App\Services\SchoolYearContextService
    {
        if ($getShared) {
            return static::getSharedInstance('schoolYearContext');
        }

        return new \App\Services\SchoolYearContextService(
            model(\App\Models\SchoolYearModel::class),
            static::schoolYearAccessPolicy()
        );
    }

    public static function schoolYearAccessPolicy(bool $getShared = true): \App\Services\SchoolYearAccessPolicy
    {
        if ($getShared) {
            return static::getSharedInstance('schoolYearAccessPolicy');
        }

        return new \App\Services\SchoolYearAccessPolicy();
    }

    public static function schoolYearViewData(bool $getShared = true): \App\Services\SchoolYearViewDataService
    {
        if ($getShared) {
            return static::getSharedInstance('schoolYearViewData');
        }

        return new \App\Services\SchoolYearViewDataService(
            static::schoolYearContext(),
            static::schoolYearAccessPolicy()
        );
    }

    public static function schoolYearWriteGuard(bool $getShared = true): \App\Services\SchoolYearWriteGuard
    {
        if ($getShared) {
            return static::getSharedInstance('schoolYearWriteGuard');
        }

        return new \App\Services\SchoolYearWriteGuard();
    }

    public static function schoolYearValidation(bool $getShared = true): \App\Services\SchoolYearValidationService
    {
        if ($getShared) {
            return static::getSharedInstance('schoolYearValidation');
        }

        return new \App\Services\SchoolYearValidationService(
            model(\App\Models\SchoolYearModel::class)
        );
    }

    public static function schoolYearManagement(bool $getShared = true): \App\Services\SchoolYearManagementService
    {
        if ($getShared) {
            return static::getSharedInstance('schoolYearManagement');
        }

        return new \App\Services\SchoolYearManagementService(
            model(\App\Models\SchoolYearModel::class),
            model(\App\Models\ConfigurationModel::class),
            model(\App\Models\SchoolYearTransitionLogModel::class),
            model(\App\Models\SchoolYearClosingBatchModel::class),
            static::schoolYearValidation(),
            \Config\Database::connect()
        );
    }

    public static function schoolYearClosing(bool $getShared = true): \App\Services\SchoolYearClosingService
    {
        if ($getShared) {
            return static::getSharedInstance('schoolYearClosing');
        }

        return new \App\Services\SchoolYearClosingService(
            model(\App\Models\SchoolYearModel::class),
            model(\App\Models\SchoolYearClosingBatchModel::class),
            model(\App\Models\SchoolYearClosingItemModel::class),
            model(\App\Models\ConfigurationModel::class),
            static::schoolYearManagement(),
            \Config\Database::connect()
        );
    }
}
