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

class Profil extends CI_Controller {

    public function __construct() {
        parent::__construct();
        if(!$this->session->userdata('logged_in')) redirect('auth/login');
        $this->load->model('Profil_model');
        $this->load->library('form_validation');
        $this->load->library('upload');
    }

    public function index() {
        $user_id = $this->session->userdata('user_id');
        $data['user']  = $this->Profil_model->get_user($user_id);
        $data['warga'] = $this->Profil_model->get_warga_by_user($user_id);

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('profil/index', $data);
        $this->load->view('templates/footer');
    }

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

        $this->form_validation->set_rules('nama_lengkap', 'Nama Lengkap', 'required|trim');
        $this->form_validation->set_rules('username', 'Username', 'required|trim|alpha_numeric');
        $this->form_validation->set_rules('email',        'Email',        'trim|valid_email');
        $this->form_validation->set_rules('no_hp',        'No HP',        'trim');

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

        $username_baru = $this->input->post('username', TRUE);
        $this->load->model('User_model');
        if($this->User_model->is_username_exists($username_baru, $user_id)) {
            $this->session->set_flashdata('error', 'Username sudah terdaftar atau digunakan oleh orang lain.');
            redirect('profil');
        }

        $data_user = [
            'nama_lengkap' => $this->input->post('nama_lengkap', TRUE),
            'username'     => $username_baru,
            'email'        => $this->input->post('email', TRUE),
            'no_hp'        => $this->input->post('no_hp', TRUE),
            'updated_at'   => date('Y-m-d H:i:s'),
        ];
        $this->Profil_model->update_user($user_id, $data_user);

        $warga = $this->Profil_model->get_warga_by_user($user_id);
        if($warga) {
            $this->Profil_model->update_warga($warga->id, [
                'nama_lengkap'  => $this->input->post('nama_lengkap', TRUE),
                'tempat_lahir'  => $this->input->post('tempat_lahir', TRUE),
                'tanggal_lahir' => $this->input->post('tanggal_lahir', TRUE),
                'pekerjaan'     => $this->input->post('pekerjaan', TRUE),
                'agama'         => $this->input->post('agama', TRUE),
            ]);
        }

        $this->session->set_userdata('nama', $this->input->post('nama_lengkap', TRUE));
        $this->session->set_flashdata('success', 'Profil berhasil diperbarui.');
        redirect('profil');
    }

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

        if(empty($_FILES['foto']['name'])) {
            $this->session->set_flashdata('error', 'Pilih foto terlebih dahulu.');
            redirect('profil');
        }

        // Buat folder jika belum ada
        $upload_path = FCPATH . 'uploads/foto_profil/';
        if(!is_dir($upload_path)) mkdir($upload_path, 0755, TRUE);

        $config = [
            'upload_path'   => $upload_path,
            'allowed_types' => 'jpg|jpeg|png|webp',
            'max_size'      => 2048, // 2MB
            'encrypt_name'  => TRUE,
        ];
        $this->upload->initialize($config);

        if(!$this->upload->do_upload('foto')) {
            $this->session->set_flashdata('error', $this->upload->display_errors('', ''));
            redirect('profil');
        }

        $file_name = $this->upload->data('file_name');

        // Hapus foto lama jika ada
        $user = $this->Profil_model->get_user($user_id);
        if(!empty($user->foto) && file_exists($upload_path . $user->foto)) {
            unlink($upload_path . $user->foto);
        }

        $this->Profil_model->update_user($user_id, [
            'foto'       => $file_name,
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        // Update session foto
        $this->session->set_userdata('foto', $file_name);

        $this->session->set_flashdata('success', 'Foto profil berhasil diperbarui.');
        redirect('profil');
    }

    public function hapus_foto() {
        $user_id = $this->session->userdata('user_id');
        $user    = $this->Profil_model->get_user($user_id);

        $upload_path = FCPATH . 'uploads/foto_profil/';
        if(!empty($user->foto) && file_exists($upload_path . $user->foto)) {
            unlink($upload_path . $user->foto);
        }

        $this->Profil_model->update_user($user_id, [
            'foto'       => NULL,
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
        $this->session->unset_userdata('foto');

        $this->session->set_flashdata('success', 'Foto profil berhasil dihapus.');
        redirect('profil');
    }

    public function ganti_password() {
        $user_id = $this->session->userdata('user_id');
        $user    = $this->Profil_model->get_user($user_id);

        $this->form_validation->set_rules('password_lama', 'Password Lama', 'required');
        $this->form_validation->set_rules('password_baru', 'Password Baru', 'required|min_length[6]');
        $this->form_validation->set_rules('konfirmasi',    'Konfirmasi',    'required|matches[password_baru]');

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

        if(!password_verify($this->input->post('password_lama'), $user->password)) {
            $this->session->set_flashdata('error', 'Password lama tidak sesuai.');
            redirect('profil');
        }

        $this->Profil_model->update_user($user_id, [
            'password'   => password_hash($this->input->post('password_baru'), PASSWORD_BCRYPT),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        $this->session->set_flashdata('success', 'Password berhasil diubah.');
        redirect('profil');
    }

    public function check_username() {
        header('Content-Type: application/json');

        if (!$this->input->is_ajax_request()) {
            echo json_encode(['status' => 'error', 'msg' => 'No direct script access allowed']);
            return;
        }

        $username = $this->input->post('username', TRUE);
        $user_id = $this->session->userdata('user_id');

        if (!preg_match('/^[a-zA-Z0-9]+$/', $username)) {
            echo json_encode(['status' => 'invalid', 'msg' => 'Hanya huruf dan angka, tanpa spasi']);
            return;
        }

        $this->load->model('User_model');
        if ($this->User_model->is_username_exists($username, $user_id)) {
            echo json_encode(['status' => 'taken', 'msg' => 'Username tidak tersedia']);
        } else {
            echo json_encode(['status' => 'available', 'msg' => 'Username tersedia']);
        }
    }
}