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

class Login extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('admin/Admin_model');
        $this->load->model('admin/Kos_model');
        $this->load->library('session');
        $this->load->library('email');
        $this->load->helper(array('url', 'form', 'security'));
    }

    public function index()
    {
        if ($this->session->userdata('admin_logged_in')) {
            redirect('admin/dashboard');
        }
        $data['error'] = $this->session->flashdata('error');
        $this->load->view('admin/login', $data);
    }

    public function action()
    {
        $email = $this->input->post('email');
        $password = $this->input->post('password');

        $admin = $this->Admin_model->get_by_email($email);
        if ($admin) {
            if ($admin->status == 'nonaktif' && $admin->is_suspended == 1 && $admin->suspended_until === null) {
                $this->session->set_flashdata(
                    'error',
                    '❌ <strong>AKUN DINONAKTIFKAN PERMANEN</strong><br>' .
                        'Akun Anda telah dinonaktifkan permanen oleh Super Admin.<br>' .
                        '<strong>Alasan:</strong> ' . ($admin->suspension_reason ?: 'Tidak disebutkan') . '<br>' .
                        'Hubungi Super Admin untuk informasi lebih lanjut.'
                );
                redirect('admin');
            }
            if ($admin->is_suspended == 1 && $admin->suspended_until !== null) {
                $suspended_until = strtotime($admin->suspended_until);
                $current_time = time();
                if ($suspended_until > $current_time) {
                    $days_left = ceil(($suspended_until - $current_time) / (60 * 60 * 24));
                    $suspended_date = date('d M Y H:i', $suspended_until);
                    $this->session->set_flashdata(
                        'error',
                        '⏳ <strong>AKUN DINONAKTIFKAN SEMENTARA</strong><br>' .
                            'Akun Anda dinonaktifkan sementara hingga: <strong>' . $suspended_date . '</strong><br>' .
                            '<strong>Sisa waktu:</strong> ' . $days_left . ' hari<br>' .
                            '<strong>Alasan:</strong> ' . ($admin->suspension_reason ?: 'Tidak disebutkan') . '<br>' .
                            'Anda dapat login kembali setelah tanggal tersebut.'
                    );
                    redirect('admin');
                } else {
                    $this->Admin_model->update($admin->id, [
                        'is_suspended' => 0,
                        'suspended_until' => null,
                        'suspension_reason' => null,
                        'status' => 'aktif',
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);
                    $this->db->insert('admin_suspend_logs', [
                        'admin_id' => $admin->id,
                        'action' => 'auto_activate',
                        'type' => 'temporary',
                        'reason' => 'Auto activation after suspension period ended',
                        'created_at' => date('Y-m-d H:i:s')
                    ]);
                    $this->send_activation_notification($admin);
                }
            }
            if (password_verify($password, $admin->password)) {
                if ($admin->warning_count > 0) {
                    $warning_reset_days = 30;
                    $last_warning_date = $admin->updated_at ?: $admin->created_at;
                    $days_since_warning = floor((time() - strtotime($last_warning_date)) / (60 * 60 * 24));
                    if ($days_since_warning >= $warning_reset_days) {
                        $this->Admin_model->update($admin->id, [
                            'warning_count' => 0,
                            'updated_at' => date('Y-m-d H:i:s')
                        ]);
                    }
                }
                $this->session->set_userdata([
                    'admin_logged_in' => true,
                    'admin_id'        => $admin->id,
                    'admin_name'      => $admin->nama,
                    'admin_email'     => $admin->email,
                    'admin_warning_count' => $admin->warning_count,
                    'is_suspended'    => $admin->is_suspended
                ]);
                redirect('admin/dashboard');
            }
        }
        $this->session->set_flashdata('error', '❌ Email atau password salah');
        redirect('admin');
    }
    public function proses()
    {
        $email    = $this->input->post('email', true);
        $password = $this->input->post('password', true);
        $admin = $this->Admin_model->get_by_email($email);
        if ($admin) {
            if ($admin->status == 'nonaktif' && $admin->is_suspended == 1 && $admin->suspended_until === null) {
                $this->session->set_flashdata(
                    'error',
                    '❌ <strong>AKUN DINONAKTIFKAN PERMANEN</strong><br>' .
                        'Akun Anda telah dinonaktifkan permanen oleh Super Admin.'
                );
                redirect('admin/login');
            }
            if ($admin->is_suspended == 1 && $admin->suspended_until !== null) {
                $suspended_until = strtotime($admin->suspended_until);
                $current_time = time();
                if ($suspended_until > $current_time) {
                    $days_left = ceil(($suspended_until - $current_time) / (60 * 60 * 24));
                    $suspended_date = date('d M Y H:i', $suspended_until);
                    $this->session->set_flashdata(
                        'error',
                        '⏳ <strong>AKUN DINONAKTIFKAN SEMENTARA</strong><br>' .
                            'Akun Anda dinonaktifkan sementara hingga: ' . $suspended_date . '<br>' .
                            'Sisa waktu: ' . $days_left . ' hari'
                    );
                    redirect('admin/login');
                }
            }
            if (password_verify($password, $admin->password)) {
                $list_kos = $this->Kos_model->get_by_admin($admin->id);
                $default_kos_id = !empty($list_kos) ? $list_kos[0]->id_kos : null;
                $this->session->set_userdata([
                    'admin_logged_in' => true,
                    'admin_id'        => $admin->id,
                    'id_admin'        => $admin->id,
                    'admin_name'      => $admin->nama,
                    'list_kos'        => $list_kos,
                    'id_kos'          => $default_kos_id
                ]);
                redirect('admin/dashboard');
            }
        }
        $this->session->set_flashdata('error', '❌ Email atau password salah.');
        redirect('admin/login');
    }
    private function send_activation_notification($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 Anda 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; }
                .content { padding: 20px; background: #f5f5f5; }
                .footer { padding: 10px; text-align: center; font-size: 12px; color: #666; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h2>Akun Telah Diaktifkan Kembali</h2>
                </div>
                <div class="content">
                    <p>Halo <strong>' . $admin->nama . '</strong>,</p>
                    <p>Akun Anda di KosCare telah diaktifkan kembali secara otomatis.</p>
                    <p>Masa suspensi sementara Anda telah berakhir dan Anda sekarang dapat:</p>
                    <ul>
                        <li>Login ke dashboard admin</li>
                        <li>Menerima laporan dari penghuni</li>
                        <li>Mengelola kos Anda kembali</li>
                    </ul>
                    <p style="text-align: center; margin-top: 30px;">
                        <a href="' . base_url('admin') . '" style="background: #4a90e2; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;">Login Sekarang</a>
                    </p>
                </div>
                <div class="footer">
                    <p>&copy; ' . date('Y') . ' KosCare. Semua hak dilindungi.</p>
                </div>
            </div>
        </body>
        </html>';
        $this->email->message($message);
    }
    public function logout()
    {
        $this->session->sess_destroy();
        redirect('admin/login');
    }
    public function set_kos($id_kos)
    {
        $this->session->set_userdata('id_kos', $id_kos);
        redirect('admin/dashboard');
    }
}
