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

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$pdo = db();
$id = $_GET['id'] ?? 0;

$stmt = $pdo->prepare("SELECT c.*, ci.image_path FROM cars c LEFT JOIN car_images ci ON c.id = ci.car_id AND ci.is_main = 1 WHERE c.id = ? AND c.status = 'approved'");
$stmt->execute([$id]);
$car = $stmt->fetch();

if (!$car) {
    header('Location: cars.php');
    exit;
}

$success = false;
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['buyer_name'] ?? '';
    $phone = $_POST['buyer_phone'] ?? '';
    $bank_id = $_POST['bank_id'] ?? '';
    $personal_info = $_POST['personal_info'] ?? '';
    $email = $_SESSION['user_email'] ?? '';
    
    $stmt = $pdo->prepare("INSERT INTO purchases (car_id, user_id, buyer_name, buyer_email, buyer_phone, bank_id, personal_info, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')");
    if ($stmt->execute([$id, $_SESSION['user_id'], $name, $email, $phone, $bank_id, $personal_info])) {
        $success = true;
    } else {
        $error = "Failed to submit request. Please try again.";
    }
}
?>

<div class="container" style="max-width: 1200px; padding: 4rem 0;">
    <?php if ($success): ?>
        <div class="box text-center" style="padding: 6rem;">
            <div style="font-size: 6rem; margin-bottom: 2.5rem; filter: drop-shadow(0 10px 20px rgba(0,0,0,0.3));">🚀</div>
            <h1 class="text-gold fw-black mb-1" style="font-size: 3.5rem;">Purchase Request Sent!</h1>
            <p class="text-secondary mb-3" style="font-size: 1.3rem; max-width: 750px; margin-left: auto; margin-right: auto; line-height: 1.8; font-weight: 600;">
                Your verification request for the <strong class="text-gold"><?= htmlspecialchars($car['brand'] . ' ' . $car['model']) ?></strong> with Bank Reference <strong class="text-gold"><?= htmlspecialchars($bank_id) ?></strong> has been successfully submitted to our verification team.
            </p>
            <div class="flex justify-center gap-1 mt-3">
                <a href="dashboard.php" class="btn btn-primary btn-lg">View Request Status</a>
                <a href="cars.php" class="btn btn-outline btn-lg">Back to Marketplace</a>
            </div>
        </div>
    <?php else: ?>
        <div class="grid" style="grid-template-columns: 1fr 1.6fr; gap: 4rem; align-items: start;">
            <div class="glass" style="padding: 2.5rem; position: sticky; top: 120px; border-top: 5px solid var(--primary-color);">
                <h3 class="fw-black mb-2 text-gold" style="text-transform: uppercase; letter-spacing: 2px; font-size: 1rem;">Transaction Summary</h3>
                <div class="mb-2" style="width: 100%; height: 220px; background-image: url('<?= htmlspecialchars($car['image_path'] ?: 'assets/images/placeholder-car.jpg') ?>'); background-size: cover; background-position: center; border-radius: 20px; border: 1px solid var(--glass-border);"></div>
                <h2 class="fw-black mb-1" style="font-size: 1.8rem; color: #fff;"><?= htmlspecialchars($car['brand'] . ' ' . $car['model']) ?></h2>
                <p class="text-secondary mb-2 fw-bold" style="font-size: 1.1rem;"><?= $car['year'] ?> Model • <?= $car['city'] ?></p>
                <div class="flex justify-between align-center mt-2 pt-2" style="border-top: 1px solid var(--glass-border);">
                    <span class="text-secondary fw-black" style="text-transform: uppercase; font-size: 0.85rem;">Total Amount Due</span>
                    <span class="price-tag" style="font-size: 1.8rem;">$<?= number_format($car['price']) ?></span>
                </div>
            </div>

            <div class="glass" style="padding: 4.5rem;">
                <h1 class="fw-black mb-1" style="font-size: 3rem; color: #fff;">Buyer Verification</h1>
                <p class="text-secondary mb-3" style="font-size: 1.15rem; font-weight: 500;">Provide your legal documentation and banking details to proceed with this secure purchase.</p>
                
                <?php if ($error): ?>
                    <div class="alert alert-error mb-2"><?= $error ?></div>
                <?php endif; ?>

                <form method="POST">
                    <div class="grid grid-2">
                        <div class="form-group">
                            <label>Full Legal Name (as on ID Card)</label>
                            <input type="text" name="buyer_name" class="form-control" value="<?= htmlspecialchars($_SESSION['user_name']) ?>" required placeholder="Enter your full name">
                        </div>
                        <div class="form-group">
                            <label>Phone Number</label>
                            <input type="text" name="buyer_phone" class="form-control" required placeholder="+93 7xx xxx xxx">
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Bank Reference ID / Account Number</label>
                        <input type="text" name="bank_id" class="form-control" required placeholder="Azizi Bank / Kabul Bank Transaction ID">
                        <p class="text-sm text-secondary mt-1 fw-bold">This reference will be verified with the Afghan banking systems.</p>
                    </div>

                    <div class="form-group">
                        <label>Legal Identification & Address</label>
                        <textarea name="personal_info" class="form-control" rows="4" required placeholder="Enter Tazkira/Passport number and current residential address for official sale documentation..."></textarea>
                    </div>
                    
                    <div class="mt-3 mb-3" style="padding: 2.5rem; background: rgba(212, 175, 55, 0.05); border-left: 5px solid var(--primary-color); border-radius: 20px;">
                        <p class="text-secondary text-sm" style="line-height: 1.8; margin: 0; font-weight: 600;">
                            <strong class="text-gold" style="font-size: 1.1rem; display: block; margin-bottom: 0.5rem;">IMPORTANT SECURITY NOTICE:</strong> 
                            Your personal data is encrypted. Submission of fraudulent bank IDs will result in account suspension and legal action under Afghanistan's automotive marketplace regulations.
                        </p>
                    </div>

                    <div class="flex align-center gap-1 mt-3">
                        <button type="submit" class="btn btn-primary btn-lg" style="flex: 2; font-weight: 900; letter-spacing: 1px;">SUBMIT SECURE PURCHASE REQUEST</button>
                        <a href="car_detail.php?id=<?= $id ?>" class="btn btn-outline btn-lg" style="flex: 1; font-weight: 700;">CANCEL</a>
                    </div>
                </form>
            </div>
        </div>
    <?php endif; ?>
</div>

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