<?php
// deposit.php
session_start();
require 'db.php'; // hakikisha una db.php yenye inaconnect $conn

// ----------- CHECK STATUS (AJAX) ----------
if (isset($_GET['check_status']) && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $stmt = $conn->prepare("SELECT status FROM deposits WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    header("Content-Type: application/json");
    echo json_encode(["status" => $res['status'] ?? "pending"]);
    exit;
}
// -----------------------------------------

// For demo, assume user amelogin
if (!isset($_SESSION['user_id'])) {
  $_SESSION['user_id'] = 1; // fallback demo
}
$user_id = (int)$_SESSION['user_id'];

$msg = "";
$deposit_id = null;

if ($_SERVER['REQUEST_METHOD'] === "POST") {
    $reference = trim($_POST['reference']);
    $amount    = (float)$_POST['amount'];

    if (!$reference || !$amount) {
        $msg = "⚠ Please fill all fields";
    } elseif (!isset($_FILES['screenshot']) || $_FILES['screenshot']['error'] !== UPLOAD_ERR_OK) {
        $msg = "⚠ Please upload a valid screenshot";
    } else {
        $file = $_FILES['screenshot'];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg','jpeg','png'];

        if (!in_array($ext, $allowed)) {
            $msg = "⚠ Only JPG, JPEG, PNG allowed";
        } elseif ($file['size'] > 5*1024*1024) {
            $msg = "⚠ File too large (max 5MB)";
        } else {
            $newName = uniqid("ss_", true) . "." . $ext;
            $uploadPath = "uploads/" . $newName;
            if (!is_dir("uploads")) mkdir("uploads");

            if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
                $stmt = $conn->prepare("INSERT INTO deposits 
                    (user_id, phone, amount, reference, screenshot, status, created_at) 
                    VALUES (?, '', ?, ?, ?, 'pending', NOW())");
                $stmt->bind_param("idss", $user_id, $amount, $reference, $newName);

                if ($stmt->execute()) {
                    $deposit_id = $stmt->insert_id;
                    $msg = "✅ Deposit submitted successfully!";
                } else {
                    $msg = "❌ Database error: " . $conn->error;
                }
            } else {
                $msg = "⚠ Failed to save screenshot";
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>EWA Pay</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    body { margin: 0; font-family: Arial, sans-serif; background: #f0f9f4; }
    .app { max-width: 400px; margin: 20px auto; background: #fff; border-radius: 12px;
           box-shadow: 0 0 8px rgba(0,0,0,0.2); overflow: hidden; position:relative; }
    .header { display: flex; justify-content: space-between; align-items: center;
              padding: 12px; background: #fff; border-bottom: 1px solid #eee; }
    .header img { height: 32px; border-radius: 15px; }
    .lang { display: flex; gap: 8px; }
    .lang button { border: none; padding: 6px 14px; border-radius: 6px; cursor: pointer; font-weight: bold; }
    .lang .active { background: #16a34a; color: #fff; }
    .content { padding: 16px; }
    .pay-text { background: #ecfdf5; color: #047857; text-align: center; padding: 10px; border-radius: 8px; font-weight: bold; margin: 12px 0; }
    .qr-section { display: flex; gap: 10px; margin-bottom: 12px; }
    .qr-card { flex: 1; border: 1px solid #ddd; border-radius: 8px; text-align: center; padding: 8px; }
    .qr-card img { width: 100%; border-radius: 8px; }
    .upload-container { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center;
                        border: 1px dashed #bbb; border-radius: 8px; color: #16a34a; font-weight: bold; font-size: 18px;
                        cursor: pointer; padding: 8px; }
    .upload-container input[type="file"] { display: none; }
    .upload-label { margin-top: 6px; font-size: 12px; color: #374151; text-align: center; }
    .input-group { margin: 12px 0; }
    .input-group label { font-size: 14px; display: block; margin-bottom: 4px; color: #374151; }
    .input-group input { width: 94%; padding: 10px; border-radius: 6px; border: 1px solid #ccc; font-size: 15px; }
    .remark { margin: 12px 0; display: flex; justify-content: space-between; align-items: center;
              background: #f3f4f6; padding: 10px; border-radius: 6px; }
    .remark span { font-weight: bold; color: #16a34a; }
    .copy-btn { background: #16a34a; color: #fff; border: none; padding: 4px 12px; border-radius: 6px; cursor: pointer; font-size: 12px; font-weight: bold; }
    .submit { background: #16a34a; color: #fff; font-size: 16px; font-weight: bold; padding: 12px; text-align: center;
              border-radius: 8px; cursor: pointer; margin-top: 8px; width: 100%; }
    .expire { text-align: center; color: #16a34a; font-weight: bold; margin-top: 10px; font-size:18px; }
    .footer { font-size: 12px; color: #666; text-align: center; margin: 10px 0; }
    .yellow-box { background: #fef08a; padding: 10px; border-radius: 8px; }
    .yellow-box h3 { margin: 6px 0; font-size: 16px; font-weight: bold; }
    .qrnote { font-size: 12px; color: #ef4444; }
    .message { text-align:center; margin:10px 0; font-weight:bold; }

    /* popup success inside container */
    .popup {
      position: absolute;
      top:0; left:0;
      width:100%; height:100%;
      display:flex;
      align-items:center; justify-content:center;
      background: rgba(0,0,0,0.6);
      visibility:hidden;
      z-index: 999;
    }
    .popup .box {
      background:#fff;
      padding:30px;
      border-radius:12px;
      text-align:center;
      font-size:20px;
      font-weight:bold;
      color:green;
      animation: glow 1s infinite alternate;
    }
    @keyframes glow {
      from { box-shadow:0 0 10px #16a34a; }
      to { box-shadow:0 0 30px #16a34a; }
    }

    /* popup for copy */
    #copyPopup {
      position: fixed;
      top:50%;
      left:50%;
      transform: translate(-50%, -50%);
      background: rgba(0,0,0,0.7);
      padding: 12px 24px;
      border-radius: 12px;
      color:#fff;
      font-weight:bold;
      font-size:16px;
      display:flex;
      align-items:center;
      justify-content:center;
      visibility:hidden;
      z-index: 9999;
      opacity:0;
      transition: opacity 0.3s ease;
    }
    #copyPopup.show {
      visibility: visible;
      opacity:1;
    }
  </style>
</head>
<body>
  <div class="app">
    <div class="header">
      <img src="mk.jpg" alt="EWA Pay Logo">
      <div class="lang">
        <button class="active">ASM</button>
      </div>
    </div>
    <div class="content">
      <?php if($msg): ?>
        <div class="message"><?= htmlspecialchars($msg) ?></div>
      <?php endif; ?>
      <form method="post" enctype="multipart/form-data">
        <div class="pay-text">Pay the amount you input below</div>

        <div class="qr-section">
          <div class="qr-card yellow-box">
            <img src="qr.jpg" alt="QR Code">
            <h3>John</h3>
            <div class="remark" style="justify-content:center; margin-top:6px;">
              <span id="mpesaNumber">0790820641</span>
              <button type="button" class="copy-btn" onclick="copyMpesaNumber()">Copy</button>
            </div>
           
          </div>

          <label class="upload-container">
            +<br>Upload
            <input type="file" name="screenshot" id="screenshot" accept="image/*" required>
            <span class="upload-label">Upload Payment Screenshot</span>
          </label>
        </div>

        <div class="input-group">
          <label>Amount</label>
          <input type="number" name="amount" id="amount" placeholder="Enter amount" required>
        </div>

        <div class="input-group">
          <label>Mpesa Code</label>
          <input type="text" name="reference" id="tid" placeholder="Please input Mpesa Code" required>
        </div>

        <button type="submit" class="submit">Submit</button>
        <?php if ($deposit_id): ?>
          <div class="expire" id="countdown">Expiration 10:00</div>
        <?php endif; ?>
      </form>
    </div>
    <div class="footer">© 2025 ASM Pay. All rights reserved.</div>

    <!-- popup success -->
    <div class="popup" id="popup">
      <div class="box">✅ Payment Success</div>
    </div>

    <!-- popup copy -->
    <div id="copyPopup">Copied</div>
  </div>

  <script>
    function copyMpesaNumber() {
      const number = document.getElementById('mpesaNumber').textContent;
      navigator.clipboard.writeText(number).then(() => {
        const copyPopup = document.getElementById('copyPopup');
        copyPopup.classList.add('show');
        setTimeout(() => { copyPopup.classList.remove('show'); }, 2000);
      });
    }

    <?php if ($deposit_id): ?>
      let timeLeft = 600; // 10 mins
      const countdownEl = document.getElementById("countdown");
      const popup = document.getElementById("popup");

      const timer = setInterval(() => {
        if (timeLeft <= 0) {
          clearInterval(timer);
          countdownEl.textContent = "❌ Expired";
        } else {
          let m = Math.floor(timeLeft/60);
          let s = timeLeft%60;
          countdownEl.textContent = "Expiration " + String(m).padStart(2,'0') + ":" + String(s).padStart(2,'0');
          timeLeft--;
        }
      },1000);

      setInterval(() => {
        fetch("deposit.php?check_status=1&id=<?= $deposit_id ?>")
          .then(r=>r.json())
          .then(data=>{
            if (data.status === "success") {
              popup.style.visibility = "visible";
              setTimeout(()=>{ popup.style.visibility = "hidden"; },7000);
              clearInterval(timer);
              countdownEl.textContent = "✅ Success";
            }
          });
      },2000);
    <?php endif; ?>
  </script>
</body>
</html>
