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

use App\Controllers\PurchaseController;
use App\Services\PurchaseService;
use App\Repositories\CarRepository;

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

$controller = new PurchaseController();
$purchaseService = new PurchaseService();
$carRepo = new CarRepository();

$id = $_GET['id'] ?? 0;
$userId = $_SESSION['user_id'];

// Step 1: Try to reserve the car
$reservation = $controller->reserve($id, $userId);

if (!$reservation['success']) {
    $_SESSION['error'] = $reservation['message'];
    header('Location: car_detail.php?id=' . $id);
    exit;
}

$car = $carRepo->find($id);
// Fetch main image manually since find() doesn't JOIN images (standard repository pattern)
$stmt = db()->prepare("SELECT image_path FROM car_images WHERE car_id = ? AND is_main = 1");
$stmt->execute([$id]);
$mainImage = $stmt->fetch();
$car['image_path'] = $mainImage ? $mainImage['image_path'] : 'assets/images/placeholder-car.jpg';

$costs = $purchaseService->calculateFees($car['price']);

$success = false;
$error = '';
$transactionId = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $buyerData = [
        'name' => $_POST['buyer_name'] ?? '',
        'phone' => $_POST['buyer_phone'] ?? '',
        'email' => $_SESSION['user_email'] ?? '',
        'bank_id' => $_POST['bank_id'] ?? '',
        'personal_info' => $_POST['personal_info'] ?? '',
        'payment_method' => $_POST['payment_method'] ?? 'bank_transfer'
    ];
    
    $result = $controller->checkout($id, $userId, $buyerData);
    
    if ($result['success']) {
        $success = true;
        $transactionId = $result['transaction_id'];
    } else {
        $error = $result['message'];
    }
}
?>

<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 Initiated!</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 secure transaction <strong class="text-gold"><?= htmlspecialchars($transactionId) ?></strong> has been created.
                The car is reserved for you. Please proceed with payment verification.
            </p>
            <div class="flex justify-center gap-1 mt-3">
                <a href="receipt.php?tx=<?= $transactionId ?>" class="btn btn-primary btn-lg">View Invoice</a>
                <a href="dashboard.php" class="btn btn-outline btn-lg">Go to Dashboard</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;">Enterprise Checkout</h3>
                <div class="mb-2" style="width: 100%; height: 220px; background-image: url('<?= htmlspecialchars($car['image_path']) ?>'); 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="mt-2 pt-2" style="border-top: 1px solid var(--glass-border);">
                    <div class="flex justify-between mb-1">
                        <span class="text-secondary">Car Price</span>
                        <span class="text-white fw-bold">$<?= number_format($costs['base_price'], 2) ?></span>
                    </div>
                    <div class="flex justify-between mb-1">
                        <span class="text-secondary">Marketplace Fee (<?= $purchaseService->calculateFees($car['price'])['fee'] / $car['price'] * 100 ?>%)</span>
                        <span class="text-white fw-bold">$<?= number_format($costs['fee'], 2) ?></span>
                    </div>
                    <div class="flex justify-between mb-1">
                        <span class="text-secondary">Tax (<?= $purchaseService->calculateFees($car['price'])['tax'] / $car['price'] * 100 ?>%)</span>
                        <span class="text-white fw-bold">$<?= number_format($costs['tax'], 2) ?></span>
                    </div>
                    <div class="flex justify-between align-center mt-1 pt-1" style="border-top: 2px dashed var(--glass-border);">
                        <span class="text-gold fw-black" style="text-transform: uppercase; font-size: 0.85rem;">Total Payable</span>
                        <span class="price-tag" style="font-size: 1.8rem;">$<?= number_format($costs['total'], 2) ?></span>
                    </div>
                </div>

                <div class="mt-2 p-1 text-center" style="background: rgba(255,0,0,0.1); border-radius: 10px;">
                    <p class="text-sm text-white m-0">Reservation expires in: <span id="timer">15:00</span></p>
                </div>
            </div>

            <div class="glass" style="padding: 4.5rem;">
                <div class="flex align-center gap-1 mb-2">
                    <span class="badge badge-primary">ESCROW PROTECTION ACTIVE</span>
                    <span class="text-secondary text-sm">Transaction ID: Securely Generated</span>
                </div>
                <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>Payment Method</label>
                        <select name="payment_method" class="form-control" required>
                            <option value="bank_transfer">Bank Transfer (Escrow Mode)</option>
                            <option value="card">Credit/Debit Card</option>
                            <option value="wallet">Digital Wallet</option>
                        </select>
                    </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;">ENTERPRISE ESCROW SYSTEM:</strong> 
                            Your payment will be held securely in Escrow. Funds are only released to the seller once you confirm receipt of the vehicle and the admin verifies all documentation.
                        </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;">SECURE CHECKOUT & PAY</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>

<script>
let timeLeft = 15 * 60;
const timerElement = document.getElementById('timer');
const countdown = setInterval(() => {
    if (timeLeft <= 0) {
        clearInterval(countdown);
        alert('Reservation expired. Please refresh the page to try again.');
        window.location.reload();
    } else {
        const minutes = Math.floor(timeLeft / 60);
        const seconds = timeLeft % 60;
        timerElement.innerText = `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
        timeLeft--;
    }
}, 1000);
</script>

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