<?php
// admin/deposits.php

// Debugging Enable
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
// Check config path
if (file_exists("includes/config.php")) {
    require_once "includes/config.php";
} else {
    require_once "../includes/config.php";
}

if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}

$error = $success = "";

// ---------------------------------------------------
// 🔍 CAPTURE CURRENT FILTERS (To maintain search state)
// ---------------------------------------------------
$filter_params = $_GET;
unset($filter_params['action']); 
unset($filter_params['id']);
$current_params = http_build_query($filter_params);
$redirect_url = "deposits.php" . ($current_params ? "?" . $current_params : "");

/* ---------------- MANUAL PROMOTION FEES ADD (BONUS) ---------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['manual_deposit'])) {
    $mobile = trim($_POST['mobile']);
    $amt = (float) $_POST['amount'];

    if (!empty($mobile) && $amt > 0) {
        // Get User ID
        $stmt = $conn->prepare("SELECT id FROM users WHERE mobile=? LIMIT 1");
        $stmt->bind_param("s", $mobile);
        $stmt->execute();
        $stmt->bind_result($uid);
        
        if ($stmt->fetch()) {
            $stmt->close();

            // Gateway ID (Promotion Fees)
            $gateway_id = null;
            $g = $conn->prepare("SELECT id FROM gateways WHERE name='Promotion Fees' LIMIT 1");
            $g->execute();
            $g->bind_result($gateway_id);
            $g->fetch();
            $g->close();

            if ($gateway_id === null) {
                // Agar Gateway nahi hai to bana lo
                $conn->query("INSERT INTO gateways (name, upi_id, qr_code, status) VALUES ('Promotion Fees', 'manual', '', 'active')");
                $gateway_id = $conn->insert_id;
            }

            // Insert into Deposits Table
            $stmt2 = $conn->prepare("INSERT INTO deposits (user_id, gateway_id, amount, status, created_at, order_no) VALUES (?, ?, ?, 'successful', NOW(), ?)");
            $order_no = "MANUAL" . time();
            $stmt2->bind_param("iids", $uid, $gateway_id, $amt, $order_no);
            
            if ($stmt2->execute()) {
                $stmt2->close();

                // UPDATE USER BALANCE
                $stmt3 = $conn->prepare("UPDATE users SET bonus_balance = bonus_balance + ? WHERE id=?");
                $stmt3->bind_param("di", $amt, $uid);
                $stmt3->execute();
                $stmt3->close();

                $success = "✅ Manual Bonus ₹$amt added to $mobile! User is now VIP 9.";
            } else {
                $error = "❌ Failed to add deposit record.";
            }
        } else {
            $error = "❌ User not found with this mobile number.";
        }
    } else {
        $error = "❌ Invalid input details.";
    }
}

/* ---------------- APPROVE / REJECT (GATEWAY REQUESTS) ---------------- */
if (isset($_GET['action'], $_GET['id'])) {
    $id = (int)$_GET['id'];
    $action = $_GET['action'];

    $stmt = $conn->prepare("SELECT d.*, g.name as gateway_name FROM deposits d LEFT JOIN gateways g ON d.gateway_id=g.id WHERE d.id=? LIMIT 1");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $deposit = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($deposit) {
        if ($action === 'approve' && $deposit['status'] === 'pending') {
            
            $amt = $deposit['amount'];
            $uid = $deposit['user_id'];
            $g_name = $deposit['gateway_name'];

            // Approve Deposit Status
            $conn->query("UPDATE deposits SET status='successful' WHERE id=$id");
            
            // BALANCE UPDATE LOGIC
            if ($g_name === 'Promotion Fees') {
                $conn->query("UPDATE users SET bonus_balance = bonus_balance + $amt WHERE id=$uid");
            } else {
                $conn->query("UPDATE users SET deposit_balance = deposit_balance + $amt WHERE id=$uid");
            }

        } elseif ($action === 'reject' && $deposit['status'] === 'pending') {
            $conn->query("UPDATE deposits SET status='rejected' WHERE id=$id");
        }
    }
    header("Location: " . $redirect_url);
    exit;
}

/* ---------------- SEARCH & FETCH DEPOSITS ---------------- */
$search = trim($_GET['search'] ?? '');
$where = "1=1";
$params = [];
$types = "";

if ($search !== "") {
    $where .= " AND (u.mobile LIKE ? OR d.order_no LIKE ? OR d.amount LIKE ?)";
    $s = "%$search%";
    // Bind 3 times for mobile, order_no, and amount
    $params[] = $s; $params[] = $s; $params[] = $s;
    $types .= "sss";
}

$manual_deposits = [];
$gateway_deposits = [];

$sql = "SELECT d.*, u.mobile, g.name AS gateway_name 
        FROM deposits d 
        LEFT JOIN users u ON d.user_id=u.id 
        LEFT JOIN gateways g ON d.gateway_id=g.id 
        WHERE $where
        ORDER BY d.id DESC";

