<?php
require_once __DIR__ . '/../config/database.php';

class UserManagement {
    private $db;

    public function __construct() {
        $database = new Database();
        $this->db = $database->getConnection();
    }

    /**
     * Get all users
     */
    public function getAllUsers($page = 1, $limit = 20, $search = '') {
        $offset = ($page - 1) * $limit;

        // Get admin email from .env to exclude from results
        $adminEmail = $_ENV['ADMIN_EMAIL'] ?? 'admin@example.com';

        $params = [];
        $whereClause = 'WHERE email != :admin_email';
        $params[':admin_email'] = $adminEmail;

        if (!empty($search)) {
            $whereClause .= " AND (username LIKE :search OR email LIKE :search OR name LIKE :search)";
            $params[':search'] = "%$search%";
        }

        // Get total count
        $countSql = "SELECT COUNT(*) FROM users $whereClause";
        $countStmt = $this->db->prepare($countSql);
        $countStmt->bindParam(':admin_email', $params[':admin_email']);

        if (!empty($search)) {
            $countStmt->bindParam(':search', $params[':search']);
        }

        $countStmt->execute();
        $total = $countStmt->fetchColumn();

        // Get users
        $sql = "SELECT * FROM users $whereClause ORDER BY id DESC LIMIT :limit OFFSET :offset";
        $stmt = $this->db->prepare($sql);
        $stmt->bindParam(':admin_email', $params[':admin_email']);

        if (!empty($search)) {
            $stmt->bindParam(':search', $params[':search']);
        }

        $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();

        $users = $stmt->fetchAll();

        return [
            'users' => $users,
            'total' => $total,
            'pages' => ceil($total / $limit),
            'current_page' => $page
        ];
    }

    /**
     * Get user by ID
     */
    public function getUserById($id) {
        // Get admin email from .env
        $adminEmail = $_ENV['ADMIN_EMAIL'] ?? 'admin@example.com';

        $stmt = $this->db->prepare("SELECT * FROM users WHERE id = :id AND email != :admin_email");
        $stmt->bindParam(':id', $id);
        $stmt->bindParam(':admin_email', $adminEmail);
        $stmt->execute();

        return $stmt->fetch();
    }

    /**
     * Update user
     */
    public function updateUser($id, $data) {
        // Get admin email from .env
        $adminEmail = $_ENV['ADMIN_EMAIL'] ?? 'admin@example.com';

        // First check if this is the .env admin user (by email)
        $stmt = $this->db->prepare("SELECT email FROM users WHERE id = :id");
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        $user = $stmt->fetch();

        // Don't allow updating the .env admin user
        if ($user && $user['email'] === $adminEmail) {
            return false;
        }

        $allowedFields = ['username', 'email', 'name', 'role', 'is_active', 'email_verified'];
        $updates = [];
        $params = [':id' => $id];

        foreach ($data as $key => $value) {
            if (in_array($key, $allowedFields)) {
                $updates[] = "$key = :$key";
                $params[":$key"] = $value;
            }
        }

        if (empty($updates)) {
            return false;
        }

        // Get current timestamp
        $currentTimestamp = date('Y-m-d H:i:s');

        // Add updated_at to updates
        $updates[] = "updated_at = :updated_at";
        $params[":updated_at"] = $currentTimestamp;

        $sql = "UPDATE users SET " . implode(', ', $updates) . " WHERE id = :id";
        $stmt = $this->db->prepare($sql);

        return $stmt->execute($params);
    }

    /**
     * Update user password
     */
    public function updateUserPassword($id, $password) {
        // Get admin email from .env
        $adminEmail = $_ENV['ADMIN_EMAIL'] ?? 'admin@example.com';

        // First check if this is the .env admin user (by email)
        $stmt = $this->db->prepare("SELECT email FROM users WHERE id = :id");
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        $user = $stmt->fetch();

        // Don't allow updating the .env admin user's password
        if ($user && $user['email'] === $adminEmail) {
            return false;
        }

        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

        // Get current timestamp
        $currentTimestamp = date('Y-m-d H:i:s');

        $stmt = $this->db->prepare("UPDATE users SET password = :password, updated_at = :updated_at WHERE id = :id");
        $stmt->bindParam(':password', $hashedPassword);
        $stmt->bindParam(':updated_at', $currentTimestamp);
        $stmt->bindParam(':id', $id);

        return $stmt->execute();
    }

    /**
     * Delete user
     */
    public function deleteUser($id) {
        // Get admin email from .env
        $adminEmail = $_ENV['ADMIN_EMAIL'] ?? 'admin@example.com';

        // Get user details
        $stmt = $this->db->prepare("SELECT role, email FROM users WHERE id = :id");
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        $user = $stmt->fetch();

        // Don't allow deleting admin users or the .env admin user
        if (!$user || $user['role'] === 'admin' || $user['email'] === $adminEmail) {
            return false;
        }

        $stmt = $this->db->prepare("DELETE FROM users WHERE id = :id");
        $stmt->bindParam(':id', $id);

        return $stmt->execute();
    }

    /**
     * Get user statistics
     */
    public function getUserStats() {
        // Get admin email from .env to exclude from results
        $adminEmail = $_ENV['ADMIN_EMAIL'] ?? 'admin@example.com';

        // Total users (excluding .env admin)
        $stmt = $this->db->prepare("SELECT COUNT(*) FROM users WHERE email != :admin_email");
        $stmt->bindParam(':admin_email', $adminEmail);
        $stmt->execute();
        $totalUsers = $stmt->fetchColumn();

        // Total admins (excluding .env admin)
        $stmt = $this->db->prepare("SELECT COUNT(*) FROM users WHERE role = :role AND email != :admin_email");
        $role = 'admin';
        $stmt->bindParam(':role', $role);
        $stmt->bindParam(':admin_email', $adminEmail);
        $stmt->execute();
        $totalAdmins = $stmt->fetchColumn();

        // Total regular users
        $stmt = $this->db->prepare("SELECT COUNT(*) FROM users WHERE role = :role AND email != :admin_email");
        $role = 'user';
        $stmt->bindParam(':role', $role);
        $stmt->bindParam(':admin_email', $adminEmail);
        $stmt->execute();
        $totalRegularUsers = $stmt->fetchColumn();

        // Recent users (excluding .env admin)
        $stmt = $this->db->prepare("SELECT * FROM users WHERE email != :admin_email ORDER BY created_at DESC LIMIT 5");
        $stmt->bindParam(':admin_email', $adminEmail);
        $stmt->execute();
        $recentUsers = $stmt->fetchAll();

        return [
            'total_users' => $totalUsers,
            'total_admins' => $totalAdmins,
            'total_regular_users' => $totalRegularUsers,
            'recent_users' => $recentUsers
        ];
    }
}