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

class Pengaturan extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('admin/Pengaturan_model'); // <- pakai path lengkap dan huruf besar
        $this->load->library(['session', 'form_validation']);
        $this->load->helper(['url', 'form']);
    }

    public function index()
    {
        if (!$this->session->userdata('admin_id')) {
            redirect('admin/login');
        }

        $data['admin'] = $this->Pengaturan_model->get_admin_by_id($this->session->userdata('admin_id'));
        $this->load->view('admin/pengaturan', $data);
    }

    public function update()
    {
        if (!$this->session->userdata('admin_id')) {
            redirect('admin/login');
        }

        $id = $this->session->userdata('admin_id');
        $admin = $this->Pengaturan_model->get_admin_by_id($id);

        $nama = $this->input->post('nama');
        $email = $this->input->post('email');
        $password_lama = $this->input->post('password_lama');
        $password_baru = $this->input->post('password_baru');

        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');

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

        $update_data = [
            'nama' => $nama,
            'email' => $email
        ];

        if (!empty($password_lama) && !empty($password_baru)) {
            if (password_verify($password_lama, $admin->password)) {
                $update_data['password'] = password_hash($password_baru, PASSWORD_DEFAULT);
            } else {
                $this->session->set_flashdata('error', 'Password lama tidak sesuai.');
                redirect('admin/pengaturan');
            }
        }

        if ($this->Pengaturan_model->update_admin($id, $update_data)) {
            $this->session->set_flashdata('success', 'Profil berhasil diperbarui.');
        } else {
            $this->session->set_flashdata('error', 'Gagal memperbarui profil.');
        }

        redirect('admin/pengaturan');
    }
}
