<?php
require_once __DIR__ . '/includes/header.php';

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header('Location: index.php');
    exit;
}

$pdo = db();
$message = '';

if (isset($_POST['action']) && isset($_POST['purchase_id'])) {
    $purchase_id = $_POST['purchase_id'];
    $action = $_POST['action'];
    $status = ($action === 'approve') ? 'approved' : 'rejected';
    
    try {
        $pdo->beginTransaction();
        
        // Update purchase status
        $stmt = $pdo->prepare("UPDATE purchases SET status = ? WHERE id = ?");
        $stmt->execute([$status, $purchase_id]);
        
        if ($status === 'approved') {
            // Get car ID
            $stmt = $pdo->prepare("SELECT car_id FROM purchases WHERE id = ?");
            $stmt->execute([$purchase_id]);
            $car_id = $stmt->fetchColumn();
            
            // Mark car as sold
            $stmt = $pdo->prepare("UPDATE cars SET status = 'sold' WHERE id = ?");
            $stmt->execute([$car_id]);
        }
        
        $pdo->commit();
        $message = "Purchase request " . ($status === 'approved' ? 'approved' : 'rejected') . " successfully.";
    } catch (Exception $e) {
        $pdo->rollBack();
        $message = "Error: " . $e->getMessage();
    }
}

// Fetch all purchases with car and user info
$stmt = $pdo->query("
    SELECT p.*, c.brand, c.model, c.price, c.year, u.name as buyer_user_name, ci.image_path
    FROM purchases p
    JOIN cars c ON p.car_id = c.id
    JOIN users u ON p.user_id = u.id
    LEFT JOIN car_images ci ON c.id = ci.car_id AND ci.is_main = 1
    ORDER BY p.created_at DESC
");
$purchases = $stmt->fetchAll();
?>

<div class="container-fluid" style="padding: 2rem 4rem;">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 3rem;">
        <div>
            <h1 style="font-size: 2.5rem; font-weight: 900; margin-bottom: 0.5rem;">Purchase Requests</h1>
            <p style="color: var(--text-secondary);">Review and manage buyer bank verification requests.</p>
        </div>
        <a href="admin_dashboard.php" class="btn btn-outline">Back to Dashboard</a>
    </div>

    <?php if ($message): ?>
        <div class="glass" style="padding: 1rem; margin-bottom: 2rem; border-color: var(--primary-color); color: var(--primary-color); font-weight: 600;">
            <?= $message ?>
        </div>
    <?php endif; ?>

    <div class="glass" style="overflow-x: auto; padding: 0;">
        <table style="width: 100%; border-collapse: collapse; text-align: left;">
            <thead>
                <tr style="background: rgba(0,0,0,0.05);">
                    <th style="padding: 1.5rem;">Vehicle</th>
                    <th style="padding: 1.5rem;">Buyer Details</th>
                    <th style="padding: 1.5rem;">Bank ID</th>
                    <th style="padding: 1.5rem;">Price</th>
                    <th style="padding: 1.5rem;">Status</th>
                    <th style="padding: 1.5rem;">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($purchases as $p): ?>
                <tr style="border-bottom: 1px solid var(--glass-border);">
                    <td style="padding: 1.5rem;">
                        <div style="display: flex; align-items: center; gap: 1rem;">
                            <img src="<?= htmlspecialchars($p['image_path'] ?: 'assets/images/placeholder-car.jpg') ?>" style="width: 80px; height: 50px; object-fit: cover; border-radius: 8px;">
                            <div>
                                <div style="font-weight: 700;"><?= htmlspecialchars($p['brand'] . ' ' . $p['model']) ?></div>
                                <div style="font-size: 0.8rem; color: var(--text-secondary);"><?= $p['year'] ?></div>
                            </div>
                        </div>
                    </td>
                    <td style="padding: 1.5rem;">
                        <div style="font-weight: 600;"><?= htmlspecialchars($p['buyer_name']) ?></div>
                        <div style="font-size: 0.85rem; color: var(--text-secondary);"><?= htmlspecialchars($p['buyer_phone']) ?></div>
                        <div style="font-size: 0.75rem; color: var(--text-secondary); max-width: 200px;"><?= htmlspecialchars($p['personal_info']) ?></div>
                    </td>
                    <td style="padding: 1.5rem;">
                        <code style="background: rgba(0,0,0,0.1); padding: 0.3rem 0.6rem; border-radius: 4px;"><?= htmlspecialchars($p['bank_id']) ?></code>
                    </td>
                    <td style="padding: 1.5rem; font-weight: 700; color: var(--primary-color);">$<?= number_format($p['price']) ?></td>
                    <td style="padding: 1.5rem;">
                        <span class="badge" style="background: <?= $p['status'] === 'approved' ? 'var(--success)' : ($p['status'] === 'rejected' ? 'var(--danger)' : 'var(--primary-color)') ?>; color: white; padding: 0.3rem 0.8rem; border-radius: 20px; font-size: 0.75rem; text-transform: uppercase;">
                            <?= $p['status'] ?>
                        </span>
                    </td>
                    <td style="padding: 1.5rem;">
                        <?php if ($p['status'] === 'pending'): ?>
                        <div style="display: flex; gap: 0.5rem;">
                            <form method="POST" style="display: inline;">
                                <input type="hidden" name="purchase_id" value="<?= $p['id'] ?>">
                                <button type="submit" name="action" value="approve" class="btn btn-primary" style="padding: 0.5rem 1rem; font-size: 0.8rem;">Approve</button>
                            </form>
                            <form method="POST" style="display: inline;">
                                <input type="hidden" name="purchase_id" value="<?= $p['id'] ?>">
                                <button type="submit" name="action" value="reject" class="btn btn-outline" style="padding: 0.5rem 1rem; font-size: 0.8rem; border-color: var(--danger); color: var(--danger);">Reject</button>
                            </form>
                        </div>
                        <?php else: ?>
                            <span style="color: var(--text-secondary); font-size: 0.85rem;">Completed</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($purchases)): ?>
                <tr>
                    <td colspan="6" style="padding: 4rem; text-align: center; color: var(--text-secondary);">No purchase requests found.</td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>