<?php
/**
 * Agentic Square - High Security Injection Controller Engine
 * Envato CodeCanyon Standard Architecture Execution Rules
 */

require_once __DIR__ . '/config/config.php';

// Refuse direct execution configurations outside POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ' . app_url('register.php'));
    exit;
}

// 1. Structural Verification Framework Validation
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    $_SESSION['register_error'] = "Security validation tracking failure. Token match expired.";
    header('Location: ' . app_url('register.php'));
    exit;
}

// 2. Clear Payload Constraints and Sanitize Base Form Fields
$full_name = trim($_POST['full_name'] ?? '');
$email     = filter_var(trim($_POST['email'] ?? ''), FILTER_VALIDATE_EMAIL);
$password  = $_POST['password'] ?? '';
$role      = trim($_POST['role'] ?? '');

// 3. System Boundary Rules Processing
if (empty($full_name) || !$email || empty($password) || empty($role)) {
    $_SESSION['register_error'] = "Processing execution error. Complete fields cleanly.";
    header('Location: ' . app_url('register.php'));
    exit;
}

if (!in_array($role, ['buyer', 'seller'])) {
    $_SESSION['register_error'] = "Invalid authorization parameters targeted.";
    header('Location: ' . app_url('register.php'));
    exit;
}

if (strlen($password) < 8) {
    $_SESSION['register_error'] = "Password must span at least 8 alphanumeric metrics.";
    header('Location: ' . app_url('register.php'));
    exit;
}

try {
    // 4. Evaluate User Collision Constraints
    $check_query = "SELECT id FROM users WHERE email = :email LIMIT 1";
    $check_stmt  = $pdo->prepare($check_query);
    $check_stmt->execute(['email' => $email]);
    
    if ($check_stmt->fetch()) {
        $_SESSION['register_error'] = "An account is already linked to this address.";
        header('Location: ' . app_url('register.php'));
        exit;
    }

    // 5. Generate One-Way Cryptographic Hash Match
    $hashed_password = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);

    // 6. Execute Secure PDO Parameterized Database Insertion
    $insert_query = "INSERT INTO users (full_name, email, password, role, created_at) 
                     VALUES (:full_name, :email, :password, :role, NOW())";
                     
    $insert_stmt = $pdo->prepare($insert_query);
    $execution_state = $insert_stmt->execute([
        'full_name' => htmlspecialchars($full_name, ENT_QUOTES, 'UTF-8'), // Protect layout layers against structural XSS
        'email'     => $email,
        'password'  => $hashed_password,
        'role'      => $role
    ]);

    if ($execution_state) {
        $_SESSION['register_success'] = "Account onboarding complete! You can sign in.";
        header('Location: ' . app_url('register.php'));
        exit;
    }

} catch (\PDOException $e) {
    // Structural Logging Configuration Strategy: Keep execution codes clean of architecture definitions in production profiles
    $_SESSION['register_error'] = "System architecture runtime fault. Execution pipeline terminated.";
    header('Location: ' . app_url('register.php'));
    exit;
}
