<?php
/**
 * check.php (persistent sessions) — مُعدّل حسب طلبك:
 * - الجلسة تبقى صالحة حتى بعد غلق/فتح المتصفح طالما بيانات المستخدم في هذا الملف لم تتغير.
 * - عند تغيير اليوزر/الباسورد في هذا الملف → يتم الخروج تلقائيًا ويُطلب تسجيل الدخول.
 * - يحافظ على الأمن: كوكيز HttpOnly + SameSite=Lax + اتباع HTTPS تلقائيًا.
 * - يمنع الكاش.
 */

$https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');

// إعدادات الكوكي الخاصة بالجلسة (عمر طويل 180 يوم)
$cookie_lifetime_days = 180;
$cookie_lifetime = 60 * 60 * 24 * $cookie_lifetime_days;

session_set_cookie_params([
    'lifetime' => $cookie_lifetime,
    'path'     => '/',
    'secure'   => $https,
    'httponly' => true,
    'samesite' => 'Lax',
]);
ini_set('session.use_strict_mode', '1');
ini_set('session.cookie_httponly', '1');
ini_set('session.cookie_samesite', 'Lax');

session_start();

// لا-كاش
header('Content-Type: text/html; charset=UTF-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

// قائمة المستخدمين الأصلية (نُسخت كما هي من ملفك)
$users = [
"ahmedmakky"  => "66350045",
    "mohamedmakky" => "67004700",
    "mhmoodmakky" => "66284220",
    "yasermakky" => "97552180",	
    "aliyaser"  => "65578748",
    "ezzat93"   => "9121993",
    "ahmedabdo" => "94772637",
    "eljazaf"  => "66515813",
    "keko"     => "55170401",
    "ameer"    => "95557973",
    "eslam"    => "96672452",
    "karim"    => "50677749",
    "usama"    => "94717020",
    "admin25"   => "52030015",
    "admin35"  => "350200012",
    "admin45"   => "45001960",
    "admin55"   => "55075800",
    "admin65"  => "650781240",
    "admin75"   => "75023679",
    "admin85"   => "854653965",	
    "admin95"   => "95441365",
];

// ============== دوال مساعدة ==============
function current_user_signature($user, $pass) {
    return hash('sha256', $user . ':' . $pass);
}

function set_auth_cookies($user, $sig, $lifetime, $https) {
    setcookie('AUTH_U', $user, [
        'expires'  => time() + $lifetime,
        'path'     => '/',
        'secure'   => $https,
        'httponly' => true,
        'samesite' => 'Lax',
    ]);
    setcookie('AUTH_S', $sig, [
        'expires'  => time() + $lifetime,
        'path'     => '/',
        'secure'   => $https,
        'httponly' => true,
        'samesite' => 'Lax',
    ]);
}

function clear_auth_cookies($https) {
    foreach (['AUTH_U','AUTH_S'] as $c) {
        setcookie($c, '', [
            'expires'  => time() - 3600,
            'path'     => '/',
            'secure'   => $https,
            'httponly' => true,
            'samesite' => 'Lax',
        ]);
    }
}

function force_logout_and_login($msg='') {
    global $https;
    if (session_status() === PHP_SESSION_ACTIVE) {
        $_SESSION = [];
        if (ini_get('session.use_cookies')) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'] ?? '', $params['secure'], $params['httponly']);
        }
        session_destroy();
    }
    clear_auth_cookies($https);
    show_login_form($msg);
    exit;
}

