<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Cron extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->model('admin/Admin_model');
        $this->load->library('email');
    }

    /**
     * Aktifkan admin yang masa suspendnya sudah selesai
     * URL: /cron/activate_suspended_admins
     */
    public function activate_suspended_admins()
    {
        // Log start time
        $start_time = date('Y-m-d H:i:s');
        log_message('info', 'CRON: Starting activate_suspended_admins at ' . $start_time);
        
        // Get admin dengan suspend yang sudah expired
        $expired_admins = $this->Admin_model->get_expired_suspensions();
        
        $activated_count = 0;
        $failed_count = 0;
        
        if (!empty($expired_admins)) {
            foreach ($expired_admins as $admin) {
                try {
                    // Aktifkan admin kembali
                    $success = $this->Admin_model->activate_after_suspension($admin->id);
                    
                    if ($success) {
                        // Log aktivasi
                        $this->db->insert('admin_suspend_logs', [
                            'admin_id' => $admin->id,
                            'action' => 'auto_activate',
                            'type' => 'temporary',
                            'duration_days' => null,
                            'suspended_until' => $admin->suspended_until,
                            'reason' => 'Auto activation after suspension period ended',
                            'created_at' => date('Y-m-d H:i:s')
                        ]);
                        
                        // Kirim notifikasi email ke admin
                        $this->send_activation_email($admin);
                        
                        $activated_count++;
                        log_message('info', 'CRON: Admin ' . $admin->id . ' (' . $admin->email . ') activated successfully.');
                    } else {
                        $failed_count++;
                        log_message('error', 'CRON: Failed to activate admin ' . $admin->id);
                    }
                } catch (Exception $e) {
                    $failed_count++;
                    log_message('error', 'CRON: Error activating admin ' . $admin->id . ': ' . $e->getMessage());
                }
            }
            
            $message = "Auto activation completed:\n";
            $message .= "- Total processed: " . count($expired_admins) . "\n";
            $message .= "- Successfully activated: " . $activated_count . "\n";
            $message .= "- Failed: " . $failed_count . "\n";
            
            echo $message;
            log_message('info', 'CRON: ' . $message);
            
        } else {
            echo "No admins to activate.\n";
            log_message('info', 'CRON: No admins to activate.');
        }
        
        // Log end time
        $end_time = date('Y-m-d H:i:s');
        log_message('info', 'CRON: Finished activate_suspended_admins at ' . $end_time);
    }
    
    /**
     * Cek status suspend admin dan kirim reminder
     * URL: /cron/check_suspend_status
     */
    public function check_suspend_status()
    {
        log_message('info', 'CRON: Starting check_suspend_status');
        
        // Get semua admin yang sedang suspended
        $suspended_admins = $this->Admin_model->get_suspended_admins();
        
        $reminder_sent = 0;
        
        foreach ($suspended_admins as $admin) {
            if ($admin->suspended_until) {
                $days_left = ceil((strtotime($admin->suspended_until) - time()) / (60 * 60 * 24));
                
                // Kirim reminder 3 hari sebelum aktif kembali
                if ($days_left == 3) {
                    $this->send_reminder_email($admin, $days_left);
                    $reminder_sent++;
                    log_message('info', 'CRON: Reminder sent to admin ' . $admin->id . ' (' . $days_left . ' days left)');
                }
                
                // Kirim notifikasi 1 hari sebelum aktif kembali
                if ($days_left == 1) {
                    $this->send_last_day_email($admin);
                    log_message('info', 'CRON: Last day notification sent to admin ' . $admin->id);
                }
            }
        }
        
        echo "Suspend status check completed. Reminders sent: " . $reminder_sent . "\n";
        log_message('info', 'CRON: Suspend status check completed. Reminders sent: ' . $reminder_sent);
    }
    
    /**
     * Clean up old suspend logs
     * URL: /cron/cleanup_logs
     */
    public function cleanup_logs()
    {
        // Hapus logs yang lebih dari 90 hari
        $cutoff_date = date('Y-m-d H:i:s', strtotime('-90 days'));
        
        $this->db->where('created_at <', $cutoff_date);
        $deleted = $this->db->delete('admin_suspend_logs');
        
        echo "Cleaned up " . $deleted . " old log entries.\n";
        log_message('info', 'CRON: Cleaned up ' . $deleted . ' old log entries.');
    }
    
    /**
     * Kirim email notifikasi aktivasi
     */
    private function send_activation_email($admin)
    {
        $config = [
            'protocol' => 'smtp',
            'smtp_host' => 'ssl://smtp.gmail.com',
            'smtp_port' => 465,
            'smtp_user' => 'your-email@gmail.com',
            'smtp_pass' => 'your-password',
            'mailtype' => 'html',
            'charset' => 'utf-8',
            'newline' => "\r\n"
        ];
        
        $this->email->initialize($config);
        
        $this->email->from('noreply@koscare.com', 'KosCare System');
        $this->email->to($admin->email);
        $this->email->subject('Akun Telah Diaktifkan Kembali - KosCare');
        
        $message = '
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #4a90e2; color: white; padding: 20px; text-align: center; border-radius: 10px 10px 0 0; }
                .content { padding: 30px; background: #f9f9f9; border-radius: 0 0 10px 10px; }
                .footer { padding: 20px; text-align: center; font-size: 12px; color: #666; }
                .button { display: inline-block; padding: 12px 24px; background: #4a90e2; color: white; text-decoration: none; border-radius: 5px; margin: 20px 0; }
                .info-box { background: #e7f3ff; border-left: 4px solid #4a90e2; padding: 15px; margin: 20px 0; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h2>🎉 Akun Anda Telah Diaktifkan Kembali</h2>
                </div>
                <div class="content">
                    <p>Halo <strong>' . $admin->nama . '</strong>,</p>
                    
                    <p>Kami ingin menginformasikan bahwa akun Anda di <strong>KosCare</strong> telah diaktifkan kembali secara otomatis.</p>
                    
                    <div class="info-box">
                        <p><strong>Detail Aktivasi:</strong></p>
                        <ul>
                            <li>Masa suspensi sementara telah berakhir</li>
                            <li>Status akun: <strong>Aktif</strong></li>
                            <li>Tanggal aktivasi: ' . date('d M Y H:i') . '</li>
                        </ul>
                    </div>
                    
                    <p>Sekarang Anda dapat:</p>
                    <ul>
                        <li>✅ Login ke dashboard admin</li>
                        <li>✅ Menerima dan memproses laporan dari penghuni</li>
                        <li>✅ Mengelola kos dan penghuni</li>
                        <li>✅ Menggunakan semua fitur KosCare</li>
                    </ul>
                    
                    <div style="text-align: center; margin: 30px 0;">
                        <a href="' . base_url('admin') . '" class="button">Login ke Dashboard</a>
                    </div>
                    
                    <p>Jika Anda mengalami masalah saat login, silakan hubungi tim support kami.</p>
                </div>
                <div class="footer">
                    <p>&copy; ' . date('Y') . ' KosCare. Semua hak dilindungi.</p>
                    <p>Email ini dikirim secara otomatis, mohon tidak membalas email ini.</p>
                </div>
            </div>
        </body>
        </html>';
        
        $this->email->message($message);
        
        try {
            // Uncomment untuk mengirim email
            // if ($this->email->send()) {
            //     return true;
            // } else {
            //     log_message('error', 'Email sending failed: ' . $this->email->print_debugger());
            //     return false;
            // }
            return true; // Untuk testing, return true
        } catch (Exception $e) {
            log_message('error', 'Email exception: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Kirim email reminder
     */
    private function send_reminder_email($admin, $days_left)
    {
        // Implementasi email reminder
        // Sama seperti send_activation_email, tapi dengan konten reminder
        return true;
    }
    
    /**
     * Kirim email last day notification
     */
    private function send_last_day_email($admin)
    {
        // Implementasi email last day notification
        return true;
    }
    
    /**
     * Test cron job
     */
    public function test()
    {
        echo "Cron job is working properly!\n";
        echo "Server time: " . date('Y-m-d H:i:s') . "\n";
        echo "Timezone: " . date_default_timezone_get() . "\n";
        
        // Test database connection
        if ($this->db->conn_id) {
            echo "Database: Connected\n";
        } else {
            echo "Database: Not connected\n";
        }
    }
}