<?php
/**
 * Clase base para manejo de usuarios
 * Turpial Airlines, C.A.
 */

require_once dirname(__DIR__) . '/config/database.php';

class User {
    private $db;
    private $id;
    private $username;
    private $email;
    private $full_name;
    private $role_id;
    private $role_name;
    
    public function __construct() {
        $this->db = new Database();
    }
    
    public function authenticate($username, $password) {
        $sql = "SELECT u.*, r.name as role_name 
                FROM users u 
                JOIN roles r ON u.role_id = r.id 
                WHERE u.username = ? AND u.is_active = 1";
        
        $user = $this->db->fetch($sql, [$username]);
        
        if ($user && password_verify($password, $user['password'])) {
            $this->id = $user['id'];
            $this->username = $user['username'];
            $this->email = $user['email'];
            $this->full_name = $user['full_name'];
            $this->role_id = $user['role_id'];
            $this->role_name = $user['role_name'];
            
            // Iniciar sesión
            $_SESSION['user_id'] = $this->id;
            $_SESSION['username'] = $this->username;
            $_SESSION['full_name'] = $this->full_name;
            $_SESSION['role_id'] = $this->role_id;
            $_SESSION['role_name'] = $this->role_name;
            
            return true;
        }
        
        return false;
    }
    
    public function isLoggedIn() {
        return isset($_SESSION['user_id']);
    }
    
    public function hasPermission($required_role_id) {
        if (!$this->isLoggedIn()) {
            return false;
        }
        
        return $_SESSION['role_id'] <= $required_role_id;
    }
    
    public function logout() {
        session_destroy();
    }
    
    public function getAllUsers() {
        $sql = "SELECT u.*, r.name as role_name 
                FROM users u 
                JOIN roles r ON u.role_id = r.id 
                ORDER BY u.created_at DESC";
        
        return $this->db->fetchAll($sql);
    }
    
    public function getRoles() {
        $sql = "SELECT * FROM roles ORDER BY id";
        return $this->db->fetchAll($sql);
    }
    
    public function create($data) {
        $sql = "INSERT INTO users (username, email, password, full_name, role_id) 
                VALUES (?, ?, ?, ?, ?)";
        
        $password_hash = password_hash($data['password'], PASSWORD_DEFAULT);
        
        $this->db->query($sql, [
            $data['username'],
            $data['email'],
            $password_hash,
            $data['full_name'],
            $data['role_id']
        ]);
        
        return $this->db->lastInsertId();
    }
    
    public function update($id, $data) {
        $fields = [];
        $values = [];
        
        foreach ($data as $key => $value) {
            if ($key !== 'id') {
                if ($key === 'password' && !empty($value)) {
                    $fields[] = "password = ?";
                    $values[] = password_hash($value, PASSWORD_DEFAULT);
                } elseif ($key !== 'password') {
                    $fields[] = "$key = ?";
                    $values[] = $value;
                }
            }
        }
        
        $values[] = $id;
        
        $sql = "UPDATE users SET " . implode(', ', $fields) . " WHERE id = ?";
        
        return $this->db->query($sql, $values);
    }
    
    public function delete($id) {
        $sql = "UPDATE users SET is_active = 0 WHERE id = ?";
        return $this->db->query($sql, [$id]);
    }
    
    public function getById($id) {
        $sql = "SELECT u.*, r.name as role_name 
                FROM users u 
                JOIN roles r ON u.role_id = r.id 
                WHERE u.id = ?";
        
        return $this->db->fetch($sql, [$id]);
    }
    
    // Getters
    public function getId() { return $this->id; }
    public function getUsername() { return $this->username; }
    public function getEmail() { return $this->email; }
    public function getFullName() { return $this->full_name; }
    public function getRoleId() { return $this->role_id; }
    public function getRoleName() { return $this->role_name; }
}

?>