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

class Superadmin extends CI_Controller
{
    // Tambahkan model di constructor
    public function __construct()
    {
        parent::__construct();
        $this->load->model('superadmin/Superadmin_model');
        $this->load->model('admin/Admin_model');
        $this->load->model('superadmin/Kos_model');
        $this->load->model('superadmin/Report_model'); // Tambah ini
        $this->load->library('session');
        $this->load->helper(['url', 'form']);
    }
    public function report_list()
    {
        $this->check_login();

        $data['reports'] = $this->Report_model->get_all();
        $data['title']   = "Kelola Laporan Admin";
        $data['pending_count'] = $this->Report_model->count_by_status('pending');
        $data['diproses_count'] = $this->Report_model->count_by_status('diproses');

        $this->load->view('superadmin/report_list', $data);
    }

    public function report_detail($id)
    {
        $this->check_login();

        $data['report'] = $this->Report_model->get($id);
        $data['title']  = "Detail Laporan";

        if (!$data['report']) {
            $this->session->set_flashdata('error', 'Laporan tidak ditemukan');
            redirect('superadmin/superadmin/report_list');
        }

        $this->load->view('superadmin/report_detail', $data);
    }

    public function process_report()
    {
        $this->check_login();

        $id_report = $this->input->post('id_report');
        $action = $this->input->post('action');
        $duration = $this->input->post('duration'); // dalam hari
        $notes = $this->input->post('notes');

        // Get report details
        $report = $this->Report_model->get($id_report);

        if (!$report) {
            $this->session->set_flashdata('error', 'Laporan tidak ditemukan');
            redirect('superadmin/superadmin/report_list');
        }

        // Update report status and action
        $report_data = [
            'status' => 'diproses',
            'tindakan' => $action,
            'updated_at' => date('Y-m-d H:i:s')
        ];

        // Handle different actions
        if ($action == 'peringatan') {
            // Increment warning count
            $this->db->set('warning_count', 'warning_count + 1', FALSE);
            $this->db->where('id', $report->id_admin);
            $this->db->update('admin');

            $this->session->set_flashdata('success', 'Peringatan telah diberikan kepada admin');
        } elseif ($action == 'nonaktif_sementara') {
            // Calculate suspension period
            $suspend_until = date('Y-m-d H:i:s', strtotime("+$duration days"));

            $admin_data = [
                'is_suspended' => 1,
                'suspended_until' => $suspend_until,
                'suspension_reason' => $notes,
                'status' => 'nonaktif'
            ];

            // Update admin status
            $this->Admin_model->update($report->id_admin, $admin_data);

            // Update report with suspension details
            $report_data['durasi_nonaktif'] = $duration;
            $report_data['tanggal_nonaktif'] = date('Y-m-d H:i:s');
            $report_data['tanggal_aktif_kembali'] = $suspend_until;

            $this->session->set_flashdata('success', "Admin dinonaktifkan sementara selama $duration hari");
        } elseif ($action == 'nonaktif_permanen') {
            // Permanently deactivate admin
            $admin_data = [
                'status' => 'nonaktif',
                'is_suspended' => 1,
                'suspended_until' => NULL,
                'suspension_reason' => $notes
            ];

            $this->Admin_model->update($report->id_admin, $admin_data);
            $this->session->set_flashdata('success', 'Admin dinonaktifkan secara permanen');
        }

        // Update report
        $this->Report_model->update_report($id_report, $report_data);

        redirect('superadmin/superadmin/report_list');
    }

    public function activate_admin($admin_id)
    {
        $this->check_login();

        $admin_data = [
            'status' => 'aktif',
            'is_suspended' => 0,
            'suspended_until' => NULL,
            'suspension_reason' => NULL
        ];

        $this->Admin_model->update($admin_id, $admin_data);

        $this->session->set_flashdata('success', 'Admin telah diaktifkan kembali');
        redirect('superadmin/superadmin/admin_list');
    }

    // =============== LOGIN PAGE ===============
    public function index()
    {
        if ($this->session->userdata('super_admin_logged_in')) {
            redirect('superadmin/superadmin/dashboard');
        }
        $this->load->view('superadmin/login');
    }

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

        $super_admin = $this->Superadmin_model->get_by_email($email);

