<?php
namespace Models;
/* ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
ini_set('log_errors', '1');
ini_set('error_log', __DIR__.'/../logs/error.log');
 */
require_once __DIR__ . '/../models/Database.php';
use PDO;

class User {
    private static $pdo;

// Initialiser la connexion à la base de données
    public static function init() {
        if (self::$pdo == null) {
            self::$pdo = Database::getInstance()->getConnection();
            self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            self::$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 
        }
    }
    public function findAll() {
        $stmt =self::$pdo->prepare("SELECT * FROM users ORDER BY created_at DESC");
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function findById($id) {
        self::init(); // Assure la connexion à la DB
        $stmt =self::$pdo->prepare("SELECT * FROM users WHERE id = :id");
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function findByUsername(string $username): ?array
{
    self::init(); // Assure la connexion à la DB
    
    try {
        // Journalisation de débogage
        error_log("Recherche de l'utilisateur: " . $username);
        
        $stmt = self::$pdo->prepare("SELECT * FROM users WHERE username = :username LIMIT 1");
        $stmt->bindValue(':username', $username, PDO::PARAM_STR);
        
        if (!$stmt->execute()) {
            error_log("Erreur d'exécution de la requête");
            return null;
        }
        
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            error_log("Aucun utilisateur trouvé pour: " . $username);
            return null;
        }
        
        return $user;
        
    } catch (\PDOException $e) {
        error_log("Erreur PDO dans findByUsername: " . $e->getMessage());
        return null;
    }
}


    public function create($data) {
        self::init(); // Assure la connexion à la DB
        $stmt =self::$pdo->prepare("
            INSERT INTO users (username, email, password, user_roles) 
            VALUES (:username, :email, :password, :user_roles)
        ");
        
        $passwordHash = password_hash($data['password'], PASSWORD_BCRYPT);
        
        $stmt->bindParam(':username', $data['username'], PDO::PARAM_STR);
        $stmt->bindParam(':email', $data['email'], PDO::PARAM_STR);
        $stmt->bindParam(':password', $passwordHash, PDO::PARAM_STR);
        $stmt->bindParam(':user_roles', $data['user_roles'], PDO::PARAM_STR);
        
        return $stmt->execute();
    }

    public function update($id, $data) {
        self::init(); // Assure la connexion à la DB
        $query = "UPDATE users SET username = :username, email = :email, user_roles = :user_roles";
        $params = [
            ':id' => $id,
            ':username' => $data['username'],
            ':email' => $data['email'],
            ':user_roles' => $data['user_roles']
        ];

        if (!empty($data['password'])) {
            $query .= ", password = :password";
            $params[':password'] = password_hash($data['password'], PASSWORD_BCRYPT);
        }

        $query .= " WHERE id = :id";
        
        $stmt =self::$pdo->prepare($query);
        return $stmt->execute($params);
    }

    public function delete($id) {
        self::init(); // Assure la connexion à la DB
        $stmt =self::$pdo->prepare("DELETE FROM users WHERE id = :id");
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        return $stmt->execute();
    }

    public function countAll() {
        self::init(); // Assure la connexion à la DB
        $stmt =self::$pdo->prepare("SELECT COUNT(*) FROM users");
        $stmt->execute();
        return $stmt->fetchColumn();
    }
}
?>