<?php
require_once(__DIR__ . '/../config/config.php');
require_once(__DIR__ . '/../classes/Database.php');
require_once(__DIR__ . '/../classes/Payment.php');

// Check if user is logged in
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}
$userId = $_SESSION['user_id'];

$db = Database::getInstance();
$payment = new Payment();

// Handle payment form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'initiate_payment') {
    $packageId = (int)$_POST['package_id'];
    $packages = $payment->getPaymentPackages();
    $selectedPackage = null;

    foreach ($packages as $pkg) {
        if ($pkg['id'] == $packageId) {
            $selectedPackage = $pkg;
            break;
        }
    }

    if ($selectedPackage) {
        $orderId = $payment->createPaymentOrder($userId, $selectedPackage['price'], $selectedPackage['name']);
        $_SESSION['payment_order_id'] = $orderId;
        $_SESSION['payment_amount'] = $selectedPackage['price'];
        header('Location: payment_gateway.php?order_id=' . $orderId);
        exit;
    }
}

$currentBalance = $payment->getBalance($userId);
$packages = $payment->getPaymentPackages();
$transactions = $payment->getTransactionHistory($userId, 10);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Buy Credits - <?php echo APP_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 40px 20px;
        }

        .container-main {
            max-width: 1000px;
            margin: 0 auto;
        }

        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            margin-bottom: 30px;
        }

        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px 15px 0 0;
            padding: 25px;
            border: none;
        }

        .card-header h3 {
            margin: 0;
            font-weight: 700;
        }

        .balance-display {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 15px;
            text-align: center;
            margin-bottom: 30px;
        }

        .balance-display h4 {
            margin: 0;
            font-size: 18px;
            opacity: 0.9;
        }

        .balance-display .amount {
            font-size: 48px;
            font-weight: 700;
            margin: 10px 0 0 0;
        }

        .package-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .package-card {
            background: white;
            border: 2px solid #e0e0e0;
            border-radius: 12px;
            padding: 25px;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .package-card:hover {
            border-color: #667eea;
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.15);
            transform: translateY(-5px);
        }

        .package-card.popular {
            border-color: #667eea;
            background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%);
        }

        .package-card .badge-popular {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            margin-bottom: 15px;
            display: inline-block;
        }

        .package-card h4 {
            font-weight: 700;
            color: #333;
            margin-bottom: 10px;
        }

        .package-card .credits {
            font-size: 24px;
            font-weight: 700;
            color: #667eea;
            margin-bottom: 10px;
        }

        .package-card .price {
            font-size: 32px;
            font-weight: 700;
            color: #333;
            margin: 15px 0;
        }

        .package-card .price small {
            font-size: 14px;
            color: #666;
        }

        .package-card .description {
            color: #666;
            font-size: 14px;
            margin: 15px 0;
        }

        .package-card .btn {
            width: 100%;
            padding: 10px;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .package-card .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .package-card .btn-primary:hover {
            background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
            color: white;
        }

        .transaction-table {
            margin-top: 20px;
        }

        .transaction-table thead {
            background: #f8f9fa;
        }

        .transaction-table td {
            vertical-align: middle;
            padding: 15px;
        }

        .badge-credit {
            background: #10b981;
            color: white;
        }

        .badge-debit {
            background: #ef4444;
            color: white;
        }

        @media (max-width: 768px) {
            .package-grid {
                grid-template-columns: 1fr;
            }

            .balance-display .amount {
                font-size: 36px;
            }
        }
    </style>
</head>
<body>
    <div class="container-main">
        <!-- Current Balance -->
        <div class="balance-display">
            <h4>💳 Your Current Balance</h4>
            <div class="amount">₹<?php echo number_format($currentBalance, 2); ?></div>
            <small>Available Credits for Searches</small>
        </div>

        <!-- Payment Packages -->
        <div class="card">
            <div class="card-header">
                <h3><i class="fas fa-shopping-cart"></i> Buy Credits</h3>
            </div>
            <div class="card-body p-4">
                <div class="package-grid">
                    <?php foreach ($packages as $pkg): ?>
                    <div class="package-card <?php echo $pkg['id'] === 3 ? 'popular' : ''; ?>">
                        <?php if ($pkg['id'] === 3): ?>
                        <div class="badge-popular">⭐ Most Popular</div>
                        <?php endif; ?>
                        
                        <h4><?php echo htmlspecialchars($pkg['name']); ?></h4>
                        <div class="credits"><?php echo $pkg['credits']; ?> Credits</div>
                        <div class="price">
                            ₹<?php echo number_format($pkg['price'], 0); ?>
                            <small>/package</small>
                        </div>
                        <p class="description"><?php echo htmlspecialchars($pkg['description']); ?></p>
                        
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="action" value="initiate_payment">
                            <input type="hidden" name="package_id" value="<?php echo $pkg['id']; ?>">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-arrow-right"></i> Buy Now
                            </button>
                        </form>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- Transaction History -->
        <div class="card">
            <div class="card-header">
                <h3><i class="fas fa-history"></i> Transaction History</h3>
            </div>
            <div class="card-body p-4">
                <?php if (count($transactions) > 0): ?>
                <table class="table table-hover transaction-table">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Type</th>
                            <th>Amount</th>
                            <th>Description</th>
                            <th>Balance</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($transactions as $txn): ?>
                        <tr>
                            <td><?php echo date('d M Y H:i', strtotime($txn['created_at'])); ?></td>
                            <td>
                                <span class="badge <?php echo $txn['type'] === 'credit' ? 'badge-credit' : 'badge-debit'; ?>">
                                    <?php echo ucfirst($txn['type']); ?>
                                </span>
                            </td>
                            <td>
                                <strong><?php echo $txn['type'] === 'credit' ? '+' : '-'; ?>₹<?php echo number_format($txn['amount'], 2); ?></strong>
                            </td>
                            <td><?php echo htmlspecialchars($txn['description']); ?></td>
                            <td>₹<?php echo number_format($txn['balance_after'], 2); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php else: ?>
                <p class="text-center text-muted py-4">No transactions yet</p>
                <?php endif; ?>
            </div>
        </div>

        <!-- Back Button -->
        <div class="text-center">
            <a href="dashboard.php" class="btn btn-outline-light btn-lg">
                <i class="fas fa-arrow-left"></i> Back to Dashboard
            </a>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
