<?php
/**
 * agent_mission.php
 * Agent Panel-এর Mission/Milestone System — এখন এটা Days-এর বদলে
 * তার Downline User-দের মোট (Approved) Deposit Amount-এর উপর
 * ভিত্তি করে কাজ করে। যেমন: "মোট ৳10,000 Deposit হলে ৳200 Bonus"।
 *
 * Bonus সরাসরি ব্যবহার করা যাবে না — শুধু Admin-এর কাছে "Sell"
 * (Cash-out Request) করা যাবে, bKash/Nagad Number দিয়ে।
 *
 * ✅ এটা সম্পূর্ণ নতুন ফাইল — কোনো Existing ফাইল স্পর্শ করা হয়নি।
 */
session_start();
if (!isset($_SESSION['agent_uid']) || $_SESSION['agent_uid'] == "") {
    header("location:index.php");
    exit;
}
include("conn.php");

$agent_uid = $_SESSION['agent_uid'];
$agent_mobile = $_SESSION['agent_mobile'];

$agent_verify = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT userid FROM tb_agent WHERE userid='$agent_uid' AND status='1'"
));
if (!$agent_verify) {
    session_destroy();
    header("location:index.php?err=kicked");
    exit;
}

$agent_wallet = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT motta FROM shonu_kaichila WHERE balakedara='$agent_uid'"
));
$agent_balance = $agent_wallet['motta'] ?? 0;

$agent_code_row = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT owncode FROM shonu_subjects WHERE id='$agent_uid'"
));
$agent_owncode = $agent_code_row['owncode'] ?? '';

/* ══════════════════════════════════════════════════════════
   Milestone Config টেবিল — এখন Deposit Amount-ভিত্তিক
   না থাকলে তৈরি হবে, প্রথমবার Default Milestone বসানো হবে
   ══════════════════════════════════════════════════════════ */
mysqli_query($conn, "
    CREATE TABLE IF NOT EXISTS agent_mission_milestones (
        id INT AUTO_INCREMENT PRIMARY KEY,
        deposit_required DECIMAL(15,2) NOT NULL UNIQUE,
        bonus_amount DECIMAL(15,2) NOT NULL DEFAULT 0,
        is_active TINYINT(1) NOT NULL DEFAULT 1
    )
");
$countRow = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as c FROM agent_mission_milestones"));
if ((int)$countRow['c'] === 0) {
    mysqli_query($conn, "
        INSERT INTO agent_mission_milestones (deposit_required, bonus_amount) VALUES
        (5000, 100), (10000, 250), (25000, 700), (50000, 1500), (100000, 3500), (200000, 8000)
    ");
}

/* ══════════════════════════════════════════════════════════
   Sell Request টেবিল — না থাকলে তৈরি হবে
   ══════════════════════════════════════════════════════════ */
mysqli_query($conn, "
    CREATE TABLE IF NOT EXISTS agent_mission_sell_requests (
        id INT AUTO_INCREMENT PRIMARY KEY,
        agent_userid VARCHAR(50) NOT NULL,
        milestone_id INT NOT NULL,
        deposit_required DECIMAL(15,2) NOT NULL,
        bonus_amount DECIMAL(15,2) NOT NULL,
        payment_method VARCHAR(20) NOT NULL,
        payment_number VARCHAR(20) NOT NULL,
        status VARCHAR(20) NOT NULL DEFAULT 'pending',
        requested_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        processed_at DATETIME NULL,
        UNIQUE KEY uniq_agent_milestone (agent_userid, milestone_id)
    )
");

$message = '';
$message_type = '';

/* ══════════════════════════════════════════════════════════
   Downline User-দের ID খুঁজে বের করা
   ══════════════════════════════════════════════════════════ */
$downlineIds = [];
$dlRes = mysqli_query($conn, "SELECT id FROM shonu_subjects WHERE code = '".mysqli_real_escape_string($conn, $agent_owncode)."'");
while ($r = mysqli_fetch_assoc($dlRes)) { $downlineIds[] = $r['id']; }

/* ══════════════════════════════════════════════════════════
   Downline-দের মোট Approved Deposit বের করা (thevani.sthiti='1')
   ══════════════════════════════════════════════════════════ */
$totalDeposit = 0;
if (!empty($downlineIds)) {
    $idList = implode(',', array_map('intval', $downlineIds));
    $depRow = mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT COALESCE(SUM(motta),0) as total FROM thevani WHERE balakedara IN ($idList) AND sthiti = '1'"
    ));
    $totalDeposit = floatval($depRow['total']);
}

/* ══════════════════════════════════════════════════════════
   সব Milestone আনা + প্রতিটার Status বের করা
   ══════════════════════════════════════════════════════════ */
$milestones = [];
$mResult = mysqli_query($conn, "SELECT * FROM agent_mission_milestones WHERE is_active = 1 ORDER BY deposit_required ASC");
while ($m = mysqli_fetch_assoc($mResult)) {
    $claimRow = mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT status FROM agent_mission_sell_requests WHERE agent_userid = '$agent_uid' AND milestone_id = '".$m['id']."'"
    ));
    $m['claim_status'] = $claimRow ? $claimRow['status'] : null;
    $m['unlocked'] = $totalDeposit >= floatval($m['deposit_required']);
    $milestones[] = $m;
}

