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

class Admin extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();

        // Enable error reporting for debugging
        error_reporting(E_ALL);
        ini_set('display_errors', 1);

        // Load models
        $this->load->model('admin/Admin_model');
        $this->load->model('admin/Kos_model');
        $this->load->model('admin/Payment_model');
        $this->load->model('admin/Laporan_model');
        $this->load->model('admin/Subscription_model');

        // Load helpers and libraries
        $this->load->helper(array('url', 'form', 'security'));
        $this->load->library('session');

        // Check login for all methods except login and register
        $current_method = $this->router->fetch_method();
        $excluded_methods = ['index', 'login', 'action', 'proses', 'logout', 'register'];

        if (!in_array($current_method, $excluded_methods) && !$this->session->userdata('admin_logged_in')) {
            redirect('admin/login');
        }
    }

    /**
     * Halaman login (default)
     */
    public function index()
    {
        // If already logged in, redirect to dashboard
        if ($this->session->userdata('admin_logged_in')) {
            redirect('admin/dashboard');
        }

        $data['error'] = $this->session->flashdata('error');
        $this->load->view('admin/login', $data);
    }

    /**
     * Alias untuk index (login page)
     */
    public function login()
    {
        $this->index();
    }

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

        $admin = $this->Admin_model->get_by_email($email);

        // Check if admin exists
        if ($admin) {
            // Check if admin suspended
            if ($admin->is_suspended == 1 && $admin->suspended_until !== null) {
                if (strtotime($admin->suspended_until) > time()) {
                    // Admin still suspended
                    $this->session->set_flashdata(
                        'error',
                        'Akun Anda dinonaktifkan sementara hingga ' .
                            date('d M Y H:i', strtotime($admin->suspended_until)) .
                            '. Alasan: ' . ($admin->suspension_reason ?: 'Tidak disebutkan')
                    );
                    redirect('admin');
                } else {
                    // Suspension period ended, reactivate
                    $this->Admin_model->update($admin->id, [
                        'is_suspended' => 0,
                        'suspended_until' => null,
                        'suspension_reason' => null
                    ]);
                }
            }

            // Check if admin permanently disabled
            if ($admin->status == 'nonaktif' && $admin->is_suspended == 1 && $admin->suspended_until === null) {
                $this->session->set_flashdata(
                    'error',
                    'Akun Anda dinonaktifkan permanen oleh Super Admin. Alasan: ' .
                        ($admin->suspension_reason ?: 'Tidak disebutkan')
                );
                redirect('admin');
            }

            // Verify password
            if (password_verify($password, $admin->password)) {
                // Reset warning if needed
                if ($admin->warning_count > 0) {
                    $warning_reset_days = 30; // Reset after 30 days
                    $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')
                        ]);
                    }
                }

                // Get all kos owned by admin
                $list_kos = $this->Kos_model->get_by_admin($admin->id);

                // Set default kos (first one)
                $default_kos_id = !empty($list_kos) ? $list_kos[0]->id_kos : null;

                // Set session data
                $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,
                    'list_kos'        => $list_kos,
                    'id_kos'          => $default_kos_id
                ]);

                // Redirect to dashboard
                redirect('admin/dashboard');
            }
        }

        // If email/password wrong
        $this->session->set_flashdata('error', 'Email atau password salah');
        redirect('admin');
    }

    /**
     * Alternate login process
     */
    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 && password_verify($password, $admin->password)) {
            // Get all kos owned by admin
            $list_kos = $this->Kos_model->get_by_admin($admin->id);

            // Set default kos (first one)
            $default_kos_id = !empty($list_kos) ? $list_kos[0]->id_kos : null;

            // Set session data
            $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');
        } else {
            $this->session->set_flashdata('error', 'Email atau password salah.');
            redirect('admin/login');
        }
    }

    /**
     * Dashboard utama
     */
    public function dashboard()
    {
        $id_admin = $this->session->userdata('admin_id');

        // Get all kos owned by this admin
        $data['list_kos'] = $this->Kos_model->get_by_admin($id_admin);

        // Get all penghuni from all kos owned by admin
        $data['list_penghuni'] = $this->Kos_model->get_all_penghuni_by_admin($id_admin);
        $data['total_penghuni'] = !empty($data['list_penghuni']) ? count($data['list_penghuni']) : 0;

        // Count reports from Kos
        $total_laporan = 0;
        $total_pending = 0;
        $total_proses  = 0;
        $total_selesai = 0;

        foreach ($data['list_kos'] as $kos) {
            $total_laporan += $this->Laporan_model->count_all_by_kos($kos->id_kos);
            $total_pending += $this->Laporan_model->count_by_status_kos('Diajukan', $kos->id_kos);
            $total_proses  += $this->Laporan_model->count_by_status_kos('Diproses', $kos->id_kos);
            $total_selesai += $this->Laporan_model->count_by_status_kos('Selesai', $kos->id_kos);
        }

        $data['total_laporan']   = $total_laporan;
        $data['laporan_pending'] = $total_pending;
        $data['laporan_proses']  = $total_proses;
        $data['laporan_selesai'] = $total_selesai;

        // Recent activities
        $data['recent_activities'] = $this->Laporan_model->get_recent_activities_by_admin($id_admin, 10);

        // Check subscription status
        $data['has_subscription'] = $this->Subscription_model->check_subscription($id_admin);
        $data['active_subscription'] = $this->Subscription_model->get_active_subscription($id_admin);

        // Get admin details including warning count
        $admin = $this->Admin_model->get($id_admin);

        // Set last_warning_date untuk digunakan di view
        $data['last_warning_date'] = null;
        if (!empty($admin->updated_at) || !empty($admin->created_at)) {
            $data['last_warning_date'] = !empty($admin->updated_at) ? $admin->updated_at : $admin->created_at;
        }

        // Initialize all user report variables with default values
        $data['user_reports_count'] = 0;
        $data['pending_reports_count'] = 0;
        $data['user_reports_list'] = [];
        $data['last_user_report'] = null;

        // Load Report_model for user reports
        $this->load->model('superadmin/Report_model');

        try {
            // Get user reports using methods from your Report_model
            $user_reports = $this->Report_model->get_by_admin($id_admin);
            $pending_reports = $this->Report_model->get_by_admin_with_details($id_admin, 'pending');

            $data['user_reports_count'] = $this->Report_model->count_by_admin($id_admin);
            $data['pending_reports_count'] = $this->Report_model->count_by_admin_status($id_admin, 'pending');

            // Get recent user reports list
            $data['user_reports_list'] = $this->Report_model->get_by_admin_limit($id_admin, 5);

            // Get last report date
            $data['last_user_report'] = $this->Report_model->get_last_by_admin($id_admin);
        } catch (Exception $e) {
            // Fallback jika ada error
            error_log('Report_model error: ' . $e->getMessage());

            // Query langsung ke database jika tabel reports ada
            if ($this->db->table_exists('reports')) {
                // Count total reports
                $this->db->where('id_admin', $id_admin);
                $data['user_reports_count'] = $this->db->count_all_results('reports');

                // Count pending reports
                $this->db->where('id_admin', $id_admin);
                $this->db->where('status', 'pending');
                $data['pending_reports_count'] = $this->db->count_all_results('reports');

                // Get recent reports
                if ($data['user_reports_count'] > 0) {
                    $this->db->select('r.*, p.nama_penghuni, p.email as penghuni_email');
                    $this->db->from('reports r');
                    $this->db->join('penghuni p', 'p.id_penghuni = r.id_penghuni', 'left');
                    $this->db->where('r.id_admin', $id_admin);
                    $this->db->order_by('r.created_at', 'DESC');
                    $this->db->limit(5);
                    $data['user_reports_list'] = $this->db->get()->result();

                    // Get last report date
                    $this->db->select('created_at');
                    $this->db->from('reports');
                    $this->db->where('id_admin', $id_admin);
                    $this->db->order_by('created_at', 'DESC');
                    $this->db->limit(1);
                    $last = $this->db->get()->row();
                    $data['last_user_report'] = $last ? $last->created_at : null;
                }
            }
        }

        // Set admin data
        $data['title'] = 'Dashboard Admin';
        $data['admin'] = $admin;
        $data['warning_count'] = !empty($admin->warning_count) ? $admin->warning_count : 0;
        $data['is_suspended'] = !empty($admin->is_suspended) ? $admin->is_suspended : 0;
        $data['suspended_until'] = !empty($admin->suspended_until) ? $admin->suspended_until : null;
        $data['suspension_reason'] = !empty($admin->suspension_reason) ? $admin->suspension_reason : null;

        // Calculate average rating
        $data['average_rating'] = 0;
        if ($this->db->table_exists('ratings')) {
            // Jika ada tabel ratings terpisah
            $this->db->select_avg('rating');
            $this->db->where('id_admin', $id_admin);
            $rating_result = $this->db->get('ratings')->row();
            $data['average_rating'] = $rating_result->rating ? round($rating_result->rating, 1) : 0;
        } else {
            // Default value jika tidak ada rating system
            $data['average_rating'] = 0;
        }

        $this->load->view('admin/dashboard', $data);
    }

    /**
     * Set active kos
     */
    public function set_kos($id_kos)
    {
        $list_kos = $this->session->userdata('list_kos');
        $valid = false;

        if (!empty($list_kos)) {
            foreach ($list_kos as $kos) {
                if ($kos->id_kos == $id_kos) {
                    $valid = true;
                    break;
                }
            }
        }

        if ($valid) {
            $this->session->set_userdata('id_kos', $id_kos);
            $this->session->set_flashdata('success', 'Kos aktif berhasil diganti.');
        } else {
            $this->session->set_flashdata('error', 'Kos tidak valid untuk admin ini.');
        }

        redirect('admin/dashboard');
    }

    /**
     * Halaman subscription/langganan fitur chat
     */
    public function subscription()
    {
        $admin_id = $this->session->userdata('admin_id');

        // Get admin data
        $admin = $this->db->get_where('admin', ['id' => $admin_id])->row();

        // Get current subscription
        $current_subscription = $this->Payment_model->get_admin_subscription($admin_id);
        $is_chat_active = $this->Payment_model->is_chat_active($admin_id);

        $data = [
            'title' => 'Langganan Fitur Chat',
            'admin' => $admin,
            'current_subscription' => $current_subscription,
            'is_chat_active' => $is_chat_active,
            'price' => 50000,
            'duration' => 30
        ];

        $this->load->view('admin/header', $data);
        $this->load->view('admin/payment/checkout', $data);
        $this->load->view('admin/footer');
    }

    public function chat()
    {
        // Check subscription first
        $admin_id = $this->session->userdata('admin_id');
        $has_subscription = $this->Subscription_model->check_subscription($admin_id);

        if (!$has_subscription) {
            $this->session->set_flashdata('error', 'Anda perlu berlangganan untuk mengakses fitur chat.');
            redirect('admin/subscription');
        }

        // Load chat view
        $data['title'] = 'Chat dengan Penghuni';
        $this->load->view('admin/header', $data);
        $this->load->view('admin/chat/index');
        $this->load->view('admin/footer');
    }

    public function iklan()
    {
        // Method iklan
        $data['title'] = 'Manajemen Iklan';
        $this->load->view('admin/header', $data);
        $this->load->view('admin/iklan');
        $this->load->view('admin/footer');
    }

    public function kos()
    {
        // Method kos
        $data['title'] = 'Manajemen Kos';
        $this->load->view('admin/header', $data);
        $this->load->view('admin/kos');
        $this->load->view('admin/footer');
    }

    public function laporan()
    {
        // Method laporan
        $data['title'] = 'Laporan Penghuni';
        $this->load->view('admin/header', $data);
        $this->load->view('admin/laporan');
        $this->load->view('admin/footer');
    }

    public function pengaturan()
    {
        // Method pengaturan
        $data['title'] = 'Pengaturan';
        $this->load->view('admin/header', $data);
        $this->load->view('admin/pengaturan');
        $this->load->view('admin/footer');
    }

    public function penghuni()
    {
        // Method penghuni
        $data['title'] = 'Data Penghuni';
        $this->load->view('admin/header', $data);
        $this->load->view('admin/penghuni');
        $this->load->view('admin/footer');
    }

    public function register()
    {
        // Method register
        $data['title'] = 'Registrasi Admin';
        $this->load->view('admin/register', $data);
    }

    /**
     * Halaman untuk melihat laporan dari user - READ ONLY
     */
    public function laporan_admin_reports()
    {
        $id_admin = $this->session->userdata('admin_id');
        
        // Load model
        $this->load->model('superadmin/Report_model');
        
        // Get all reports for this admin
        $reports = $this->Report_model->get_by_admin_with_details($id_admin);
        
        // Count reports by status
        $pending_count = $this->Report_model->count_by_admin_status($id_admin, 'pending');
        $process_count = $this->Report_model->count_by_admin_status($id_admin, 'diproses');
        $done_count = $this->Report_model->count_by_admin_status($id_admin, 'selesai');
        $total_count = $this->Report_model->count_by_admin($id_admin);
        
        $data = [
            'title' => 'Laporan dari Penghuni',
            'reports' => $reports,
            'pending_count' => $pending_count,
            'process_count' => $process_count,
            'done_count' => $done_count,
            'total_count' => $total_count,
            'admin' => $this->Admin_model->get($id_admin)
        ];
        
        $this->load->view('admin/laporan_admin_reports', $data);
    }

    /**
     * Tandai laporan sebagai sudah dibaca
     */
    public function mark_report_read()
    {
        // Check if user is logged in
        if (!$this->session->userdata('admin_logged_in')) {
            echo json_encode(['success' => false, 'message' => 'Anda harus login terlebih dahulu.']);
            return;
        }
        
        $id_report = $this->input->post('id_report');
        $id_admin = $this->session->userdata('admin_id');
        
        $this->load->model('superadmin/Report_model');
        
        // Update status menjadi 'selesai' (sudah dibaca)
        $data = [
            'status' => 'selesai',
            'updated_at' => date('Y-m-d H:i:s')
        ];
        
        $this->db->where('id_report', $id_report);
        $this->db->where('id_admin', $id_admin);
        $success = $this->db->update('reports', $data);
        
        echo json_encode([
            'success' => $success,
            'message' => $success ? 'Laporan berhasil ditandai sebagai sudah dibaca.' : 'Gagal memperbarui status laporan.'
        ]);
    }

    /**
     * Get count of unread reports
     */
    public function get_unread_report_count()
    {
        // Check if user is logged in
        if (!$this->session->userdata('admin_logged_in')) {
            echo json_encode(['count' => 0]);
            return;
        }
        
        $id_admin = $this->session->userdata('admin_id');
        
        $this->db->where('id_admin', $id_admin);
        $this->db->where('status', 'pending');
        $count = $this->db->count_all_results('reports');
        
        echo json_encode(['count' => $count]);
    }

    /**
     * Update status laporan - COMMENT/HAPUS KARENA READ ONLY
     */
    /*
    public function update_report_status($id_report)
    {
        // Admin tidak diperbolehkan mengubah laporan dari Super Admin
        $this->session->set_flashdata('error', 'Anda tidak diizinkan mengubah laporan dari Super Admin.');
        redirect('admin/laporan_admin_reports');
    }
    */

    /**
     * Logout
     */
    public function logout()
    {
        $this->session->sess_destroy();
        redirect('admin/login');
    }
}