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

// Stop manual browser attempts to run this engine
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die(json_encode(["status" => "error", "message" => "Direct script access is denied."]));
}

$email    = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
$user_ip  = $_POST['userip'] ?? '';   
$nas_ip   = $_POST['nasip'] ?? '';    

if (empty($email) || empty($password) || empty($user_ip) || empty($nas_ip)) {
    echo json_encode(["status" => "fail", "message" => "Missing authentication telemetry parameters from controller redirection."]);
    exit;
}

// 1. Authenticate against local cPanel email system via standard secure IMAP loopback
$mailbox = "{127.0.0.1:993/imap/ssl/novalidate-cert}";
$imap_conn = @imap_open($mailbox, $email, $password, OP_HALFOPEN, 1);

if (!$imap_conn) {
    echo json_encode(["status" => "fail", "message" => "Invalid campus email or password settings."]);
    exit;
}
@imap_close($imap_conn);

// 2. Transmit the user authorization payload back to the H3C hardware controller's internal API engine
$h3c_auth_url = "http://" . $nas_ip . ":80/portal/auth"; 

$payload = [
    'userip'   => $user_ip,
    'username' => $email,
    'password' => $password
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $h3c_auth_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
curl_setopt($ch, CURLOPT_TIMEOUT, 6);

$result = curl_exec($ch);
curl_close($ch);

// Return full success state back to user browser interface
echo json_encode(["status" => "success", "message" => "Authenticated successfully! Granting network access..."]);
exit;
?>