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

class Dashboard extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('user/Dashboard_model');
        $this->load->model('admin/Admin_model');
        $this->load->model('admin/Subscription_model');
        $this->load->library('session');
        $this->load->helper('url');

        // Check login
        if (!$this->session->userdata('user_logged_in')) {
            redirect('user/login');
        }
    }

    public function index()
    {
        $user_id = $this->session->userdata('user_id');

        // Get user data
        $data['user'] = $this->Dashboard_model->get_user_by_id($user_id);

        if (!$data['user']) {
            $this->session->sess_destroy();
            redirect('user/login');
        }

        // Cek status admin - AKTIFKAN KEMBALI SUSPENSION CHECK
        $admin_status = $this->check_admin_status($data['user']->id_kos);
        $data['admin_suspended'] = $admin_status;

        // Get statistics
        $data['stats'] = $this->Dashboard_model->get_user_statistics($user_id);

        // Get recent laporan
        $data['laporan'] = $this->Dashboard_model->get_user_laporan($user_id, 10);

        // Get iklan berdasarkan kos user
        $data['iklan'] = $this->Dashboard_model->get_iklan_by_kos($data['user']->id_kos);

        // Check if admin has active subscription for chat
        if ($admin_status['admin_id']) {
            $data['admin_has_subscription'] = $this->Subscription_model->check_subscription($admin_status['admin_id']);
        } else {
            $data['admin_has_subscription'] = false;
        }

        // Set page title
        $data['title'] = 'Dashboard Penghuni';

        // Load view
        $this->load->view('user/dashboard/index', $data);
    }

    /**
     * Cek status admin berdasarkan kos - DENGAN SUSPENSION CHECK
     */
    private function check_admin_status($id_kos)
    {
        if (empty($id_kos)) {
            return [
                'suspended' => false,
                'type' => 'no_kos',
                'message' => 'Anda belum terdaftar di kos manapun',
                'admin_id' => null
            ];
        }

        // 1. Cari data kos berdasarkan id_kos
        $this->db->where('id_kos', $id_kos);
        $kos = $this->db->get('kos')->row();

        if (!$kos) {
            return [
                'suspended' => false,
                'type' => 'no_kos_data',
                'message' => 'Data kos tidak ditemukan',
                'admin_id' => null
            ];
        }

        // 2. Cari admin berdasarkan id_admin yang ada di tabel kos
        if (isset($kos->id_admin) && !empty($kos->id_admin)) {
            $this->db->where('id', $kos->id_admin);
            $admin = $this->db->get('admin')->row();
        } else {
            $admin = null;
        }

        if (!$admin) {
            return [
                'suspended' => false,
                'type' => 'no_admin',
                'message' => 'Tidak ada admin untuk kos ini',
                'admin_id' => null
            ];
        }

        // 3. CEK STATUS SUSPENDED
        if ($admin->is_suspended == 1) {
            // Cek apakah suspended sementara atau permanen
            if (!empty($admin->suspended_until)) {
                // SUSPENDED SEMENTARA
                $suspended_until = strtotime($admin->suspended_until);
                $now = time();

                if ($suspended_until > $now) {
                    // Masih dalam masa suspend
                    $days_left = ceil(($suspended_until - $now) / (60 * 60 * 24));

                    return [
                        'suspended' => true,
                        'type' => 'temporary',
                        'message' => 'Admin sedang dinonaktifkan sementara',
                        'admin_id' => $admin->id,
                        'admin_name' => $admin->name ?? 'Admin',
                        'admin_email' => $admin->email ?? '',
                        'until' => $admin->suspended_until,
                        'days_left' => $days_left,
                        'reason' => $admin->suspend_reason ?? 'Tidak ada alasan'
                    ];
                } else {
                    // Waktu suspend sudah lewat tapi belum di-aktivasi otomatis
                    // Kembalikan status aktif
                    return [
                        'suspended' => false,
                        'type' => 'active',
                        'message' => 'Admin aktif',
                        'admin_id' => $admin->id,
                        'admin_name' => $admin->name ?? 'Admin',
                        'admin_email' => $admin->email ?? ''
                    ];
                }
            } else {
                // SUSPENDED PERMANEN
                return [
                    'suspended' => true,
                    'type' => 'permanent',
                    'message' => 'Admin dinonaktifkan permanen',
                    'admin_id' => $admin->id,
                    'admin_name' => $admin->name ?? 'Admin',
                    'admin_email' => $admin->email ?? '',
                    'reason' => $admin->suspend_reason ?? 'Tidak ada alasan'
                ];
            }
        }

        // Admin aktif normal
        return [
            'suspended' => false,
            'type' => 'active',
            'message' => 'Admin aktif',
            'admin_id' => $admin->id,
            'admin_name' => $admin->name ?? 'Admin',
            'admin_email' => $admin->email ?? ''
        ];
    }

    public function laporan()
    {
        $user_id = $this->session->userdata('user_id');
        $data['user'] = $this->Dashboard_model->get_user_by_id($user_id);

        if (!$data['user']) {
            $this->session->sess_destroy();
            redirect('user/login');
        }

        // Cek status admin
        $admin_status = $this->check_admin_status($data['user']->id_kos);
        $data['admin_suspended'] = $admin_status;

        // Get all laporan
        $data['laporan'] = $this->Dashboard_model->get_user_laporan($user_id);

        $data['title'] = 'Laporan Saya';
        $this->load->view('user/dashboard/laporan', $data);
    }

    public function tambah()
    {
        $user_id = $this->session->userdata('user_id');
        $data['user'] = $this->Dashboard_model->get_user_by_id($user_id);

        if (!$data['user']) {
            $this->session->sess_destroy();
            redirect('user/login');
        }

        // Cek status admin - BLOCK jika suspended
        $admin_status = $this->check_admin_status($data['user']->id_kos);

        if ($admin_status['suspended']) {
            $this->session->set_flashdata('error', 'Tidak dapat membuat laporan. ' . $admin_status['message']);
            redirect('user/dashboard');
        }

        $data['title'] = 'Buat Laporan Baru';
        $this->load->view('user/dashboard/tambah', $data);
    }

    public function simpan_laporan()
    {
        $user_id = $this->session->userdata('user_id');
        $user = $this->Dashboard_model->get_user_by_id($user_id);

        if (!$user) {
            $this->session->sess_destroy();
            redirect('user/login');
        }

        // CEK STATUS ADMIN - BLOCK jika suspended
        $admin_status = $this->check_admin_status($user->id_kos);

        if ($admin_status['suspended']) {
            $this->session->set_flashdata('error', 'Tidak dapat membuat laporan. Admin sedang dinonaktifkan.');
            redirect('user/dashboard');
        }

        // Validasi form
        $this->load->library('form_validation');
        $this->form_validation->set_rules('judul', 'Judul', 'required|min_length[5]');
        $this->form_validation->set_rules('deskripsi', 'Deskripsi', 'required|min_length[10]');
        $this->form_validation->set_rules('kategori', 'Kategori', 'required');

        if ($this->form_validation->run() == FALSE) {
            $this->session->set_flashdata('error', validation_errors());
            redirect('user/dashboard/tambah');
        }

        // Cari admin berdasarkan kos
        $this->db->where('id_kos', $user->id_kos);
        $kos = $this->db->get('kos')->row();

        $id_admin = null;
        if ($kos && isset($kos->id_admin)) {
            $id_admin = $kos->id_admin;
        }

        // Upload bukti jika ada
        $bukti = '';
        if (!empty($_FILES['bukti']['name'])) {
            $config['upload_path'] = './asset/bukti_laporan/';
            $config['allowed_types'] = 'jpg|jpeg|png|pdf';
            $config['max_size'] = 2048;
            $config['encrypt_name'] = TRUE;

            $this->load->library('upload', $config);

            if ($this->upload->do_upload('bukti')) {
                $upload_data = $this->upload->data();
                $bukti = $upload_data['file_name'];
            }
        }

        // Data laporan
        $laporan_data = [
            'id_penghuni' => $user_id,
            'id_kos' => $user->id_kos,
            'id_admin' => $id_admin,
            'judul' => $this->input->post('judul'),
            'deskripsi' => $this->input->post('deskripsi'),
            'kategori' => $this->input->post('kategori'),
            'prioritas' => $this->input->post('prioritas') ?: 'normal',
            'bukti' => $bukti,
            'status' => 'Diajukan',
            'tanggal_laporan' => date('Y-m-d H:i:s'),
            'created_at' => date('Y-m-d H:i:s')
        ];

        // Simpan ke database
        if ($this->Dashboard_model->insert_laporan($laporan_data)) {
            $this->session->set_flashdata('success', 'Laporan berhasil diajukan!');
            redirect('user/dashboard/laporan');
        } else {
            $this->session->set_flashdata('error', 'Gagal mengajukan laporan. Silakan coba lagi.');
            redirect('user/dashboard/tambah');
        }
    }

    public function detail($id_laporan)
    {
        $user_id = $this->session->userdata('user_id');

        // Get laporan dengan validasi kepemilikan
        $data['laporan'] = $this->Dashboard_model->get_laporan_by_id($id_laporan, $user_id);

        if (!$data['laporan']) {
            $this->session->set_flashdata('error', 'Laporan tidak ditemukan atau Anda tidak memiliki akses.');
            redirect('user/dashboard/laporan');
        }

        $data['title'] = 'Detail Laporan';
        $this->load->view('user/dashboard/detail', $data);
    }

    public function edit($id_laporan)
    {
        $user_id = $this->session->userdata('user_id');
        $data['user'] = $this->Dashboard_model->get_user_by_id($user_id);

        // Cek status admin - BLOCK jika suspended
        $admin_status = $this->check_admin_status($data['user']->id_kos);

        if ($admin_status['suspended']) {
            $this->session->set_flashdata('error', 'Tidak dapat mengedit laporan. Admin sedang dinonaktifkan.');
            redirect('user/dashboard/laporan');
        }

        // Get laporan dengan validasi kepemilikan
        $data['laporan'] = $this->Dashboard_model->get_laporan_by_id($id_laporan, $user_id);

        if (!$data['laporan']) {
            $this->session->set_flashdata('error', 'Laporan tidak ditemukan atau Anda tidak memiliki akses.');
            redirect('user/dashboard/laporan');
        }

        // Hanya bisa edit jika status masih Diajukan
        if ($data['laporan']->status != 'Diajukan') {
            $this->session->set_flashdata('error', 'Laporan tidak dapat diedit karena sudah diproses.');
            redirect('user/dashboard/detail/' . $id_laporan);
        }

        $data['title'] = 'Edit Laporan';
        $this->load->view('user/dashboard/edit', $data);
    }

    public function hapus($id_laporan)
    {
        $user_id = $this->session->userdata('user_id');
        $user = $this->Dashboard_model->get_user_by_id($user_id);

        // Cek status admin - BLOCK jika suspended
        $admin_status = $this->check_admin_status($user->id_kos);

        if ($admin_status['suspended']) {
            $this->session->set_flashdata('error', 'Tidak dapat menghapus laporan. Admin sedang dinonaktifkan.');
            redirect('user/dashboard/laporan');
        }

        // Get laporan dengan validasi kepemilikan
        $laporan = $this->Dashboard_model->get_laporan_by_id($id_laporan, $user_id);

        if (!$laporan) {
            $this->session->set_flashdata('error', 'Laporan tidak ditemukan atau Anda tidak memiliki akses.');
            redirect('user/dashboard/laporan');
        }

        // Hanya bisa hapus jika status masih Diajukan
        if ($laporan->status != 'Diajukan') {
            $this->session->set_flashdata('error', 'Laporan tidak dapat dihapus karena sudah diproses.');
            redirect('user/dashboard/detail/' . $id_laporan);
        }

        // Hapus file bukti jika ada
        if (!empty($laporan->bukti)) {
            $file_path = './asset/bukti_laporan/' . $laporan->bukti;
            if (file_exists($file_path)) {
                unlink($file_path);
            }
        }

        // Hapus dari database
        if ($this->Dashboard_model->delete_laporan($id_laporan)) {
            $this->session->set_flashdata('success', 'Laporan berhasil dihapus.');
        } else {
            $this->session->set_flashdata('error', 'Gagal menghapus laporan.');
        }

        redirect('user/dashboard/laporan');
    }

    public function profile()
    {
        $user_id = $this->session->userdata('user_id');
        $data['user'] = $this->Dashboard_model->get_user_by_id($user_id);

        if (!$data['user']) {
            $this->session->sess_destroy();
            redirect('user/login');
        }

        $data['title'] = 'Profil Saya';
        $this->load->view('user/dashboard/profile', $data);
    }

    public function update_profile()
    {
        $user_id = $this->session->userdata('user_id');

        $this->load->library('form_validation');
        $this->form_validation->set_rules('nama_penghuni', 'Nama Lengkap', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
        $this->form_validation->set_rules('no_hp', 'No. HP', 'required');

        if ($this->form_validation->run() == FALSE) {
            $this->session->set_flashdata('error', validation_errors());
            redirect('user/dashboard/profile');
        }

        $data = [
            'nama_penghuni' => $this->input->post('nama_penghuni'),
            'email' => $this->input->post('email'),
            'no_hp' => $this->input->post('no_hp'),
            'updated_at' => date('Y-m-d H:i:s')
        ];

        // Update password jika diisi
        $password = $this->input->post('password');
        if (!empty($password)) {
            $data['password'] = password_hash($password, PASSWORD_DEFAULT);
        }

        if ($this->Dashboard_model->update_user($user_id, $data)) {
            $this->session->set_flashdata('success', 'Profil berhasil diperbarui.');
        } else {
            $this->session->set_flashdata('error', 'Gagal memperbarui profil.');
        }

        redirect('user/dashboard/profile');
    }
}