function show_login_form($error = '') {
    echo '<!doctype html><html lang="ar" dir="rtl"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">';
    echo '<title>تسجيل الدخول</title><style>
        body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Tahoma,Arial;background:#0b1220;color:#fff;margin:0;display:flex;align-items:center;justify-content:center;height:100vh}
        .card{background:#141b2d;border:1px solid #1f2a44;border-radius:16px;padding:24px;max-width:360px;width:100%;box-shadow:0 10px 30px rgba(0,0,0,.35)}
        h2{margin:0 0 16px 0;font-size:20px}
        input{width:100%;padding:12px 14px;border-radius:10px;border:1px solid #24314f;background:#101726;color:#fff;margin:6px 0 12px 0}
        input[type=submit]{cursor:pointer;border-color:#2b5cff}
        .err{color:#ff6b6b;margin:0 0 8px 0}
    </style></head><body><div class="card">';
    echo '<h2>تسجيل الدخول</h2>';
    if ($error) echo '<div class="err">'.htmlspecialchars($error, ENT_QUOTES, 'UTF-8').'</div>';
    echo '<form method="post" autocomplete="off">
            <input type="text" name="username" placeholder="اسم المستخدم" required>
            <input type="password" name="password" placeholder="كلمة المرور" required>
            <input type="submit" value="دخول">
          </form></div></body></html>';
}
// ============ نهاية الدوال ============

// (1) إحياء جلسة تلقائيًا من الكوكيز إن لم توجد جلسة
if (!isset($_SESSION['user'], $_SESSION['sig']) && isset($_COOKIE['AUTH_U'], $_COOKIE['AUTH_S'])) {
    $cu = (string)$_COOKIE['AUTH_U'];
    $cs = (string)$_COOKIE['AUTH_S'];
    if (isset($users[$cu])) {
        $expected = current_user_signature($cu, $users[$cu]);
        if (hash_equals($cs, $expected)) {
            $_SESSION['user'] = $cu;
            $_SESSION['sig']  = $expected;
            session_regenerate_id(true);
            set_auth_cookies($cu, $expected, $cookie_lifetime, $https);
        } else {
            clear_auth_cookies($https);
        }
    } else {
        clear_auth_cookies($https);
    }
}

// (2) تسجيل الدخول اليدوي
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['username'], $_POST['password']) && !isset($_POST['__proxy_passthrough'])) {
    $u = trim((string)$_POST['username']);
    $p = (string)$_POST['password'];

    if (isset($users[$u]) && hash_equals($users[$u], $p)) {
        $sig = current_user_signature($u, $users[$u]);
        $_SESSION['user'] = $u;
        $_SESSION['sig']  = $sig;
        session_regenerate_id(true);
        set_auth_cookies($u, $sig, $cookie_lifetime, $https);
    } else {
        force_logout_and_login('❌ اسم المستخدم أو كلمة المرور غير صحيحة');
    }
}

// (3) التحقق الدائم من صلاحية الجلسة
if (!isset($_SESSION['user'], $_SESSION['sig'])) {
    show_login_form();
    exit;
}
$u = $_SESSION['user'];
if (!isset($users[$u])) {
    force_logout_and_login('تم حذف المستخدم أو تغييره.');
}
$current_sig = current_user_signature($u, $users[$u]);
if (!hash_equals($_SESSION['sig'], $current_sig)) {
    force_logout_and_login('تم تغيير اسم المستخدم أو كلمة المرور. يرجى تسجيل الدخول مرة أخرى.');
}

// (4) زر خروج
if (isset($_GET['logout'])) {
    force_logout_and_login('خروج يدوي.');
}

// (5) تمرير الطلب للرابط البعيد (Proxy) بعد التحقق
$remoteUrl = "https://spidertvapp.com/mohammed5060-elqanas/check.php";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $remoteUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// تمرير POST للوحة مع علامة تمييز
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postFields = $_POST;
    $postFields['__proxy_passthrough'] = '1';
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));
}

$response = curl_exec($ch);
if ($response === false) {
    echo "Proxy Error: " . curl_error($ch);
    exit;
}
curl_close($ch);

// إخراج رد اللوحة + أدوات بسيطة
echo $response;
echo '<div style="margin:10px;direction:rtl;text-align:right">
        <button onclick="history.back()">رجوع</button>
        <a href="?logout=1" style="margin-right:10px">تسجيل الخروج</a>
      </div>';
?>
