<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (!defined('VALID_ACCESS')) { include(__DIR__ . '/include/config.php'); }

// Already logged in — redirect
if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
    try {
        $stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :id");
        $stmt->bindParam(':id', $_SESSION['user_id']); $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        header('Location: ' . ($user && $user['is_admin'] == 1 ? 'admin/dashboard.php' : 'user/dashboard.php'));
    } catch (PDOException $e) { header('Location: user/dashboard.php'); }
    exit();
}

// POST handler
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email    = trim($_POST['LoginForm']['email']);
    $password = $_POST['LoginForm']['password'];
    $remember = isset($_POST['LoginForm']['remember']);

    $captcha_answer = isset($_POST['captcha_answer']) ? intval($_POST['captcha_answer']) : -1;
    $captcha_expected = isset($_SESSION['captcha_result']) ? intval($_SESSION['captcha_result']) : null;
    unset($_SESSION['captcha_result']);
    if ($captcha_expected === null || $captcha_answer !== $captcha_expected) {
        $_SESSION['login_error'] = "Incorrect captcha answer. Please try again.";
        header('Location: signin.php'); exit();
    }

    if (empty($email) || empty($password)) { $_SESSION['login_error'] = "Email and password are required"; header('Location: signin.php'); exit(); }

    try {
        $stmt = $pdo->prepare("SELECT id, email, password, is_admin, email_verified, status FROM users WHERE email = :email");
        $stmt->bindParam(':email', $email); $stmt->execute();

        if ($stmt->rowCount() == 1) {
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            if (password_verify($password, $user['password'])) {
                if (isset($user['status']) && $user['status'] == 0) { $_SESSION['login_error'] = "Your account has been blocked. Contact administrator at " . WEB_EMAIL; header('Location: ' . $site_data['web_url'] . '/signin'); exit(); }
                if (isset($user['status']) && $user['status'] == 2) { $_SESSION['login_error'] = "Your account has been permanently banned. Contact " . WEB_EMAIL . " if you believe this is an error."; header('Location: ' . $site_data['web_url'] . '/signin'); exit(); }
                if (isset($user['email_verified']) && $user['email_verified'] == 0) {
                    $otp = rand(100000, 999999);
                    $_SESSION['email'] = $email; $_SESSION['user_id'] = $user['id']; $_SESSION['otp'] = $otp; $_SESSION['otp_time'] = time();
                    $subject = WEB_NAME . " - Email Verification Code";
                    $message = buildSigninEmailTemplate($otp);
                    send_system_email($email, $subject, $message, $pdo, $site_data, [
                        'from_email' => $site_data['web_email'] ?? '',
                        'from_name' => $site_data['web_name'] ?? WEB_NAME,
                    ]);
                    $_SESSION['error_verify'] = "Your email is not verified. We've sent a verification code to your email.";
                    header('Location: ' . $site_data['web_url'] . '/verify'); exit();
                }
                $_SESSION['user_id'] = $user['id']; $_SESSION['user_email'] = $user['email'];
                $_SESSION['logged_in'] = true; $_SESSION['verified'] = true; $_SESSION['is_admin'] = $user['is_admin'];
                if ($remember) {
                    $token = bin2hex(random_bytes(32)); setcookie('remember_token', $token, time() + 86400*30, "/");
                    try { $s = $pdo->prepare("UPDATE users SET remember_token = ? WHERE id = ?"); $s->execute([$token, $user['id']]); } catch(PDOException $e) {}
                }
                header('Location: ' . ($user['is_admin'] == 1 ? $site_data['web_url'] . '/admin/dashboard' : $site_data['web_url'] . '/user/dashboard')); exit();
            } else { $_SESSION['login_error'] = "Invalid email or password"; }
        } else { $_SESSION['login_error'] = "Invalid email or password"; }
    } catch (PDOException $e) { $_SESSION['login_error'] = "Database error occurred. Please try again."; }

    header('Location: ' . $site_data['web_url'] . '/signin'); exit();
}

function buildSigninEmailTemplate($otp) {
    $web_name = WEB_NAME;
    return "<!DOCTYPE html><html><body style='font-family:sans-serif;max-width:600px;margin:0 auto;padding:20px'><div style='background:linear-gradient(135deg,#4D148C,#6b23c2);padding:20px;text-align:center;border-radius:8px 8px 0 0'><h1 style='color:#fff;margin:0'>{$web_name} Verification</h1></div><div style='padding:25px;background:#f9f9f9;border-radius:0 0 8px 8px;border:1px solid #e0e0e0;border-top:none'><p>Your verification code:</p><div style='text-align:center'><div style='background:#4D148C;color:#fff;font-size:28px;font-weight:bold;padding:15px 25px;border-radius:8px;display:inline-block;letter-spacing:5px'>{$otp}</div></div><p style='background:#fff8e1;padding:10px;border-left:4px solid #ffc107;margin:20px 0;font-size:14px'><strong>Important:</strong> This code expires in 60 seconds.</p></div></body></html>";
}

