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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount = floatval($_POST['amount']);
    $txn_id = sanitize($_POST['transaction_id']);
    $notes = sanitize($_POST['notes'] ?? '');
    $sa_id = (int)$_SESSION['user_id'];

    // Handle screenshot upload
    $screenshot_path = '';
    if (isset($_FILES['screenshot']) && $_FILES['screenshot']['error'] === 0) {
        $upload_dir = '../../uploads/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 = 'dep_sa_' . $sa_id . '_' . time() . '.' . $ext;
            if (move_uploaded_file($_FILES['screenshot']['tmp_name'], $upload_dir . $filename)) {
                $screenshot_path = SITE_URL . '/uploads/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 subadmin_deposit_requests (sub_admin_id, amount, transaction_id, screenshot_path, notes) VALUES (?,?,?,?,?)");
        $stmt->bind_param('idsss', $sa_id, $amount, $txn_id, $screenshot_path, $notes);
        if ($stmt->execute()) {
            $success = "Deposit request of " . formatINR($amount) . " submitted successfully! Pending admin approval.";
        } else {
            $error = "Failed to submit request. Please try again.";
        }
    }
}

// Fetch history
$history = $conn->query("SELECT * FROM subadmin_deposit_requests WHERE sub_admin_id=" . (int)$_SESSION['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>Request Deposit - Sub Admin | 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">
    <style>.btn-primary{background:linear-gradient(135deg,var(--subadmin-accent),#0369a1)}</style>
</head>
<body>
<div class="dashboard-wrapper">
    <?php include 'partials/sidebar.php'; ?>
    <div class="main-content">
        <div class="topbar">
            <div class="topbar-title"><h1>Request Deposit</h1><p>Submit a deposit request to Master Admin</p></div>
            <div class="topbar-actions">
                <div class="wallet-display">
                    <span>💰</span>
                    <div><div class="label">My Wallet</div><div class="amount"><?= formatINR($sa['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">
                        <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="Bank/UPI Transaction Reference ID" required>
                            </div>
                            <div class="form-group">
                                <label>Payment Screenshot</label>
                                <div class="upload-area" id="uploadArea" 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, PDF 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/*,application/pdf" onchange="previewFile(this)">
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Notes (Optional)</label>
                                <textarea name="notes" class="form-control" rows="3" placeholder="Any additional information for admin..." 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>📋 Request 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['admin_note']): ?>
                            <div style="font-size:12px;color:var(--danger);margin-top:4px">❌ <?= htmlspecialchars($h['admin_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);
    } else {
        document.getElementById('previewImg').style.display = 'none';
    }
}
</script>
</body>
</html>
