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

/**
 * MY_Controller — Base controller
 * Dibaca dari session yang disimpan Auth::login()
 */
class MY_Controller extends CI_Controller {

    protected $auth_user = NULL;
    protected $is_admin  = FALSE;

    public function __construct() {
        parent::__construct();
        $this->load->library('session');
        $this->load->helper('url');

        $user_id = $this->session->userdata('user_id');
        if ($user_id) {
            // Buat object dari session agar aman dan tidak perlu DB query tiap request
            $this->auth_user = (object)[
                'id'       => (int)$this->session->userdata('user_id'),
                'name'     => $this->session->userdata('user_name'),
                'username' => $this->session->userdata('username'),
                'role'     => $this->session->userdata('role'),
            ];
            $this->is_admin = ($this->auth_user->role === 'admin');
        }
    }

    // ── Wajib login ─────────────────────────────────────────
    protected function require_login() {
        if (!$this->auth_user) {
            $this->session->set_flashdata('error', 'Silakan login terlebih dahulu.');
            redirect('auth/login');
            exit;
        }
    }

    // ── Wajib admin ─────────────────────────────────────────
    protected function require_admin() {
        $this->require_login();
        if (!$this->is_admin) {
            $this->session->set_flashdata('error', 'Akses ditolak. Hanya Admin.');
            redirect('receipt');
            exit;
        }
    }

    // ── Cek akses ke resource (admin boleh semua) ────────────
    protected function can_access($resource_user_id) {
        if ($this->is_admin) return TRUE;
        return ((int)$resource_user_id === (int)$this->auth_user->id);
    }

    // ── Render view dengan data auth otomatis ────────────────
    protected function render($view, $data = []) {
        $data['auth_user'] = $this->auth_user;
        $data['is_admin']  = $this->is_admin;
        $this->load->view('layouts/main', $data + ['content' => $view]);
    }
}
