<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once 'db.php';
require_once 'session_check.php'; 
checkUserRole(['admin']);

header('Content-Type: application/json');

try {
    $pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// Handle requests
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    fetchUsers();
} elseif ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    if (isset($input['username']) && isset($input['email']) && isset($input['role']) && isset($input['password'])) {
        createUser($input);
    } elseif (isset($_GET['reset-password'])) {
        $userId = intval($_GET['reset-password']);
        resetPassword($userId, $input);
    } elseif (isset($_GET['delete-user'])) {
        $userId = intval($_GET['delete-user']);
        deleteUser($userId);
    } else {
        http_response_code(400);
        echo json_encode(["error" => "Invalid request"]);
    }
} else {
    http_response_code(405);
    echo json_encode(["error" => "Method not allowed"]);
}

function fetchUsers()
{
    global $pdo;
    $stmt = $pdo->prepare("SELECT id, username, email, role, disabled, created_at FROM users");
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($users);
}

function createUser($input)
{
    global $pdo;

    $hashedPassword = password_hash($input['password'], PASSWORD_BCRYPT);

    $stmt = $pdo->prepare("INSERT INTO users (username, email, role, password, disabled, created_at) VALUES (:username, :email, :role, :password, 0, NOW())");

    if ($stmt->execute([
        ':username' => $input['username'],
        ':email' => $input['email'],
        ':role' => $input['role'],
        ':password' => $hashedPassword
    ])) {
        http_response_code(201);
        echo json_encode(["success" => "User created successfully"]);
    } else {
        http_response_code(500);
        echo json_encode(["error" => "Failed to create user"]);
    }
}

function resetPassword($userId, $input)
{
    global $pdo;

    if (!isset($input['password'])) {
        http_response_code(400);
        echo json_encode(["error" => "Password not provided"]);
        return;
    }

    $newPassword = password_hash($input['password'], PASSWORD_BCRYPT);

    $stmt = $pdo->prepare("UPDATE users SET password = :password WHERE id = :id");

    if ($stmt->execute([
        ':password' => $newPassword,
        ':id' => $userId
    ])) {
        echo json_encode(["success" => "Password reset successfully"]);
    } else {
        http_response_code(500);
        echo json_encode(["error" => "Failed to reset password"]);
    }
}

function deleteUser($userId)
{
    global $pdo;

    $stmt = $pdo->prepare("DELETE FROM users WHERE id = :id");

    if ($stmt->execute([':id' => $userId])) {
        echo json_encode(["success" => "User deleted successfully"]);
    } else {
        http_response_code(500);
        echo json_encode(["error" => "Failed to delete user"]);
    }
}
