<?php
require_once '../includes/functions.php';
requireLogin();

$msg = '';
$user_id = $_SESSION['user_id'];

// Handle Final Confirmation from process_payment.php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['utr'])) {
    $amount = $_POST['amount'];
    $utr = $_POST['utr'];
    $screenshot_path = '';
    
    // Handle Screenshot Upload (Optional in this flow but good to have)
    if (isset($_FILES['screenshot']) && $_FILES['screenshot']['error'] === 0) {
        $allowed = ['jpg', 'jpeg', 'png'];
        $filename = $_FILES['screenshot']['name'];
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        if (in_array($ext, $allowed)) {
            $new_name = uniqid() . '.' . $ext;
            if (!file_exists('../uploads/payments/')) mkdir('../uploads/payments/', 0777, true);
            $upload_path = '../uploads/payments/' . $new_name;
            if (move_uploaded_file($_FILES['screenshot']['tmp_name'], $upload_path)) {
                $screenshot_path = 'uploads/payments/' . $new_name;
            }
        }
    }

    $stmt = $pdo->prepare("INSERT INTO wallet_requests (user_id, amount, utr_number, screenshot_path, status) VALUES (?, ?, ?, ?, 'pending')");
    if ($stmt->execute([$user_id, $amount, $utr, $screenshot_path])) {
        $msg = "<div class='alert alert-success border-0 rounded-4 shadow-sm animate-fade-in p-4'><i class='fas fa-check-circle me-2 fs-4'></i> Request submitted successfully! Please wait for admin approval (usually within 15 mins).</div>";
    } else {
        $msg = "<div class='alert alert-danger border-0 rounded-4'>Failed to submit request. Please contact support.</div>";
    }
}

$requests = $pdo->prepare("SELECT * FROM wallet_requests WHERE user_id = ? ORDER BY request_date DESC");
$requests->execute([$user_id]);
$all_requests = $requests->fetchAll();

$settings = getSettings($pdo);
include '../includes/header.php';
?>

<div class="row animate-fade-in">
    <div class="col-md-4">
        <div class="glass-card p-4 mb-4">
            <div class="d-flex align-items-center mb-4">
                <div class="bg-primary bg-opacity-10 p-3 rounded-4 me-3">
                    <i class="fas fa-plus-circle text-primary fa-xl"></i>
                </div>
                <div>
                    <h5 class="fw-bold mb-0">Load Wallet</h5>
                    <p class="text-muted small mb-0">Add funds via UPI</p>
                </div>
            </div>

            <?php echo $msg; ?>

            <?php 
            $recharge_hash = md5($user_id . 'RECHARGE_SALT'); // Simple salt for internal validation
            ?>
            <form action="process_payment.php" method="POST">
                <input type="hidden" name="hash" value="<?php echo $recharge_hash; ?>">
                <div class="mb-4">
                    <label class="form-label fw-semibold small">Amount to Recharge (₹)</label>
                    <div class="input-group">
                        <span class="input-group-text border-end-0 bg-light text-muted fw-bold">₹</span>
                        <input type="number" name="amount" class="form-control border-start-0 fw-bold bg-light" placeholder="Min. ₹10" required min="10" step="1">
                    </div>
                </div>
                
                <div class="bg-light p-3 rounded-4 mb-4">
                    <small class="text-muted d-block mb-1"><i class="fas fa-info-circle me-1"></i> Quick Amounts</small>
                    <div class="d-flex gap-2">
                        <button type="button" onclick="this.form.amount.value=100" class="btn btn-sm btn-white border rounded-pill px-3 fw-semibold">₹100</button>
                        <button type="button" onclick="this.form.amount.value=500" class="btn btn-sm btn-white border rounded-pill px-3 fw-semibold">₹500</button>
                        <button type="button" onclick="this.form.amount.value=1000" class="btn btn-sm btn-white border rounded-pill px-3 fw-semibold">₹1000</button>
                    </div>
                </div>

                <button type="submit" class="btn btn-premium w-100 py-3 shadow">
                    Generate Payment QR <i class="fas fa-arrow-right ms-2"></i>
                </button>
            </form>
        </div>

        <div class="glass-card p-4 bg-warning bg-opacity-10 border-warning border-opacity-25">
             <h6 class="fw-bold mb-3 text-warning-emphasis"><i class="fas fa-shield-halved me-2"></i> Payment Security</h6>
             <ul class="list-unstyled small text-warning-emphasis mb-0">
                 <li class="mb-2"><i class="fas fa-check-circle me-2 opacity-50"></i> Scan the dynamic QR only</li>
                 <li class="mb-2"><i class="fas fa-check-circle me-2 opacity-50"></i> Take a screenshot after paying</li>
                 <li><i class="fas fa-check-circle me-2 opacity-50"></i> Do not refresh the payment page</li>
             </ul>
        </div>
    </div>

    <div class="col-md-8">
        <div class="glass-card overflow-hidden">
            <div class="p-4 bg-white border-bottom d-flex justify-content-between align-items-center">
                <h5 class="fw-bold mb-0">Transaction History</h5>
                <span class="badge bg-light text-dark rounded-pill px-3">Recent 10</span>
            </div>
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="bg-light">
                        <tr>
                            <th class="px-4 py-3 border-0 small text-uppercase text-muted fw-bold">Date & Time</th>
                            <th class="px-4 py-3 border-0 small text-uppercase text-muted fw-bold">Amount</th>
                            <th class="px-4 py-3 border-0 small text-uppercase text-muted fw-bold text-center">Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($all_requests)): ?>
                            <tr>
                                <td colspan="3" class="text-center py-5">
                                    <i class="fas fa-history fa-3x text-light mb-3"></i>
                                    <p class="text-muted">No transactions found.</p>
                                </td>
                            </tr>
                        <?php endif; ?>
                        <?php foreach ($all_requests as $r): ?>
                        <tr>
                            <td class="px-4 py-3">
                                <div class="fw-semibold text-dark"><?php echo date('d M, Y', strtotime($r['request_date'])); ?></div>
                                <div class="small text-muted"><?php echo date('h:i A', strtotime($r['request_date'])); ?></div>
                            </td>
                            <td class="px-4 py-3">
                                <span class="fw-bold text-dark">₹<?php echo number_format($r['amount'], 2); ?></span>
                            </td>
                            <td class="px-4 py-3 text-center">
                                <?php if($r['status'] === 'approved'): ?>
                                    <span class="badge bg-success-subtle text-success border border-success border-opacity-25 rounded-pill px-3 py-2">
                                        <i class="fas fa-check-circle me-1"></i> Success
                                    </span>
                                <?php elseif($r['status'] === 'pending'): ?>
                                    <span class="badge bg-warning-subtle text-warning border border-warning border-opacity-25 rounded-pill px-3 py-2">
                                        <i class="fas fa-clock me-1"></i> Pending
                                    </span>
                                <?php else: ?>
                                    <span class="badge bg-danger-subtle text-danger border border-danger border-opacity-25 rounded-pill px-3 py-2">
                                        <i class="fas fa-times-circle me-1"></i> Failed
                                    </span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php include '../includes/footer.php'; ?>