// Generate math captcha
$captcha_num1 = rand(1, 15);
$captcha_num2 = rand(1, 10);
$captcha_op = rand(0, 1) ? '+' : '-';
if ($captcha_op === '-' && $captcha_num1 < $captcha_num2) { $tmp = $captcha_num1; $captcha_num1 = $captcha_num2; $captcha_num2 = $tmp; }
$_SESSION['captcha_result'] = $captcha_op === '+' ? $captcha_num1 + $captcha_num2 : $captcha_num1 - $captcha_num2;
$captcha_question = $captcha_num1 . ' ' . $captcha_op . ' ' . $captcha_num2 . ' = ?';

$page_title = $site_data['web_name'] . " | Sign In";
include('include/header.php');
?>

<!-- Sign In Page -->
<section class="py-16 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto flex flex-col lg:flex-row items-center gap-12">

  <!-- Left: Info Panel -->
  <div class="flex-1 hidden lg:block">
    <div class="relative glassmorphism rounded-3xl p-10 shadow-premium overflow-hidden">
      <div class="absolute inset-0 bg-gradient-to-br from-primary/5 to-accent/5 pointer-events-none"></div>
      <div class="relative z-10">
        <h2 class="text-3xl font-extrabold text-slate-900 mb-4">Welcome back to<br><span class="text-accent"><?php echo htmlspecialchars($site_data['web_name']); ?></span></h2>
        <p class="text-slate-600 text-sm leading-relaxed mb-8">Sign in to access your dashboard, manage orders, fund your wallet, and enjoy all our digital services.</p>

        <!-- Feature highlights -->
        <div class="space-y-4">
          <div class="flex items-center gap-4 bg-slate-50 p-4 rounded-xl border border-slate-100">
            <div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center flex-shrink-0">
              <i class="fa-solid fa-bolt text-primary"></i>
            </div>
            <div>
              <h4 class="text-sm font-bold text-slate-800">Instant Delivery</h4>
              <p class="text-xs text-slate-500">Orders processed in seconds, 24/7</p>
            </div>
          </div>
          <div class="flex items-center gap-4 bg-slate-50 p-4 rounded-xl border border-slate-100">
            <div class="w-10 h-10 rounded-xl bg-accent/10 flex items-center justify-center flex-shrink-0">
              <i class="fa-solid fa-shield-halved text-accent"></i>
            </div>
            <div>
              <h4 class="text-sm font-bold text-slate-800">Secure Wallet</h4>
              <p class="text-xs text-slate-500">Your balance is protected and never expires</p>
            </div>
          </div>
          <div class="flex items-center gap-4 bg-slate-50 p-4 rounded-xl border border-slate-100">
            <div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center flex-shrink-0">
              <i class="fa-solid fa-headset text-primary"></i>
            </div>
            <div>
              <h4 class="text-sm font-bold text-slate-800">24/7 Support</h4>
              <p class="text-xs text-slate-500">We're always here to help via Telegram & WhatsApp</p>
            </div>
          </div>
        </div>

        <!-- Stats -->
        <div class="grid grid-cols-3 gap-4 mt-8 pt-6 border-t border-slate-200">
          <div class="text-center">
            <p class="text-xl font-black text-primary">10K+</p>
            <p class="text-[10px] text-slate-400 uppercase font-semibold">Users</p>
          </div>
          <div class="text-center">
            <p class="text-xl font-black text-accent">50K+</p>
            <p class="text-[10px] text-slate-400 uppercase font-semibold">Orders</p>
          </div>
          <div class="text-center">
            <p class="text-xl font-black text-primary">99.9%</p>
            <p class="text-[10px] text-slate-400 uppercase font-semibold">Uptime</p>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Right: Login Form -->
  <div class="w-full max-w-md">
    <div class="glassmorphism rounded-3xl p-8 shadow-premium">
      <!-- Header -->
      <div class="mb-6">
        <div class="inline-flex items-center gap-2 bg-primary/10 border border-primary/20 rounded-full px-3 py-1 mb-4">
          <span class="w-1.5 h-1.5 rounded-full bg-primary animate-pulse"></span>
          <span class="text-[10px] font-bold text-primary uppercase tracking-wider">Secure Login</span>
        </div>
        <h1 class="text-2xl font-extrabold text-slate-900">Sign In</h1>
        <p class="text-sm text-slate-500 mt-1">Enter your credentials to access your account</p>
      </div>

      <!-- Alerts -->
      <?php if (isset($_SESSION['login_error'])): ?>
      <div class="bg-red-50 border border-red-200 rounded-xl p-4 mb-4 flex items-center gap-3">
        <i class="fa-solid fa-circle-exclamation text-red-500"></i>
        <span class="text-sm text-red-800"><?php echo htmlspecialchars($_SESSION['login_error']); unset($_SESSION['login_error']); ?></span>
      </div>
      <?php endif; ?>

      <!-- Form -->
      <form method="POST" action="" id="signinForm">
        <!-- Email -->
        <div class="mb-4">
          <label class="block text-xs font-bold text-slate-600 uppercase tracking-wider mb-2">Email Address</label>
          <div class="relative">
            <i class="fa-solid fa-envelope absolute left-4 top-1/2 -translate-y-1/2 text-primary/50 text-sm"></i>
            <input type="email" name="LoginForm[email]" required autofocus class="w-full bg-slate-50 border border-slate-200 rounded-xl pl-11 pr-4 py-3 text-sm text-slate-800 focus:outline-none focus:border-primary focus:bg-primary/5 transition-all" placeholder="you@example.com" autocomplete="email">
          </div>
        </div>

        <!-- Password -->
        <div class="mb-4">
          <label class="block text-xs font-bold text-slate-600 uppercase tracking-wider mb-2">Password</label>
          <div class="relative">
            <i class="fa-solid fa-lock absolute left-4 top-1/2 -translate-y-1/2 text-primary/50 text-sm"></i>
            <input id="pwField" type="password" name="LoginForm[password]" required class="w-full bg-slate-50 border border-slate-200 rounded-xl pl-11 pr-12 py-3 text-sm text-slate-800 focus:outline-none focus:border-primary focus:bg-primary/5 transition-all" placeholder="Enter your password" autocomplete="current-password">
            <button type="button" onclick="togglePw()" class="absolute right-3 top-1/2 -translate-y-1/2 w-8 h-8 rounded-lg bg-white border border-slate-200 flex items-center justify-center text-slate-400 hover:text-primary transition-all">
              <i id="eyeIcon" class="fa-solid fa-eye text-xs"></i>
            </button>
          </div>
        </div>

        <!-- Remember / Forgot -->
        <div class="flex items-center justify-between mb-5">
          <label class="flex items-center gap-2 cursor-pointer">
            <input type="checkbox" name="LoginForm[remember]" value="1" checked class="w-4 h-4 accent-primary rounded">
            <span class="text-xs text-slate-600 font-medium">Remember me</span>
          </label>
          <a href="<?php echo $site_data['web_url']; ?>/resetpassword" class="text-xs font-bold text-primary hover:text-accent transition-colors">Forgot password?</a>
        </div>

        <!-- Math Captcha -->
        <div class="mb-5">
          <label class="block text-xs font-bold text-slate-600 uppercase tracking-wider mb-2">
            Solve: <span class="text-primary text-sm ml-1"><?php echo $captcha_question; ?></span>
          </label>
          <div class="relative">
            <i class="fa-solid fa-calculator absolute left-4 top-1/2 -translate-y-1/2 text-primary/50 text-sm"></i>
            <input type="number" name="captcha_answer" required class="w-full bg-slate-50 border border-slate-200 rounded-xl pl-11 pr-4 py-3 text-sm text-slate-800 focus:outline-none focus:border-primary focus:bg-primary/5 transition-all" placeholder="Your answer" autocomplete="off">
          </div>
        </div>

        <!-- Submit -->
        <button type="submit" id="submitBtn" class="w-full bg-primary hover:bg-primary-light text-white font-bold text-sm py-4 rounded-xl transition-all shadow-glow-purple flex items-center justify-center gap-2">
          <i class="fa-solid fa-right-to-bracket"></i>
          <span id="btnText">Sign In to Dashboard</span>
        </button>
      </form>

      <!-- Register link -->
      <div class="text-center mt-6 pt-5 border-t border-slate-200">
        <p class="text-sm text-slate-500">Don't have an account? <a href="<?php echo $site_data['web_url']; ?>/signup" class="font-bold text-primary hover:text-accent transition-colors">Create account →</a></p>
      </div>
    </div>
  </div>
</section>

<script>
function togglePw() {
  var f = document.getElementById('pwField');
  var i = document.getElementById('eyeIcon');
  if (f.type === 'password') { f.type = 'text'; i.className = 'fa-solid fa-eye-slash text-xs'; }
  else { f.type = 'password'; i.className = 'fa-solid fa-eye text-xs'; }
}
document.getElementById('signinForm').addEventListener('submit', function() {
  var btn = document.getElementById('submitBtn');
  btn.disabled = true; btn.classList.add('opacity-50');
  document.getElementById('btnText').textContent = 'Signing in...';
});
</script>

<?php include('include/footer.php'); ?>
