<?php
session_start();
require_once '../config.php';
require_once '../app/classes/AdminAuth.php';

$adminAuth = new AdminAuth($conn);

// Check admin authentication
if (!$adminAuth->isAuthenticated()) {
    header("Location: admin_login.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitize and validate input
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $default_password = trim($_POST['default_password']);
    $balance = floatval($_POST['balance']);
    $role = trim($_POST['role']);

    // Ensure required fields are not empty
    if ($username === '' || $email === '' || $default_password === '' || $role === '') {
        header("Location: ../index.php?error=missing_fields");
        exit();
    }

    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        header("Location: ../index.php?error=invalid_email");
        exit();
    }

    // Validate role - only 'agent' is allowed
    if ($role !== 'agent') {
        header("Location: ../index.php?error=invalid_role");
        exit();
    }

    // Check if username already exists
    $check_username_stmt = $conn->prepare("SELECT id FROM agents WHERE username = ?");
    $check_username_stmt->bind_param("s", $username);
    $check_username_stmt->execute();
    $username_result = $check_username_stmt->get_result();
    
    if ($username_result->num_rows > 0) {
        $check_username_stmt->close();
        header("Location: ../index.php?error=username_exists&username=" . urlencode($username));
        exit();
    }
    $check_username_stmt->close();

    // Check if email already exists
    $check_email_stmt = $conn->prepare("SELECT id FROM agents WHERE email = ?");
    $check_email_stmt->bind_param("s", $email);
    $check_email_stmt->execute();
    $email_result = $check_email_stmt->get_result();
    
    if ($email_result->num_rows > 0) {
        $check_email_stmt->close();
        header("Location: ../index.php?error=email_exists&email=" . urlencode($email));
        exit();
    }
    $check_email_stmt->close();

    // Hash the default password
    $password_hash = password_hash($default_password, PASSWORD_BCRYPT);

    // Prepare insert statement to prevent SQL injection
    $stmt = $conn->prepare("INSERT INTO agents (username, email, password_hash, balance, role, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
    $stmt->bind_param("sssds", $username, $email, $password_hash, $balance, $role);

    if ($stmt->execute()) {
        header("Location: ../index.php?added=1&agent=" . urlencode($username));
        exit();
    } else {
        header("Location: ../index.php?error=db");
        exit();
    }

    $stmt->close();
}
?>
