<?php
require_once '../../config.php';
requireLogin('user');
$user = $conn->query("SELECT * FROM users WHERE id=" . (int)$_SESSION['user_id'])->fetch_assoc();
$success = $error = '';
$user_id = (int)$_SESSION['user_id'];
$sa_id = (int)$user['sub_admin_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount = floatval($_POST['amount']);
    $txn_id = sanitize($_POST['transaction_id']);
    $notes = sanitize($_POST['notes'] ?? '');
    $screenshot_path = '';
    if (isset($_FILES['screenshot']) && $_FILES['screenshot']['error'] === 0) {
        $upload_dir = '../../uploads/user_deposits/';
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
        $ext = pathinfo($_FILES['screenshot']['name'], PATHINFO_EXTENSION);
        $allowed = ['jpg','jpeg','png','gif','webp','pdf'];
        if (in_array(strtolower($ext), $allowed)) {
            $filename = 'udep_' . $user_id . '_' . time() . '.' . $ext;
            if (move_uploaded_file($_FILES['screenshot']['tmp_name'], $upload_dir . $filename)) {
                $screenshot_path = SITE_URL . '/uploads/user_deposits/' . $filename;
            }
        }
    }
    if ($amount <= 0) { $error = "Please enter a valid amount."; }
    elseif (empty($txn_id)) { $error = "Transaction ID is required."; }
    else {
        $stmt = $conn->prepare("INSERT INTO user_deposit_requests (user_id, sub_admin_id, amount, transaction_id, screenshot_path, notes) VALUES (?,?,?,?,?,?)");
        $stmt->bind_param('iidsss', $user_id, $sa_id, $amount, $txn_id, $screenshot_path, $notes);
        if ($stmt->execute()) {
            $success = "Deposit request of " . formatINR($amount) . " submitted! Pending Sub Admin approval.";
        } else {
            $error = "Failed to submit. Please try again.";
        }
    }
}

$history = $conn->query("SELECT * FROM user_deposit_requests WHERE user_id=$user_id ORDER BY created_at DESC")->fetch_all(MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Deposit Funds - User | Cricket Exchange</title>
    <link rel="stylesheet" href="../../assets/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
</head>
<body>
<div class="dashboard-wrapper">
    <?php include 'partials/sidebar.php'; ?>

    <div class="main-content">
        <div class="topbar">
            <div class="topbar-title"><h1>Deposit Funds</h1><p>Submit a deposit request to your Sub Admin</p></div>
            <div class="topbar-actions">
                <div class="wallet-display"><span>💰</span><div><div class="label">Balance</div><div class="amount"><?= formatINR($user['wallet_balance']) ?></div></div></div>
            </div>
        </div>
        <div class="page-content">
            <?php if ($success): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= $success ?></div><?php endif; ?>
            <?php if ($error): ?><div class="alert alert-error"><i class="fas fa-times-circle"></i> <?= $error ?></div><?php endif; ?>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:24px;align-items:start;">
                <div class="card">
                    <div class="card-header"><h3>📥 New Deposit Request</h3></div>
                    <div class="card-body">
                        <div class="alert alert-info" style="margin-bottom:20px">
                            <i class="fas fa-info-circle"></i>
                            Transfer money to your Sub Admin's account, then submit the transaction details below for approval.
                        </div>
                        <form method="POST" enctype="multipart/form-data">
                            <div class="form-group">
                                <label>Amount (₹) *</label>
                                <input type="number" name="amount" class="form-control" placeholder="Enter deposit amount" min="1" required step="0.01">
                            </div>
                            <div class="form-group">
                                <label>Transaction ID *</label>
                                <input type="text" name="transaction_id" class="form-control" placeholder="UPI/Bank Reference ID" required>
                            </div>
                            <div class="form-group">
                                <label>Payment Screenshot *</label>
                                <div class="upload-area" onclick="document.getElementById('screenshotInput').click()">
                                    <div id="uploadPlaceholder"><div style="font-size:32px;margin-bottom:8px">📷</div><div style="font-weight:600;color:var(--text)">Click to upload screenshot</div><div style="font-size:12px;color:var(--text-muted);margin-top:4px">JPG, PNG up to 5MB</div></div>
                                    <div id="uploadPreview" style="display:none"><img id="previewImg" style="max-height:150px;border-radius:8px"><div id="fileName" style="font-size:13px;color:var(--primary);margin-top:8px"></div></div>
                                    <input type="file" name="screenshot" id="screenshotInput" accept="image/*" onchange="previewFile(this)">
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Notes (Optional)</label>
                                <textarea name="notes" class="form-control" rows="2" placeholder="Any notes..." style="resize:vertical"></textarea>
                            </div>
                            <button type="submit" class="btn btn-primary btn-full"><i class="fas fa-paper-plane"></i> Submit Deposit Request</button>
                        </form>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header"><h3>📋 Deposit History</h3></div>
                    <div style="max-height:500px;overflow-y:auto;">
                        <?php foreach ($history as $h): ?>
                        <div style="padding:16px 20px;border-bottom:1px solid var(--border)">
                            <div style="display:flex;justify-content:space-between;align-items:start;margin-bottom:8px">
                                <span class="text-primary fw-700" style="font-size:18px"><?= formatINR($h['amount']) ?></span>
                                <span class="badge badge-<?= $h['status'] ?>"><?= ucfirst($h['status']) ?></span>
                            </div>
                            <div style="font-size:13px;color:var(--text-muted)">TXN: <code><?= htmlspecialchars($h['transaction_id']) ?></code></div>
                            <?php if ($h['screenshot_path']): ?><a href="<?= $h['screenshot_path'] ?>" target="_blank" style="font-size:12px;color:var(--info)">📷 View Screenshot</a><?php endif; ?>
                            <?php if ($h['subadmin_note']): ?><div style="font-size:12px;color:var(--danger);margin-top:4px">Note: <?= htmlspecialchars($h['subadmin_note']) ?></div><?php endif; ?>
                            <div style="font-size:11px;color:var(--text-dim);margin-top:6px"><?= date('d M Y H:i', strtotime($h['created_at'])) ?></div>
                        </div>
                        <?php endforeach; ?>
                        <?php if (empty($history)): ?><div class="empty-state"><div class="empty-icon">📥</div><p>No requests yet</p></div><?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php include 'partials/scripts.php'; ?>
<script>
function previewFile(input) {
    const file = input.files[0]; if (!file) return;
    document.getElementById('uploadPlaceholder').style.display = 'none';
    document.getElementById('uploadPreview').style.display = 'block';
    document.getElementById('fileName').textContent = file.name;
    if (file.type.startsWith('image/')) {
        const reader = new FileReader();
        reader.onload = e => { document.getElementById('previewImg').src = e.target.result; document.getElementById('previewImg').style.display = 'block'; };
        reader.readAsDataURL(file);
    }
}
</script>
</body>
</html>
