<?php
/**
 * Agentic Square - High Security Login Verification & Routing Engine
 * Envato CodeCanyon Standard Architecture Execution Rules
 */

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

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

// Extract payload variables safely
$email    = filter_var(trim($_POST['email'] ?? ''), FILTER_VALIDATE_EMAIL);
$password = $_POST['password'] ?? '';

// Check basic input bounds
if (!$email || empty($password)) {
    $_SESSION['login_error'] = "Please provide valid credentials.";
    header('Location: ' . app_url('login.php'));
    exit;
}

try {
    // Look up the user context inside the database
    $query = "SELECT id, full_name, email, password, role FROM users WHERE email = :email LIMIT 1";
    $stmt  = $pdo->prepare($query);
    $stmt->execute(['email' => $email]);
    $user  = $stmt->fetch();

    // Verify user profile existence and password crypt matches
    if ($user && password_verify($password, $user['password'])) {
        
        // CodeCanyon Security Requirement: Regenerate Session ID on status change to prevent session fixation attacks
        session_regenerate_id(true);

        // Bind secure framework global state variables
        $_SESSION['user_id']   = $user['id'];
        $_SESSION['user_name'] = $user['full_name'];
        $_SESSION['user_role'] = $user['role'];

        // Role Matrix Matrix Router (Strict Conditional Matching)
        switch ($user['role']) {
            case 'admin':
                header('Location: ' . app_url('admin/admin-dashboard.php'));
                break;
                
            case 'seller':
                header('Location: ' . app_url('seller/seller-dashboard.php'));
                break;
                
            case 'buyer':
            case 'client':
                header('Location: ' . app_url('client/client-dashboard.php'));
                break;
                
            default:
                // Fallback catch-all case for undefined roles
                header('Location: ' . app_url('index.php'));
                break;
        }
        exit;

    } else {
        // Generic failure message to prevent user enumeration security flaws
        $_SESSION['login_error'] = "Invalid email or password combination.";
        header('Location: ' . app_url('login.php'));
        exit;
    }

} catch (\PDOException $e) {
    // Hide native system tracking variables from end-user templates
    $_SESSION['login_error'] = "Authentication runtime pipeline failure.";
    header('Location: ' . app_url('login.php'));
    exit;
}