        if ($super_admin && password_verify($password, $super_admin->password)) {

            $this->session->set_userdata([
                'super_admin_logged_in' => true,
                'super_admin_id'        => $super_admin->id_super_admin,
                'super_admin_name'      => $super_admin->nama
            ]);

            redirect('superadmin/superadmin/dashboard');
        } else {
            $this->session->set_flashdata('error', 'Email atau password salah');
            redirect('superadmin');
        }
    }

    // =============== DASHBOARD ===============
    public function dashboard()
    {
        $this->check_login();

        $data['admin_count'] = $this->Admin_model->count_all();
        $data['kos_count']   = $this->Kos_model->count_all();
        $data['report_count'] = $this->Report_model->count_all();
        $data['pending_reports'] = $this->Report_model->count_by_status('pending');
        $data['title']       = "Dashboard Super Admin";

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

    // ==================================================
    // =============== CRUD ADMIN =======================
    // ==================================================

    public function admin_list()
    {
        $this->check_login();

        $data['admins'] = $this->Admin_model->get_all();
        $data['title']  = "Kelola Admin";

        $this->load->view('superadmin/admin_list', $data);
    }

    public function admin_form($id = null)
    {
        $this->check_login();

        $data['admin'] = $id ? $this->Admin_model->get($id) : null;
        $data['title'] = $id ? "Edit Admin" : "Tambah Admin";

        $this->load->view('superadmin/admin_form', $data);
    }

    public function save_admin()
    {
        $this->check_login();

        $id = $this->input->post('id');

        $data = [
            'nama'  => $this->input->post('nama'),
            'email' => $this->input->post('email')
        ];

        // Tambah password jika diisi
        if ($this->input->post('password')) {
            $data['password'] = password_hash($this->input->post('password'), PASSWORD_BCRYPT);
        }

        if ($id) {
            $this->Admin_model->update($id, $data);
        } else {
            $this->Admin_model->insert($data);
        }

        redirect('superadmin/superadmin/admin_list');
    }

    public function delete_admin($id)
    {
        $this->check_login();

        $this->Admin_model->delete($id);

        redirect('superadmin/superadmin/admin_list');
    }

    // ==================================================
    // =============== CRUD KOS =========================
    // ==================================================

    public function kos_list()
    {
        $this->check_login();

        $data['koss'] = $this->Kos_model->get_all();
        $data['title'] = "Kelola Kos";

        $this->load->view('superadmin/kos_list', $data);
    }

    public function kos_form($id = null)
    {
        $this->check_login();

        $data['kos']     = $id ? $this->Kos_model->get($id) : null;
        $data['admins']  = $this->Admin_model->get_all(); // admin untuk pilih manajemen kos
        $data['title']   = $id ? "Edit Kos" : "Tambah Kos";

        $this->load->view('superadmin/kos_form', $data);
    }

    public function save_kos()
    {
        $this->check_login();

        $id        = $this->input->post('id_kos');
        $id_admin  = $this->input->post('id_admin');

        $data = [
            'id_admin'      => $id_admin,
            'nama_kos'      => $this->input->post('nama_kos'),
            'alamat'        => $this->input->post('alamat'),
            'jumlah_kamar'  => $this->input->post('jumlah_kamar'),
            'deskripsi'     => $this->input->post('deskripsi'),
            'status'        => $this->input->post('status'),
        ];

        if ($id) {
            $this->Kos_model->update($id, $data);
            $id_kos = $id;
        } else {
            $id_kos = $this->Kos_model->insert($data);
        }

        // Update admin supaya terkoneksi ke kos
        if ($id_admin) {
            $this->Admin_model->update($id_admin, ['id_kos' => $id_kos]);
        }

        redirect('superadmin/superadmin/kos_list');
    }

    public function delete_kos($id)
    {
        $this->check_login();
        $this->Kos_model->delete($id);
        redirect('superadmin/superadmin/kos_list');
    }

    // =============== LOGOUT ===============
    public function logout()
    {
        $this->session->sess_destroy();
        redirect('superadmin');
    }

    // =============== CHECK LOGIN ===============
    private function check_login()
    {
        if (!$this->session->userdata('super_admin_logged_in')) {
            redirect('superadmin');
        }
    }
}
