<?php
if(!class_exists('DBConnection')){
    require_once(__DIR__.'/../config.php');
    require_once(__DIR__.'/DBConnection.php');
}

class SystemSettings extends DBConnection{

    public $system_info = array();

    public function __construct(){
        parent::__construct();
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
    }

    /* ==============================
       INFORMACIÓN DEL SISTEMA
       ============================== */

    function load_system_info(){
        $qry = $this->conn->query("SELECT * FROM settings LIMIT 1");
        if($qry && $qry->num_rows > 0){
            $row = $qry->fetch_assoc();
            foreach($row as $k => $v){
                $_SESSION['system_info'][$k] = $v;
            }
        }else{
            // valores por defecto
            $_SESSION['system_info']['site_name'] = 'Sistema de Proyectos';
        }
    }

    function update_system_info(){
        return $this->load_system_info();
    }

    function info($field=''){
        return isset($_SESSION['system_info'][$field]) ? $_SESSION['system_info'][$field] : '';
    }

    /* ==============================
       USUARIOS / SESIÓN
       ============================== */

    function set_userdata($field='',$value=''){
        if($field !== ''){
            $_SESSION['userdata'][$field]= $value;
        }
    }

    function userdata($field=''){
        return isset($_SESSION['userdata'][$field]) ? $_SESSION['userdata'][$field] : null;
    }

    function sess_des(){
        unset($_SESSION['userdata']);
        unset($_SESSION['permisos']);
        return true;
    }

    function is_logged_in(){
        return isset($_SESSION['userdata']) && !empty($_SESSION['userdata']);
    }

    /* ==============================
       FLASH DATA
       ============================== */

    function set_flashdata($flash='',$value=''){
        if($flash !== ''){
            $_SESSION['flashdata'][$flash]= $value;
            return true;
        }
        return false;
    }

    function chk_flashdata($flash=''){
        return isset($_SESSION['flashdata'][$flash]);
    }

    function flashdata($flash=''){
        if(isset($_SESSION['flashdata'][$flash])){
            $tmp = $_SESSION['flashdata'][$flash];
            unset($_SESSION['flashdata'][$flash]);
            return $tmp;
        }
        return '';
    }

    /* ==============================
       🔐 PERMISOS DEL SISTEMA
       ============================== */

    function has_permission($modulo, $accion){
        if (!isset($_SESSION['permisos'])) {
            return false;
        }

        // ADMIN → acceso total
        if (isset($_SESSION['permisos']['*']) && $_SESSION['permisos']['*'] === true) {
            return true;
        }

        return isset($_SESSION['permisos'][$modulo]) &&
               isset($_SESSION['permisos'][$modulo][$accion]) &&
               $_SESSION['permisos'][$modulo][$accion] == 1;
    }

    function require_permission($modulo, $accion){
        if (!$this->has_permission($modulo, $accion)) {
            header("Location:/404.html");
            exit;
        }
    }
            /* ==============================
           🧾 AUDITORÍA DEL SISTEMA
           ============================== */
    
        function audit($modulo, $accion, $descripcion = ''){
    
            if (!isset($_SESSION['userdata'])) {
                return false;
            }
    
            $user_id    = $_SESSION['userdata']['id'] ?? null;
            $email      = $_SESSION['userdata']['email'] ?? null;
            $role       = $_SESSION['userdata']['role'] ?? null;
            $ip         = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';
    
            $stmt = $this->conn->prepare("
                INSERT INTO audit_log
                (user_id, user_email, role, modulo, accion, descripcion, ip)
                VALUES (?,?,?,?,?,?,?)
            ");
    
            if(!$stmt){
                return false;
            }
    
            $stmt->bind_param(
                "issssss",
                $user_id,
                $email,
                $role,
                $modulo,
                $accion,
                $descripcion,
                $ip
            );
    
            return $stmt->execute();
        }

}

/* ==============================
   INICIALIZACIÓN DEL SISTEMA
   ============================== */

$_settings = new SystemSettings();
$_settings->load_system_info();
?>
