<?php
session_start();
require_once __DIR__ . '/db/config.php';

if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header('Location: login.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();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Purchase Requests | Admin</title>
    <link rel="stylesheet" href="assets/css/fonts.css">
    <link rel="stylesheet" href="assets/css/style.css?v=<?= time() ?>">
</head>
<body>
    <div class="dashboard-container">
        <!-- Sidebar -->
        <aside class="sidebar">
            <a href="index.php" class="sidebar-brand">AFGCARS</a>
            <ul class="sidebar-menu">
                <li><a href="admin_dashboard.php"><span>Dashboard</span></a></li>
                <li><a href="admin_cars.php"><span>Manage Cars</span></a></li>
                <li><a href="admin_purchases.php" class="active"><span>Purchase Requests</span></a></li>
                <li><a href="admin_users.php"><span>Users</span></a></li>
                <li><a href="admin_messages.php"><span>Messages</span></a></li>
            </ul>
            <div class="sidebar-footer">
                <a href="logout.php" class="btn btn-danger btn-sm" style="width: 100%;">Logout</a>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="main-content">
            <header class="mb-3">
                <h1 class="fw-bold" style="font-size: 2.5rem;">Purchase Requests</h1>
                <p class="text-secondary">Verify bank IDs and personal information to approve or reject vehicle transactions.</p>
            </header>

            <?php if ($message): ?>
                <div class="alert alert-success">
                    <span class="text-gold">✓</span> <?= $message ?>
                </div>
            <?php endif; ?>

            <div class="glass" style="padding: 2.5rem;">
                <div class="table-container">
                    <table>
                        <thead>
                            <tr>
                                <th>Vehicle Details</th>
                                <th>Buyer Verification</th>
                                <th>Bank Reference</th>
                                <th>Transaction Amount</th>
                                <th>Current Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($purchases as $p): ?>
                            <tr>
                                <td>
                                    <div style="display: flex; align-items: center; gap: 1.2rem;">
                                        <img src="<?= htmlspecialchars($p['image_path'] ?: 'assets/images/placeholder-car.jpg') ?>" style="width: 90px; height: 60px; object-fit: cover; border-radius: 10px; border: 1px solid var(--glass-border);">
                                        <div>
                                            <div class="fw-bold"><?= htmlspecialchars($p['brand'] . ' ' . $p['model']) ?></div>
                                            <div class="text-sm text-secondary"><?= $p['year'] ?></div>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <div class="fw-bold text-sm"><?= htmlspecialchars($p['buyer_name']) ?></div>
                                    <div class="text-sm text-secondary"><?= htmlspecialchars($p['buyer_phone']) ?></div>
                                    <div class="text-sm text-secondary" style="max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"><?= htmlspecialchars($p['personal_info']) ?></div>
                                </td>
                                <td>
                                    <code style="background: rgba(255, 255, 255, 0.05); padding: 0.4rem 0.8rem; border-radius: 8px; border: 1px solid rgba(255,255,255,0.1); color: var(--primary-color); font-weight: 700; font-family: monospace;"><?= htmlspecialchars($p['bank_id']) ?></code>
                                </td>
                                <td>
                                    <div class="text-gold fw-bold">$<?= number_format($p['price']) ?></div>
                                </td>
                                <td>
                                    <span class="badge badge-<?= $p['status'] === 'approved' ? 'success' : ($p['status'] === 'rejected' ? 'danger' : 'warning') ?>">
                                        <?= ucfirst($p['status']) ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if ($p['status'] === 'pending'): ?>
                                    <div style="display: flex; gap: 1rem; align-items: center;">
                                        <form method="POST" style="display: inline;">
                                            <input type="hidden" name="purchase_id" value="<?= $p['id'] ?>">
                                            <button type="submit" name="action" value="approve" class="text-gold text-sm fw-bold btn-sm" style="background: none; border: none; cursor: pointer; padding: 0;">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="text-sm fw-bold btn-sm" style="background: none; border: none; cursor: pointer; padding: 0; color: var(--danger);">Reject</button>
                                        </form>
                                    </div>
                                    <?php else: ?>
                                        <span class="text-secondary text-sm fw-bold">Verified</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if (empty($purchases)): ?>
                            <tr>
                                <td colspan="6" style="padding: 4rem; text-align: center;">
                                    <p class="text-secondary">No purchase requests waiting for verification.</p>
                                </td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </main>
    </div>
</body>
</html>