<?php

class User {
    public static function findByUsername($username) {
        $db = Database::getInstance();
        return $db->fetchOne(
            "SELECT * FROM users WHERE username = ? AND is_active = 1",
            [$username]
        );
    }

    public static function findById($id) {
        $db = Database::getInstance();
        return $db->fetchOne(
            "SELECT * FROM users WHERE id = ?",
            [$id]
        );
    }

    public static function all() {
        $db = Database::getInstance();
        return $db->fetchAll(
            "SELECT id, username, email, first_name, last_name, role, is_active, last_login, created_at 
             FROM users ORDER BY id"
        );
    }

    public static function create($data) {
        $db = Database::getInstance();
        $db->execute(
            "INSERT INTO users (username, email, password, first_name, last_name, role) 
             VALUES (?, ?, ?, ?, ?, ?)",
            [
                $data['username'],
                $data['email'],
                password_hash($data['password'], PASSWORD_DEFAULT),
                $data['first_name'],
                $data['last_name'],
                $data['role']
            ]
        );
        return $db->lastInsertId();
    }

    public static function update($id, $data) {
        $db = Database::getInstance();
        $sql = "UPDATE users SET username = ?, email = ?, first_name = ?, last_name = ?, role = ?";
        $params = [
            $data['username'],
            $data['email'],
            $data['first_name'],
            $data['last_name'],
            $data['role']
        ];

        if (!empty($data['password'])) {
            $sql .= ", password = ?";
            $params[] = password_hash($data['password'], PASSWORD_DEFAULT);
        }

        $sql .= " WHERE id = ?";
        $params[] = $id;

        // Database::execute() puede devolver el número de filas afectadas o un booleano.
        // Si devuelve 0 (ninguna fila afectada) PHP lo interpreta como false.
        // Queremos que sea true si la consulta se ejecuta sin errores.
        $stmt = $db->execute($sql, $params);
        return $stmt !== false; // Devuelve true si la ejecución fue exitosa, false si hubo un error.
    }

    public static function delete($id) {
        $db = Database::getInstance();
        return $db->execute(
            "UPDATE users SET is_active = 0 WHERE id = ?",
            [$id]
        );
    }

    public static function updateProfile($id, $data) {
        $db = Database::getInstance();
        $stmt = $db->execute(
            "UPDATE users SET email = ?, first_name = ?, last_name = ? WHERE id = ?",
            [
                $data['email'],
                $data['first_name'],
                $data['last_name'],
                $id
            ]
        );
        return $stmt !== false; // Devuelve true si la ejecución fue exitosa, false si hubo un error.
    }

    public static function changePassword($id, $newPassword) {
        $db = Database::getInstance();
        $stmt = $db->execute(
            "UPDATE users SET password = ? WHERE id = ?",
            [
                password_hash($newPassword, PASSWORD_DEFAULT),
                $id
            ]
        );
        return $stmt !== false; // Devuelve true si la ejecución fue exitosa, false si hubo un error.
    }

    public static function verifyPassword($id, $password) {
        $db = Database::getInstance();
        $user = $db->fetchOne(
            "SELECT password FROM users WHERE id = ?",
            [$id]
        );
        return $user && password_verify($password, $user['password']);
    }
}
