<?php
/**
 * Classe AdminUser - Gestion des utilisateurs administrateurs - SERVICES-AE
 */

class AdminUser {
    private $pdo;
    private $table = 'admin_users';
    
    public function __construct($pdo) {
        $this->pdo = $pdo;
    }
    
    /**
     * Authentifier un utilisateur admin
     */
    public function authenticate($username, $password) {
        try {
            $stmt = $this->pdo->prepare("SELECT id, username, email, password, avatar, role, status, support_name FROM {$this->table} WHERE (username = ? OR email = ?) AND status = 'active'");
            $stmt->execute([$username, $username]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($user && password_verify($password, $user['password'])) {
                $this->updateLastLogin($user['id']);
                return $user;
            }
            return false;
        } catch (PDOException $e) {
            error_log("AdminUser::authenticate Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Obtenir un utilisateur par ID
     */
    public function getById($id) {
        try {
            $stmt = $this->pdo->prepare("SELECT id, username, email, avatar, role, status, last_login, created_at FROM {$this->table} WHERE id = ?");
            $stmt->execute([$id]);
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("AdminUser::getById Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Obtenir un utilisateur par nom d'utilisateur
     */
    public function getByUsername($username) {
        try {
            $stmt = $this->pdo->prepare("SELECT id, username, email, avatar, role, status, last_login, created_at FROM {$this->table} WHERE username = ?");
            $stmt->execute([$username]);
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("AdminUser::getByUsername Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Obtenir un utilisateur par email
     */
    public function getByEmail($email) {
        try {
            $stmt = $this->pdo->prepare("SELECT id, username, email, avatar, role, status, last_login, created_at FROM {$this->table} WHERE email = ?");
            $stmt->execute([$email]);
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("AdminUser::getByEmail Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Mettre à jour l'avatar d'un utilisateur
     */
    public function updateAvatar($userId, $avatarFilename) {
        try {
            $stmt = $this->pdo->prepare("UPDATE {$this->table} SET avatar = ?, updated_at = NOW() WHERE id = ?");
            return $stmt->execute([$avatarFilename, $userId]);
        } catch (PDOException $e) {
            error_log("AdminUser::updateAvatar Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Supprimer l'avatar d'un utilisateur
     */
    public function removeAvatar($userId) {
        try {
            $stmt = $this->pdo->prepare("UPDATE {$this->table} SET avatar = NULL, updated_at = NOW() WHERE id = ?");
            return $stmt->execute([$userId]);
        } catch (PDOException $e) {
            error_log("AdminUser::removeAvatar Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Changer le mot de passe d'un utilisateur
     */
    public function changePassword($userId, $currentPassword, $newPassword) {
        try {
            // Récupérer le mot de passe actuel
            $stmt = $this->pdo->prepare("SELECT password FROM {$this->table} WHERE id = ?");
            $stmt->execute([$userId]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$user) {
                return ['success' => false, 'message' => 'Utilisateur non trouvé.'];
            }
            
            // Vérifier le mot de passe actuel
            if (!password_verify($currentPassword, $user['password'])) {
                return ['success' => false, 'message' => 'Mot de passe actuel incorrect.'];
            }
            
            // Mettre à jour le mot de passe
            $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
            $stmt = $this->pdo->prepare("UPDATE {$this->table} SET password = ?, updated_at = NOW() WHERE id = ?");
            
            if ($stmt->execute([$hashedPassword, $userId])) {
                return ['success' => true, 'message' => 'Mot de passe changé avec succès.'];
            } else {
                return ['success' => false, 'message' => 'Erreur lors de la mise à jour du mot de passe.'];
            }
            
        } catch (PDOException $e) {
            error_log("AdminUser::changePassword Error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Erreur de base de données.'];
        }
    }
    
    /**
     * Réinitialiser le mot de passe d'un utilisateur (sans vérifier l'ancien)
     */
    public function resetPassword($userId, $newPassword) {
        try {
            // Hasher le nouveau mot de passe
            $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
            
            // Mettre à jour le mot de passe
            $stmt = $this->pdo->prepare("UPDATE {$this->table} SET password = ?, updated_at = NOW() WHERE id = ?");
            
            if ($stmt->execute([$hashedPassword, $userId])) {
                return true;
            } else {
                return false;
            }
            
        } catch (PDOException $e) {
            error_log("AdminUser::resetPassword Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Changer l'email d'un utilisateur
     */
    public function changeEmail($userId, $newEmail) {
        try {
            // Validation de l'email
            if (!filter_var($newEmail, FILTER_VALIDATE_EMAIL)) {
                return ['success' => false, 'message' => 'Format d\'email invalide.'];
            }
            
            // Vérifier si l'email n'est pas déjà utilisé par un autre utilisateur
            $stmt = $this->pdo->prepare("SELECT id FROM {$this->table} WHERE email = ? AND id != ?");
            $stmt->execute([$newEmail, $userId]);
            
            if ($stmt->rowCount() > 0) {
                return ['success' => false, 'message' => 'Cet email est déjà utilisé par un autre utilisateur.'];
            }
            
            // Mettre à jour l'email
            $stmt = $this->pdo->prepare("UPDATE {$this->table} SET email = ?, updated_at = NOW() WHERE id = ?");
            
            if ($stmt->execute([$newEmail, $userId])) {
                return ['success' => true, 'message' => 'Email mis à jour avec succès.'];
            } else {
                return ['success' => false, 'message' => 'Erreur lors de la mise à jour de l\'email.'];
            }
            
        } catch (PDOException $e) {
            error_log("AdminUser::changeEmail Error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Erreur de base de données.'];
        }
    }
    
    /**
     * Mettre à jour la dernière connexion
     */
    private function updateLastLogin($userId) {
        try {
            $stmt = $this->pdo->prepare("UPDATE {$this->table} SET last_login = NOW() WHERE id = ?");
            $stmt->execute([$userId]);
        } catch (PDOException $e) {
            error_log("AdminUser::updateLastLogin Error: " . $e->getMessage());
        }
    }
    
    /**
     * Créer un nouvel utilisateur admin
     */
    public function create($username, $password, $email = null, $role = 'admin') {
        try {
            // Si l'email n'est pas fourni, générer un email par défaut
            if (empty($email)) {
                $email = $username . '@services-ae.com';
            }
            
            // Hasher le mot de passe
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            
            // Insérer le nouvel utilisateur
            $stmt = $this->pdo->prepare("INSERT INTO {$this->table} (username, email, password, role, status, created_at) VALUES (?, ?, ?, ?, 'active', NOW())");
            return $stmt->execute([$username, $email, $hashedPassword, $role]);
            
        } catch (PDOException $e) {
            error_log("AdminUser::create Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Obtenir tous les utilisateurs avec pagination
     */
    public function getAllUsers($search = '', $offset = 0, $limit = 10, $status_filter = '') {
        try {
            $conditions = [];
            $params = [];
            
            if (!empty($search)) {
                $conditions[] = "(username LIKE ? OR email LIKE ?)";
                $searchTerm = '%' . $search . '%';
                $params[] = $searchTerm;
                $params[] = $searchTerm;
            }
            
            if (!empty($status_filter)) {
                $conditions[] = "status = ?";
                $params[] = $status_filter;
            }
            
            $where = !empty($conditions) ? 'WHERE ' . implode(' AND ', $conditions) : '';
            
            $sql = "SELECT id, username, email, avatar, role, status, last_login, created_at 
                    FROM {$this->table} 
                    {$where} 
                    ORDER BY created_at DESC 
                    LIMIT {$limit} OFFSET {$offset}";
            
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute($params);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
            
        } catch (PDOException $e) {
            error_log("AdminUser::getAllUsers Error: " . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Compter le nombre total d'utilisateurs
     */
    public function countUsers($search = '', $status_filter = '') {
        try {
            $conditions = [];
            $params = [];
            
            if (!empty($search)) {
                $conditions[] = "(username LIKE ? OR email LIKE ?)";
                $searchTerm = '%' . $search . '%';
                $params[] = $searchTerm;
                $params[] = $searchTerm;
            }
            
            if (!empty($status_filter)) {
                $conditions[] = "status = ?";
                $params[] = $status_filter;
            }
            
            $where = !empty($conditions) ? 'WHERE ' . implode(' AND ', $conditions) : '';
            
            $sql = "SELECT COUNT(*) FROM {$this->table} {$where}";
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute($params);
            return $stmt->fetchColumn();
            
        } catch (PDOException $e) {
            error_log("AdminUser::countUsers Error: " . $e->getMessage());
            return 0;
        }
    }

    /**
     * Vérifier si la table admin_users existe
     */
    public function tableExists() {
        try {
            $stmt = $this->pdo->prepare("SHOW TABLES LIKE '{$this->table}'");
            $stmt->execute();
            return $stmt->rowCount() > 0;
        } catch (PDOException $e) {
            return false;
        }
    }
    
    /**
     * Activer un utilisateur
     */
    public function activateUser($userId) {
        try {
            $stmt = $this->pdo->prepare("UPDATE {$this->table} SET status = 'active', updated_at = NOW() WHERE id = ?");
            return $stmt->execute([$userId]);
        } catch (PDOException $e) {
            error_log("AdminUser::activateUser Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Désactiver un utilisateur
     */
    public function deactivateUser($userId) {
        try {
            $stmt = $this->pdo->prepare("UPDATE {$this->table} SET status = 'inactive', updated_at = NOW() WHERE id = ?");
            return $stmt->execute([$userId]);
        } catch (PDOException $e) {
            error_log("AdminUser::deactivateUser Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Changer le statut d'un utilisateur (toggle)
     */
    public function toggleUserStatus($userId) {
        try {
            // Obtenir le statut actuel
            $stmt = $this->pdo->prepare("SELECT status FROM {$this->table} WHERE id = ?");
            $stmt->execute([$userId]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$user) {
                return false;
            }
            
            // Inverser le statut
            $newStatus = ($user['status'] === 'active') ? 'inactive' : 'active';
            
            $stmt = $this->pdo->prepare("UPDATE {$this->table} SET status = ?, updated_at = NOW() WHERE id = ?");
            return $stmt->execute([$newStatus, $userId]);
            
        } catch (PDOException $e) {
            error_log("AdminUser::toggleUserStatus Error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * Créer la table admin_users si elle n'existe pas
     */
    public function createTable() {
                $sql = "CREATE TABLE IF NOT EXISTS `{$this->table}` (
                    `id` int(11) NOT NULL AUTO_INCREMENT,
                    `username` varchar(50) NOT NULL UNIQUE,
                    `email` varchar(100) NOT NULL UNIQUE,
                    `password` varchar(255) NOT NULL,
                    `avatar` varchar(255) DEFAULT NULL,
                    `support_name` varchar(100) DEFAULT NULL,
                    `role` varchar(20) NOT NULL DEFAULT 'admin',
                    `status` enum('active','inactive') NOT NULL DEFAULT 'active',
                    `last_login` timestamp NULL DEFAULT NULL,
                    `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
                    `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    PRIMARY KEY (`id`),
                    KEY `username` (`username`),
                    KEY `status` (`status`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
        
        try {
            $this->pdo->exec($sql);
            
            // Insérer l'admin par défaut s'il n'existe pas
            $defaultPassword = password_hash('admin123', PASSWORD_DEFAULT);
            $stmt = $this->pdo->prepare("INSERT IGNORE INTO {$this->table} (username, email, password, role) VALUES (?, ?, ?, ?)");
            $stmt->execute(['admin', 'admin@services-ae.com', $defaultPassword, 'super_admin']);
            
            return true;
        } catch (PDOException $e) {
            error_log("AdminUser::createTable Error: " . $e->getMessage());
            return false;
        }
    }
}
?>