/* ══════════════════════════════════════════════════════════
   Sell Request পাঠানো
   ══════════════════════════════════════════════════════════ */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'sell_mission') {
    $milestoneId = (int)($_POST['milestone_id'] ?? 0);
    $paymentMethod = ($_POST['payment_method'] ?? '') === 'nagad' ? 'nagad' : 'bkash';
    $paymentNumberRaw = trim($_POST['payment_number'] ?? '');
    $paymentNumber = preg_replace('/[^0-9]/', '', $paymentNumberRaw);

    $target = null;
    foreach ($milestones as $m) {
        if ((int)$m['id'] === $milestoneId) { $target = $m; break; }
    }

    if (!preg_match('/^01[0-9]{9}$/', $paymentNumber)) {
        $message = '❌ সঠিক ১১-সংখ্যার bKash/Nagad Number দাও (01XXXXXXXXX)।';
        $message_type = 'danger';
    } elseif (!$target) {
        $message = '❌ ভুল Milestone।';
        $message_type = 'danger';
    } elseif (!$target['unlocked']) {
        $message = '❌ এই Milestone এখনো Unlock হয়নি।';
        $message_type = 'danger';
    } elseif ($target['claim_status'] !== null) {
        $message = '❌ এই Milestone-এর জন্য আগেই Request পাঠানো হয়েছে।';
        $message_type = 'danger';
    } else {
        $insertStmt = $conn->prepare("
            INSERT INTO agent_mission_sell_requests
            (agent_userid, milestone_id, deposit_required, bonus_amount, payment_method, payment_number, status)
            VALUES (?, ?, ?, ?, ?, ?, 'pending')
        ");
        $insertStmt->bind_param("sidsss", $agent_uid, $milestoneId, $target['deposit_required'], $target['bonus_amount'], $paymentMethod, $paymentNumber);
        $insertStmt->execute();
        $insertStmt->close();

        $message = "✅ ৳".number_format($target['deposit_required'],0)." Deposit Milestone-এর ৳".number_format($target['bonus_amount'],2)." Sell Request পাঠানো হয়েছে।";
        $message_type = 'success';

        foreach ($milestones as &$m2) {
            if ((int)$m2['id'] === $milestoneId) { $m2['claim_status'] = 'pending'; }
        }
        unset($m2);
    }
}

include("header.php");
?>

<div class="al-wrap">
  <div class="al-page-title">Agent Mission</div>
  <div class="al-page-sub">তোমার Downline User-দের মোট Deposit: <b class="mono" style="color:var(--gold);">৳<?php echo number_format($totalDeposit,2); ?></b></div>

  <?php if ($message): ?>
  <div class="al-alert al-alert-<?php echo $message_type; ?>"><?php echo htmlspecialchars($message); ?></div>
  <?php endif; ?>

  <?php foreach ($milestones as $m): ?>
  <div class="al-card" style="border-left:3px solid <?php echo $m['unlocked'] ? 'var(--gold)' : 'var(--border)'; ?>; margin-bottom:12px; padding:16px;">
    <div style="display:flex;justify-content:space-between;align-items:center;">
      <div>
        <div style="font-weight:700;font-size:15px;color:var(--text);">৳<?php echo number_format($m['deposit_required'],0); ?> Deposit Mission</div>
        <div style="font-size:12px;color:var(--text-faint);margin-top:2px;">Bonus: ৳<?php echo number_format($m['bonus_amount'],2); ?></div>
      </div>
      <div>
        <?php if (!$m['unlocked']): ?>
          <span class="al-stamp" style="background:rgba(150,145,184,.15);color:var(--text-faint);">🔒 Locked (আরও ৳<?php echo number_format(max(0, $m['deposit_required'] - $totalDeposit),0); ?> লাগবে)</span>
        <?php elseif ($m['claim_status'] === 'approved'): ?>
          <span class="al-stamp" style="background:rgba(31,185,121,.15);color:#1FB979;">✅ Sold</span>
        <?php elseif ($m['claim_status'] === 'pending'): ?>
          <span class="al-stamp" style="background:rgba(245,197,66,.15);color:var(--gold);">⏳ Pending</span>
        <?php elseif ($m['claim_status'] === 'rejected'): ?>
          <span class="al-stamp" style="background:rgba(232,84,74,.15);color:#E8544A;">❌ Rejected</span>
        <?php else: ?>
          <span class="al-stamp" style="background:rgba(34,211,238,.15);color:var(--cyan);">🎉 Unlocked</span>
        <?php endif; ?>
      </div>
    </div>

    <?php if ($m['unlocked'] && $m['claim_status'] === null): ?>
    <form method="POST" style="margin-top:14px;border-top:1px solid var(--border);padding-top:12px;">
      <input type="hidden" name="action" value="sell_mission">
      <input type="hidden" name="milestone_id" value="<?php echo $m['id']; ?>">
      <div style="display:flex;gap:8px;flex-wrap:wrap;">
        <select name="payment_method" required style="flex:1;min-width:100px;padding:9px;border-radius:8px;border:1px solid var(--border);background:var(--bg);color:var(--text);">
          <option value="bkash">bKash</option>
          <option value="nagad">Nagad</option>
        </select>
        <input type="text" name="payment_number" placeholder="01XXXXXXXXX" required maxlength="11"
               style="flex:2;min-width:150px;padding:9px;border-radius:8px;border:1px solid var(--border);background:var(--bg);color:var(--text);">
        <button type="submit" class="al-btn al-btn-cyan" style="flex:1;min-width:100px;"
          onclick="return confirm('৳<?php echo number_format($m['bonus_amount'],2); ?> Sell Request পাঠাবে?');">
          💰 Sell করো
        </button>
      </div>
    </form>
    <?php endif; ?>
  </div>
  <?php endforeach; ?>

</div>
</body>
</html>
