<?php

namespace Modules\Notification\Models;

use CodeIgniter\Model;

class NotificationScheduleModel extends Model
{
    protected $DBGroup              = 'default';
    protected $table                = 'notification_schedules';
    protected $primaryKey           = 'id';
    protected $useAutoIncrement     = true;
    protected $insertID             = 0;
    protected $returnType           = 'object';
    protected $useSoftDeletes       = false;
    protected $protectFields        = true;
    protected $allowedFields        = [
        'id', 'notification_id', 'next_run_date', 'last_run_date', 'is_active'
    ];

    // Dates
    protected $useTimestamps        = true;
    protected $dateFormat           = 'datetime';
    protected $createdField         = 'created_at';
    protected $updatedField         = 'updated_at';
    protected $deletedField         = '';

    // Validation
    protected $validationRules      = [
        'notification_id' => 'required|integer',
        'next_run_date' => 'required|valid_date'
    ];
    
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks       = true;
    protected $beforeInsert         = [];
    protected $afterInsert          = [];
    protected $beforeUpdate         = [];
    protected $afterUpdate          = [];
    protected $beforeFind           = [];
    protected $afterFind            = [];
    protected $beforeDelete         = [];
    protected $afterDelete          = [];

    /**
     * Get schedules ready to run
     */
    public function getSchedulesToRun()
    {
        return $this->where('is_active', 1)
                    ->where('next_run_date <=', date('Y-m-d H:i:s'))
                    ->findAll();
    }

    /**
     * Update schedule after execution
     */
    public function updateAfterRun($scheduleId, $nextRunDate)
    {
        return $this->update($scheduleId, [
            'last_run_date' => date('Y-m-d H:i:s'),
            'next_run_date' => $nextRunDate
        ]);
    }

    /**
     * Deactivate schedule
     */
    public function deactivate($scheduleId)
    {
        return $this->update($scheduleId, ['is_active' => 0]);
    }

    /**
     * Calculate next run date based on repeat option
     */
    public function calculateNextRunDate($repeatOption, $baseDate = null)
    {
        if ($baseDate === null) {
            $baseDate = date('Y-m-d H:i:s');
        }

        $date = new \DateTime($baseDate);

        switch ($repeatOption) {
            case 'daily':
                $date->modify('+1 day');
                break;
            case 'weekly':
                $date->modify('+1 week');
                break;
            case 'monthly':
                $date->modify('+1 month');
                break;
            default:
                return null; // No repeat
        }

        return $date->format('Y-m-d H:i:s');
    }
}
