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

class Profile extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('user/Profile_model');
        $this->load->library('session');
        $this->load->library('form_validation');
        $this->load->helper('text');
        if (!$this->session->userdata('user_logged_in')) {
            redirect('user/login');
        }
    }

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

        $data['user'] = $this->Profile_model->get_user_by_id($user_id);

        // CEK STATUS ADMIN - MENGIRIM DATA KE VIEW
        $admin_status = $this->check_admin_status($data['user']->id_kos);
        $data['admin_suspended'] = $admin_status;

        $data['title'] = 'Profil Saya';

        $this->load->view('user/dashboard/profile', $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
                    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 update()
    {
        $user_id = $this->session->userdata('user_id');

        // CEK STATUS ADMIN SEBELUM UPDATE
        $user = $this->Profile_model->get_user_by_id($user_id);
        $admin_status = $this->check_admin_status($user->id_kos);

        // Jika admin suspended, batalkan update
        if ($admin_status['suspended']) {
            $this->session->set_flashdata('error', 'Tidak dapat memperbarui profil saat admin dinonaktifkan.');
            redirect('user/profile');
        }

        $this->form_validation->set_rules('nama_penghuni', 'Nama Lengkap', 'required|trim|min_length[3]');
        $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|callback_check_email_exists');
        $this->form_validation->set_rules('no_hp', 'Nomor HP', 'required|trim|numeric|min_length[10]|max_length[15]');
        $this->form_validation->set_rules('alamat', 'Alamat', 'required|trim');
        $this->form_validation->set_rules('password_lama', 'Password Lama', 'callback_check_old_password');
        $this->form_validation->set_rules('password_baru', 'Password Baru', 'min_length[6]');
        $this->form_validation->set_rules('konfirmasi_password', 'Konfirmasi Password', 'matches[password_baru]');

        if ($this->form_validation->run() == FALSE) {
            // Validation failed
            $data['user'] = $this->Profile_model->get_user_by_id($user_id);

            // CEK STATUS ADMIN
            $admin_status = $this->check_admin_status($data['user']->id_kos);
            $data['admin_suspended'] = $admin_status;

            $data['title'] = 'Profil Saya';
            $this->load->view('user/dashboard/profile', $data);
        } else {
            // Prepare data to update
            $data = array(
                'nama_penghuni' => $this->input->post('nama_penghuni'),
                'email' => $this->input->post('email'),
                'no_hp' => $this->input->post('no_hp'),
                'alamat' => $this->input->post('alamat')
                // HAPUS 'updated_at' karena kolom tidak ada di tabel
                // 'updated_at' => date('Y-m-d H:i:s')
            );

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

            $result = $this->Profile_model->update_user($user_id, $data);

            if ($result) {
                // Update session data
                $this->session->set_userdata('user_name', $data['nama_penghuni']);
                $this->session->set_flashdata('success', 'Profil berhasil diperbarui!');
            } else {
                // Debug jika gagal
                if (ENVIRONMENT !== 'production') {
                    echo "Query Error: " . $this->db->last_query();
                    echo "<br>Error: " . $this->db->error()['message'];
                    die();
                }
                $this->session->set_flashdata('error', 'Gagal memperbarui profil!');
            }

            redirect('user/profile');
        }
    }

    // Custom validation: Check if email already exists (exclude current user)
    public function check_email_exists($email)
    {
        $user_id = $this->session->userdata('user_id');
        $exists = $this->Profile_model->check_email_exists($email, $user_id);

        if ($exists) {
            $this->form_validation->set_message('check_email_exists', 'Email sudah digunakan oleh pengguna lain');
            return FALSE;
        }
        return TRUE;
    }

    // Custom validation: Check old password if user wants to change password
    public function check_old_password($password_lama)
    {
        // Only validate if user is trying to change password
        if (!empty($this->input->post('password_baru'))) {
            $user_id = $this->session->userdata('user_id');
            $user = $this->Profile_model->get_user_by_id($user_id);

            if (!password_verify($password_lama, $user->password)) {
                $this->form_validation->set_message('check_old_password', 'Password lama tidak sesuai');
                return FALSE;
            }
        }
        return TRUE;
    }

    // Method untuk mengajukan permintaan pindah kamar
    public function ajukan_pindah_kamar()
    {
        $user_id = $this->session->userdata('user_id');

        // CEK STATUS ADMIN
        $user = $this->Profile_model->get_user_by_id($user_id);
        $admin_status = $this->check_admin_status($user->id_kos);

        // Jika admin suspended, batalkan pengajuan
        if ($admin_status['suspended']) {
            $this->session->set_flashdata('error', 'Tidak dapat mengajukan permintaan pindah kamar saat admin dinonaktifkan.');
            redirect('user/profile');
        }

        $this->form_validation->set_rules('alasan', 'Alasan Pindah Kamar', 'required|trim');

        if ($this->form_validation->run() == FALSE) {
            $this->session->set_flashdata('error', strip_tags(validation_errors()));
            redirect('user/profile');
        } else {
            $data = array(
                'id_penghuni' => $user_id,
                'kamar_sekarang' => $this->input->post('kamar_sekarang'),
                'alasan' => $this->input->post('alasan'),
                'status' => 'Menunggu',
                'tanggal_pengajuan' => date('Y-m-d H:i:s')
            );

            $result = $this->Profile_model->insert_permintaan_pindah($data);

            if ($result) {
                $this->session->set_flashdata('success', 'Permintaan pindah kamar berhasil diajukan!');
            } else {
                $this->session->set_flashdata('error', 'Gagal mengajukan permintaan!');
            }

            redirect('user/profile');
        }
    }

    // Method untuk upload foto profil
    public function upload_foto()
    {
        $user_id = $this->session->userdata('user_id');

        // CEK STATUS ADMIN
        $user = $this->Profile_model->get_user_by_id($user_id);
        $admin_status = $this->check_admin_status($user->id_kos);

        // Jika admin suspended, batalkan upload
        if ($admin_status['suspended']) {
            $this->session->set_flashdata('error', 'Tidak dapat mengupload foto profil saat admin dinonaktifkan.');
            redirect('user/profile');
        }

        $config['upload_path'] = './uploads/foto_profil/';
        $config['allowed_types'] = 'jpg|jpeg|png|gif';
        $config['max_size'] = 2048; // 2MB
        $config['file_name'] = 'user_' . $user_id . '_' . time();
        $config['overwrite'] = true;

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

        if (!$this->upload->do_upload('foto_profil')) {
            $error = $this->upload->display_errors();
            $this->session->set_flashdata('error', $error);
        } else {
            $upload_data = $this->upload->data();

            // Hapus foto lama jika ada
            if (!empty($user->foto_profil) && file_exists('./uploads/foto_profil/' . $user->foto_profil)) {
                unlink('./uploads/foto_profil/' . $user->foto_profil);
            }

            // Update database
            $data = array(
                'foto_profil' => $upload_data['file_name']
            );

            $result = $this->Profile_model->update_user($user_id, $data);

            if ($result) {
                $this->session->set_userdata('user_foto', $upload_data['file_name']);
                $this->session->set_flashdata('success', 'Foto profil berhasil diupload!');
            } else {
                $this->session->set_flashdata('error', 'Gagal menyimpan data foto!');
            }
        }

        redirect('user/profile');
    }

    // Method untuk menghapus foto profil
    public function hapus_foto()
    {
        $user_id = $this->session->userdata('user_id');

        // CEK STATUS ADMIN
        $user = $this->Profile_model->get_user_by_id($user_id);
        $admin_status = $this->check_admin_status($user->id_kos);

        // Jika admin suspended, batalkan hapus
        if ($admin_status['suspended']) {
            $this->session->set_flashdata('error', 'Tidak dapat menghapus foto profil saat admin dinonaktifkan.');
            redirect('user/profile');
        }

        // Hapus file foto jika ada
        if (!empty($user->foto_profil) && file_exists('./uploads/foto_profil/' . $user->foto_profil)) {
            unlink('./uploads/foto_profil/' . $user->foto_profil);
        }

        // Update database
        $data = array(
            'foto_profil' => NULL
        );

        $result = $this->Profile_model->update_user($user_id, $data);

        if ($result) {
            $this->session->unset_userdata('user_foto');
            $this->session->set_flashdata('success', 'Foto profil berhasil dihapus!');
        } else {
            $this->session->set_flashdata('error', 'Gagal menghapus foto profil!');
        }

        redirect('user/profile');
    }
}