$stmt = $conn->prepare($sql);
if ($types) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$res = $stmt->get_result();

if ($res) {
    while ($r = $res->fetch_assoc()) {
        if ($r['gateway_name'] === 'Promotion Fees') {
            $manual_deposits[] = $r;
        } else {
            $gateway_deposits[] = $r;
        }
    }
}
$stmt->close();
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Admin - Deposits</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<style>
body{font-family:'Segoe UI',Arial,sans-serif;margin:0;background:linear-gradient(135deg,#f0f4fb,#dbe6f6);color:#333;}
.svg-icon { width: 18px; height: 18px; vertical-align: middle; margin-right: 6px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.topbar .svg-icon { width: 22px; height: 22px; margin-right: 10px; }
.topbar{background:linear-gradient(90deg,#0047ab,#1a73e8);color:#fff;padding:16px 20px;font-weight:bold;display:flex;justify-content:space-between;align-items:center;box-shadow:0 4px 20px rgba(0,0,0,.2);position:sticky;top:0;z-index:1000;}
.container{max-width:1250px;margin:20px auto;padding:20px;}
.section{background:rgba(255,255,255,0.85);backdrop-filter:blur(8px);padding:25px;margin-bottom:30px;border-radius:18px;box-shadow:0 8px 24px rgba(0,0,0,.12);transition:.3s;}
.section:hover{transform:translateY(-4px);}
.section h2{margin:0 0 15px;font-size:20px;color:#0047ab;display:flex;align-items:center;}
.alert{padding:12px;border-radius:8px;margin-bottom:15px;font-weight:500; display:flex; align-items:center;}
.alert.success{background:#d4edda;color:#155724}
.alert.error{background:#f8d7da;color:#721c24}
form.manual label { display: flex; align-items: center; margin-top: 10px; font-weight: 600; font-size: 14px; color: #444; }
form.manual input{padding:12px;margin:8px 0;width:100%;border-radius:8px;border:1px solid #ccc;font-size:14px;}
form.manual button{background:linear-gradient(90deg,#28a745,#3ecf5e);color:#fff;border:none;padding:12px 20px;border-radius:8px;cursor:pointer;font-weight:bold;box-shadow:0 4px 12px rgba(0,0,0,0.2);transition:.3s; display:flex; align-items:center; justify-content:center; width: 100%; margin-top: 10px;}
form.manual button:hover{transform:scale(1.02);box-shadow:0 6px 16px rgba(0,0,0,0.3);}

/* Search Bar Styles */
.search-box { background: #fff; padding: 15px; border-radius: 12px; display: flex; gap: 10px; margin-bottom: 20px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); align-items: center; flex-wrap: wrap;}
.search-box input { flex: 1; padding: 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 14px; min-width: 200px; }
.search-box button { background: #0047ab; color: #fff; border: none; padding: 12px 24px; border-radius: 8px; cursor: pointer; font-weight: bold; transition: 0.3s; }
.search-box button:hover { background: #1a73e8; }
.search-box a.reset-btn { background: #6c757d; color: #fff; text-decoration: none; padding: 12px 24px; border-radius: 8px; font-weight: bold; transition: 0.3s; display: inline-flex; align-items: center; }
.search-box a.reset-btn:hover { background: #5a6268; }

table{width:100%;border-collapse:collapse;margin-top:10px;border-radius:12px;overflow:hidden;}
th,td{padding:14px;font-size:14px;text-align:left}
th{background:linear-gradient(90deg,#0047ab,#1a73e8);color:#fff;font-weight:600}
tr:nth-child(even){background:#f9fbff}
tr:hover{background:#eef4ff;transition:.3s}
.status{padding:6px 14px;border-radius:50px;font-weight:600;font-size:13px;display:inline-flex; align-items: center;}
.status.pending{background:#fff3cd;color:#856404}
.status.success{background:#d4edda;color:#155724}
.status.rejected{background:#f8d7da;color:#721c24}
.actions { display: flex; gap: 5px; }
.actions a{text-decoration:none;padding:8px 14px;border-radius:50px;font-size:13px;font-weight:bold;transition:.3s; display:inline-flex; align-items: center;}
.approve{background:linear-gradient(90deg,#28a745,#3ecf5e);color:#fff;box-shadow:0 3px 10px rgba(40,167,69,0.4);}
.approve:hover{box-shadow:0 6px 16px rgba(40,167,69,0.6);transform:scale(1.05);}
.reject{background:linear-gradient(90deg,#dc3545,#ff5c5c);color:#fff;box-shadow:0 3px 10px rgba(220,53,69,0.4);}
.reject:hover{box-shadow:0 6px 16px rgba(220,53,69,0.6);transform:scale(1.05);}
.back{background:#6c757d;color:#fff;text-decoration:none;padding:8px 14px;border-radius:6px;font-size:14px;transition:.3s; display:inline-flex; align-items:center;}
.back:hover{background:#5a6268;}
</style>
</head>
<body>
<div class="topbar">
  <div style="display:flex; align-items:center;">
      <svg class="svg-icon" viewBox="0 0 24 24"><path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"></path></svg>
      COSCO ADMIN PANEL
  </div>
  <a href="dashboard.php" class="back">
      <svg class="svg-icon" viewBox="0 0 24 24" style="margin-right:4px;"><path d="M19 12H5M12 19l-7-7 7-7"/></svg> 
      Back
  </a>
</div>

<div class="container">

  <div class="section">
    <h2>
        <svg class="svg-icon" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="16"></line><line x1="8" y1="12" x2="16" y2="12"></line></svg>
        Add Manual Bonus (VIP 9 Access)
    </h2>
    
    <?php if($success): ?>
        <div class="alert success">
            <svg class="svg-icon" viewBox="0 0 24 24"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>
            <?=$success?>
        </div>
    <?php endif; ?>
    
    <?php if($error): ?>
        <div class="alert error">
            <svg class="svg-icon" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"></circle><line x1="15" y1="9" x2="9" y2="15"></line><line x1="9" y1="9" x2="15" y2="15"></line></svg>
            <?=$error?>
        </div>
    <?php endif; ?>

    <form method="post" class="manual">
      <input type="hidden" name="manual_deposit" value="1">
      
      <label>
          <svg class="svg-icon" style="width:16px;height:16px;color:#666;" viewBox="0 0 24 24"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path></svg>
          User Mobile:
      </label>
      <input type="text" name="mobile" placeholder="Enter mobile number" required>
      
      <label>
          <svg class="svg-icon" style="width:16px;height:16px;color:#666;" viewBox="0 0 24 24"><line x1="12" y1="1" x2="12" y2="23"></line><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path></svg>
          Bonus Amount (₹):
      </label>
      <input type="number" step="0.01" name="amount" required>
      
      <button type="submit">
          <svg class="svg-icon" viewBox="0 0 24 24"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
          Add Bonus
      </button>
    </form>
  </div>

  <div class="section">
    <h2>
        <svg class="svg-icon" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"></circle><line x1="2" y1="12" x2="22" y2="12"></line><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"></path></svg>
        Gateway Deposit Requests
    </h2>

    <form method="get" class="search-box">
        <input type="text" name="search" placeholder="Search by Mobile, Order No, or Amount..." value="<?=htmlspecialchars($search)?>">
        <button type="submit"><svg class="svg-icon" viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg> Search</button>
        <?php if($search): ?>
            <a href="deposits.php" class="reset-btn">Clear</a>
        <?php endif; ?>
    </form>

    <div style="overflow-x:auto;">
    <table>
      <tr>
        <th>ID</th><th>Order No</th><th>User</th><th>Gateway</th><th>Amount</th>
        <th>Status</th><th>Created</th><th>Action</th>
      </tr>
      <?php if(empty($gateway_deposits)): ?>
        <tr><td colspan="8" style="text-align:center; padding:20px; color:#777;">No gateway deposits requests found matching your search.</td></tr>
      <?php else: foreach($gateway_deposits as $d): ?>
        <tr>
          <td>#<?=$d['id']?></td>
          <td><?=$d['order_no'] ?: '-'?></td>
          <td><?=$d['mobile']?></td>
          <td><?=$d['gateway_name'] ?: 'N/A'?></td>
          <td><b>₹<?=number_format($d['amount'],2)?></b></td>
          <td>
            <span class="status <?=$d['status'] == 'successful' ? 'success' : $d['status']?>">
                <?php if($d['status']=='successful' || $d['status']=='approved'): ?>
                   <svg class="svg-icon" style="width:14px;height:14px;margin-right:4px;" viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg>
                   Success
                <?php elseif($d['status']=='rejected'): ?>
                   <svg class="svg-icon" style="width:14px;height:14px;margin-right:4px;" viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
                   Rejected
                <?php else: ?>
                   <svg class="svg-icon" style="width:14px;height:14px;margin-right:4px;" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>
                   Pending
                <?php endif; ?>
            </span>
          </td>
          <td><?=date('d M Y, h:i A', strtotime($d['created_at']))?></td>
          <td class="actions">
            <?php if($d['status']=='pending'): ?>
              <a href="?action=approve&id=<?=$d['id']?>&<?=$current_params?>" class="approve">
                  <svg class="svg-icon" style="width:16px;height:16px;" viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg>
                  Approve
              </a>
              <a href="?action=reject&id=<?=$d['id']?>&<?=$current_params?>" class="reject">
                  <svg class="svg-icon" style="width:16px;height:16px;" viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
                  Reject
              </a>
            <?php else: ?>
              <span style="color:#aaa;">Completed</span>
            <?php endif; ?>
          </td>
        </tr>
      <?php endforeach; endif; ?>
    </table>
    </div>
  </div>

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