<?php
// ==========================================
// 1. CONFIGURATION SETTINGS
// ==========================================
define('CPANEL_USER', 'upikac');        // Your master cPanel username
define('CPANEL_TOKEN', 'OZ6AV1XRL9QZY7ENAOLAQVJO8D4OVZ6N');     // Generated in cPanel -> Manage API Tokens
define('CPANEL_HOST', 'localhost:2083');                  // Usually localhost if script is on the same server
define('H3C_SHARE_KEY', 'MySecretNetworkKey@2026!');   // Must match 'share-key cipher' on H3C Controller

// Allowed institute email domains (lowercase)
$allowed_domains = [
    'upik.ac.ug',
    'guest.upik.ac.ug',
    'guest.upik.ac.ug'
];

// ==========================================
// 2. INPUT SANITIZATION & VALIDATION
// ==========================================
$email = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);
$password = $_POST['password'] ?? '';

// Sanitize tracking strings passed by H3C Controller
$user_ip = filter_var($_POST['user_ip'] ?? '', FILTER_VALIDATE_IP);
$user_mac = preg_replace('/[^a-fA-F0-9:.-]/', '', $_POST['user_mac'] ?? '');

if (!$email || empty($password)) {
    die("Access Denied: Missing or invalid credentials.");
}

if (!$user_ip) {
    die("Network Error: Could not determine your local network IP address.");
}

// ==========================================
// 3. INSTITUTE EMAIL DOMAIN ENFORCEMENT
// ==========================================
list($username, $domain) = explode('@', $email);
$domain = strtolower($domain);

if (!in_array($domain, $allowed_domains)) {
    error_log("Unauthorized Wi-Fi registration attempt blocked for: " . $email);
    die("Access Denied: You must use your official institute email address.");
}

// ==========================================
// 4. CPANEL BACKEND EMAIL AUTHENTICATION
// ==========================================
$query_url = "https://" . CPANEL_HOST . ":2083/execute/Email/validate_current_password?email=" . urlencode($email) . "&password=" . urlencode($password);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $query_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Turn to true if using valid public SSL for cPanel port
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: cpanel " . CPANEL_USER . ":" . CPANEL_TOKEN]);

$api_response = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);

if ($curl_error) {
    error_log("cPanel API Connection Failure: " . $curl_error);
    die("System Error: Unable to verify credentials at this time. Please contact IT Support.");
}

$response_data = json_decode($api_response, true);

// ==========================================
// 5. SECURE H3C PAYLOAD SIGNING & HANDSHAKE
// ==========================================
if (isset($response_data['status']) && $response_data['status'] === 1) {
    
    // To implement best practices and match H3C's portal authentication protocols:
    // Generate a secure verification signature combining the network parameters and your shared secret key.
    // This stops rogue users from inspecting your code and crafting fake authorization requests.
    $timestamp = time();
    $signature_string = $user_ip . $user_mac . $timestamp . H3C_SHARE_KEY;
    $auth_hash = md5($signature_string);

    // Output a hidden HTML form that instantly submits itself to the local H3C secure loopback handler
    echo "<!DOCTYPE html>
    <html>
    <head>
        <title>Authenticating...</title>
    </head>
    <body>
        <p>Verifying network configuration... Please wait.</p>
        <form id='h3cAuthForm' method='POST' action='https://1.1.1'>
            <input type='hidden' name='userip' value='" . htmlspecialchars($user_ip) . "'>
            <input type='hidden' name='usermac' value='" . htmlspecialchars($user_mac) . "'>
            <input type='hidden' name='timestamp' value='" . $timestamp . "'>
            <input type='hidden' name='authenticator' value='" . $auth_hash . "'>
            <input type='hidden' name='status' value='success'>
        </form>
        <script type='text/javascript'>
            document.getElementById('h3cAuthForm').submit();
        </script>
    </body>
    </html>";
    exit;

} else {
    // Graceful error termination if password check fails
    die("Access Denied: Incorrect password for account " . htmlspecialchars($email));
}
?>