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

class Laporan_admin extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('user/Report_user_model');
        $this->load->model('user/Penghuni_model');
        $this->load->library('session');
        $this->load->helper(['url', 'form']);

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

    // Tampilkan semua laporan admin yang dibuat user
    public function index()
    {
        $user_id = $this->session->userdata('user_id');

        $data['user'] = $this->Penghuni_model->get_by_id($user_id);
        $data['reports'] = $this->Report_user_model->get_by_penghuni($user_id);
        $data['title'] = "Laporan Admin Saya";

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

    // Form untuk membuat laporan admin baru - FIXED VERSION
    public function tambah()
    {
        $user_id = $this->session->userdata('user_id');
        $user = $this->Penghuni_model->get_by_id($user_id);

        // FIXED: Get admin berdasarkan kos user
        $data['admins'] = $this->get_admin_by_kos($user->id_kos);

        $data['user'] = $user;
        $data['title'] = "Laporkan Admin";

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

    /**
     * Helper method to get admin by kos id - FIXED VERSION
     */
    private function get_admin_by_kos($id_kos)
    {
        if (empty($id_kos)) {
            return [];
        }

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

        if (!$kos) {
            return [];
        }

        // 2. Cek apakah ada id_admin di tabel kos
        if (!isset($kos->id_admin) || empty($kos->id_admin)) {
            return [];
        }

        // 3. Cari admin berdasarkan id_admin (TANPA FILTER STATUS)
        $this->db->where('id', $kos->id_admin);
        $admin = $this->db->get('admin')->row();

        if (!$admin) {
            return [];
        }

        // Return sebagai array (karena fungsi lain mengharapkan array)
        return [$admin];
    }

    // Simpan laporan admin baru
    public function simpan()
    {
        $user_id = $this->session->userdata('user_id');

        // 1. Validasi: Cek apakah user punya kos
        $user = $this->Penghuni_model->get_by_id($user_id);
        if (empty($user->id_kos)) {
            $this->session->set_flashdata('error', 'Anda belum terdaftar di kos manapun.');
            redirect('user/laporan_admin');
        }

        // 2. Cek admin kos user
        $this->db->where('id_kos', $user->id_kos);
        $kos = $this->db->get('kos')->row();

        if (!$kos || empty($kos->id_admin)) {
            $this->session->set_flashdata('error', 'Kos Anda tidak memiliki admin pengelola.');
            redirect('user/laporan_admin');
        }

        // 3. Validasi: user hanya boleh melaporkan admin kosnya sendiri
        $id_admin_input = $this->input->post('id_admin');
        if ($id_admin_input != $kos->id_admin) {
            $this->session->set_flashdata(
                'error',
                'Anda hanya dapat melaporkan admin pengelola kos Anda sendiri.'
            );
            redirect('user/laporan_admin/tambah');
        }

        // 4. Validasi form lainnya
        $this->load->library('form_validation');
        $this->form_validation->set_rules('judul', 'Judul', 'required|min_length[5]|max_length[255]');
        $this->form_validation->set_rules('deskripsi', 'Deskripsi', 'required|min_length[10]');

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

        $data = [
            'id_penghuni' => $user_id,
            'id_admin' => $id_admin_input,
            'judul' => $this->input->post('judul'),
            'deskripsi' => $this->input->post('deskripsi'),
            'status' => 'pending',
            'tindakan' => 'none',
            'created_at' => date('Y-m-d H:i:s')
        ];

        // Handle file upload jika ada
        if (!empty($_FILES['bukti']['name'])) {
            // Pastikan folder uploads ada
            $upload_path = './uploads/reports/';
            if (!is_dir($upload_path)) {
                mkdir($upload_path, 0777, true);
            }

            $config['upload_path'] = $upload_path;
            $config['allowed_types'] = 'jpg|jpeg|png|pdf|doc|docx';
            $config['max_size'] = 2048;
            $config['encrypt_name'] = TRUE;

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

            if ($this->upload->do_upload('bukti')) {
                $upload_data = $this->upload->data();
                $data['bukti'] = $upload_data['file_name'];
            } else {
                $this->session->set_flashdata('error', 'Gagal upload file: ' . $this->upload->display_errors());
                redirect('user/laporan_admin/tambah');
            }
        }

        $inserted = $this->Report_user_model->create($data);

        if ($inserted) {
            $this->session->set_flashdata('success', 'Laporan admin berhasil dikirim!');
        } else {
            $this->session->set_flashdata('error', 'Gagal mengirim laporan admin');
        }

        redirect('user/laporan_admin');
    }

    // Detail laporan admin
    public function detail($id)
    {
        $user_id = $this->session->userdata('user_id');

        $data['report'] = $this->Report_user_model->get_by_id($id, $user_id);

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

        // Tambahkan nama admin ke data
        if ($data['report']->id_admin) {
            $this->db->where('id', $data['report']->id_admin);
            $admin = $this->db->get('admin')->row();
            $data['report']->admin_name = $admin ? $admin->nama : 'Admin tidak ditemukan';
            $data['report']->admin_email = $admin ? $admin->email : '';
        } else {
            $data['report']->admin_name = 'Tidak ada admin';
            $data['report']->admin_email = '';
        }

        $data['user'] = $this->Penghuni_model->get_by_id($user_id);
        $data['title'] = "Detail Laporan Admin";

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

    // Hapus laporan (hanya yang pending) - HARD DELETE VERSION
    public function hapus($id)
    {
        $user_id = $this->session->userdata('user_id');

        // 1. Get report first to check if it exists and can be deleted
        $report = $this->Report_user_model->get_by_id($id, $user_id);

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

        // 2. Check if report can be deleted (only pending status)
        if ($report->status != 'pending') {
            $this->session->set_flashdata('error', 'Laporan tidak dapat dihapus karena sudah diproses');
            redirect('user/laporan_admin');
        }

        // 3. Delete the file if exists
        if (!empty($report->bukti)) {
            $file_path = './uploads/reports/' . $report->bukti;
            if (file_exists($file_path)) {
                unlink($file_path);
            }
        }

        // 4. HARD DELETE from database - BENAR-BENAR HAPUS DATA
        $this->db->where('id_report', $id);
        $this->db->where('id_penghuni', $user_id);
        $deleted = $this->db->delete('admin_reports');

        if ($deleted) {
            $this->session->set_flashdata('success', 'Laporan berhasil dihapus secara permanen');
        } else {
            $this->session->set_flashdata('error', 'Gagal menghapus laporan');
        }

        redirect('user/laporan_admin');
    }

    /**
     * RESET ALL - untuk testing/development
     * JANGAN gunakan di production!
     */
    public function reset_all()
    {
        // Hanya untuk development
        if (ENVIRONMENT == 'production') {
            show_error('Fitur ini tidak tersedia di production');
        }

        $user_id = $this->session->userdata('user_id');

        // 1. Hapus semua laporan user ini
        $this->db->where('id_penghuni', $user_id);
        $this->db->delete('admin_reports');

        // 2. Reset warning count untuk admin kos user
        $user = $this->Penghuni_model->get_by_id($user_id);
        if ($user && $user->id_kos) {
            $this->db->where('id_kos', $user->id_kos);
            $kos = $this->db->get('kos')->row();

            if ($kos && $kos->id_admin) {
                // Reset admin data
                $this->db->where('id', $kos->id_admin);
                $this->db->update('admin', [
                    'warning_count' => 0,
                    'is_suspended' => 0,
                    'suspended_until' => NULL,
                    'suspension_reason' => NULL
                ]);

                // Hapus suspensions
                $this->db->where('id_admin', $kos->id_admin);
                $this->db->delete('admin_suspensions');

                // Hapus suspend logs
                $this->db->where('admin_id', $kos->id_admin);
                $this->db->delete('admin_suspend_logs');
            }
        }

        $this->session->set_flashdata('success', 'Semua data laporan dan peringatan telah direset');
        redirect('user/laporan_admin');
    }
}
