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

class User_controller extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper(['url','form']);
        $this->load->library(['form_validation','session']);
        // proteksi halaman admin
    if(!$this->session->userdata('logged_in')) {
        $this->session->set_flashdata('error','Silakan login terlebih dahulu!');
        redirect('auth');
    }
    }

    // Menampilkan semua admin
    public function index() {
        $data['users'] = $this->db->get('admin')->result();
        $this->load->view('Admin/Master_user', $data);
    }

    // Form tambah admin
    public function add_admin() {
        $this->load->view('Admin/Add_admin'); // view form tambah admin
    }

    // Proses simpan admin baru
public function save_admin() {
    // VALIDASI FORM
    $this->form_validation->set_rules('nama_lengkap','Nama Lengkap','required');
    $this->form_validation->set_rules('job','Job','required');
    $this->form_validation->set_rules('dob','Date of Birth','required');
    $this->form_validation->set_rules('username','Username','required');
    $this->form_validation->set_rules('email','Email','required|valid_email');
    $this->form_validation->set_rules('password','Password','required|min_length[6]');
    $this->form_validation->set_rules('role','Role','required|in_list[admin,user]');

 if ($this->form_validation->run() == FALSE) {
    $this->load->view('Admin/Add_admin'); // langsung load view, jangan redirect
    return;
}


    $data = [
        'nama_lengkap' => $this->input->post('nama_lengkap'),
        'job'          => $this->input->post('job'),
        'dob'          => $this->input->post('dob'),
        'username'     => $this->input->post('username'),
        'email'        => $this->input->post('email'),
        'password'     => password_hash($this->input->post('password'), PASSWORD_DEFAULT),
        'role'         => $this->input->post('role'),
        'created_at'   => date('Y-m-d H:i:s')
    ];

    // DEBUG: tampilkan data POST jika perlu
    // var_dump($data); exit;

    // UPLOAD FOTO
    if (!empty($_FILES['foto']['name'])) {
        $config['upload_path']   = './asset/img/admin/';
        $config['allowed_types'] = 'jpg|jpeg|png|gif';
        $config['max_size']      = 2048;
        $config['file_name']     = 'admin_'.time();

        // pastikan folder ada
        if(!is_dir($config['upload_path'])) mkdir($config['upload_path'], 0777, true);

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

        if ($this->upload->do_upload('foto')) {
            $upload_data = $this->upload->data();
            $data['foto'] = $upload_data['file_name'];
        } else {
            $this->session->set_flashdata('error', 'Upload Foto Gagal: '.$this->upload->display_errors());
            redirect('user_controller/add_admin');
            return;
        }
    }

    // INSERT DENGAN DEBUG ERROR
    if (!$this->db->insert('admin', $data)) {
        $error = $this->db->error();
        echo '<pre>';
        echo "Gagal insert admin:\n";
        print_r($error);
        echo '</pre>';
        exit;
    } else {
        $this->session->set_flashdata('success', 'Admin berhasil ditambahkan!');
        redirect('user_controller');
    }
}




    // Lihat profil admin
    public function profil($id) {
        $data['admin'] = $this->db->get_where('admin', ['id' => $id])->row();

        if (!$data['admin']) {
            show_error("Data admin dengan ID $id tidak ditemukan!", 404);
        }

        $this->load->view('Admin/profil_admin', $data);
    }

    public function delete($id) {
        $this->db->delete('admin', ['id' => $id]);
        $this->session->set_flashdata('success', 'Admin berhasil dihapus');
        redirect('user_controller');
    }

    public function edit_profil($id)
    {
        $data['admin'] = $this->db->get_where('admin', ['id' => $id])->row();
        if (!$data['admin']) {
            show_error("Data admin dengan ID $id tidak ditemukan!");
        }
        $this->load->view('Admin/edit_profil', $data);
    }

    public function update_profil($id)
    {
        // 1. Ambil data admin yang akan di-update untuk referensi foto lama
        $admin = $this->db->get_where('admin', ['id' => $id])->row();

        if (!$admin) {
            $this->session->set_flashdata('error', 'Admin tidak ditemukan.');
            redirect('user_controller');
            return;
        }

        // 2. Terapkan Form Validation (Opsional, tapi disarankan)
        $this->form_validation->set_rules('nama_lengkap','Nama Lengkap','required');
        $this->form_validation->set_rules('job','Job','required');
        $this->form_validation->set_rules('username','Username','required');
        // Tambahkan validasi password jika diisi
        if ($this->input->post('password')) {
            $this->form_validation->set_rules('password','Password','min_length[6]');
        }
        
        if ($this->form_validation->run() == FALSE) {
            // Jika validasi gagal, kembali ke halaman edit
            $data['admin'] = $admin; // Kirim kembali data admin ke view
            $this->load->view('Admin/edit_profil', $data);
            return;
        }


        // 3. Persiapkan data UPDATE
        $data = [
            'nama_lengkap' => $this->input->post('nama_lengkap'),
            'job'          => $this->input->post('job'),
            'dob'          => $this->input->post('dob'),
            'username'     => $this->input->post('username'),
            'email'        => $this->input->post('email'),
            'role'         => $this->input->post('role')
        ];

        // 4. Proses Update Password
        if ($this->input->post('password')) {
            $data['password'] = password_hash($this->input->post('password'), PASSWORD_BCRYPT);
        }

        // 5. Proses Upload Foto
        if (!empty($_FILES['foto']['name'])) {
            $config['upload_path']   = './asset/img/admin/';
            $config['allowed_types'] = 'jpg|jpeg|png|gif';
            $config['max_size']      = 2048;
            $config['file_name']     = 'admin_'.$id.'_'.time(); // Nama unik per admin

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

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

                // Hapus foto lama jika ada
                if(!empty($admin->foto) && file_exists('./asset/img/admin/'.$admin->foto)){
                    unlink('./asset/img/admin/'.$admin->foto);
                }
            } else {
                // Tampilkan pesan error upload yang spesifik
                $error_msg = strip_tags($this->upload->display_errors());
                $this->session->set_flashdata('error', 'Gagal Update Foto: '.$error_msg);
                redirect('User_controller/edit_profil/'.$id);
                return;
            }
        }

        // 6. Jalankan Proses Update Database
        $this->db->where('id', $id);
        $this->db->update('admin', $data);

        // Cek apakah update berhasil atau tidak (optional, tapi baik)
        if ($this->db->affected_rows() > 0 || !empty($_FILES['foto']['name']) || !empty($this->input->post('password'))) {
            $this->session->set_flashdata('success', 'Profil admin berhasil diperbarui ✅');
        } else {
            $this->session->set_flashdata('info', 'Tidak ada perubahan yang dilakukan.');
        }

        redirect('User_controller/profil/'.$id);
    }

    public function edit_master_user($id) {
        $this->load->model('User_model');

        $data['admin'] = $this->User_model->get_by_id($id);
        if (!$data['admin']) {
            $this->session->set_flashdata('error', 'User tidak ditemukan.');
            redirect('user_controller');
        }

        $this->load->view('Admin/edit_profil', $data);
    }
    
} 
