<?php
/**
 * Process Booking - UPDATED WITH WALLET PAYMENT
 * File: process-booking.php (ROOT DIRECTORY)
 */

require_once 'app/Core/init.php';

// Must be logged in as customer
if (!Auth::check() || Auth::userType() !== 'customer') {
    flash('error', 'Please login as a customer to book items', 'danger');
    redirect('auth/login.php');
}

// Check if this is a form submission or page refresh
$is_post_request = $_SERVER['REQUEST_METHOD'] === 'POST';
$has_pending_booking = isset($_SESSION['pending_booking']);

// If no POST data and no pending booking, redirect
if (!$is_post_request && !$has_pending_booking) {
    redirect('items.php');
}

// Process new booking from POST
if ($is_post_request) {
    // Validate CSRF token
    if (!Security::validateToken($_POST['csrf_token'] ?? '')) {
        flash('error', 'Invalid request. Please try again.', 'danger');
        redirect('items.php');
    }
    
    // Get form data
    $item_id = isset($_POST['item_id']) ? (int)$_POST['item_id'] : 0;
    $start_date = $_POST['start_date'] ?? '';
    $end_date = $_POST['end_date'] ?? '';
    $quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 0;
    
    if (!$item_id || !$start_date || !$end_date || !$quantity) {
        flash('error', 'Please fill all required fields', 'danger');
        redirect("item-details.php?id={$item_id}");
    }
    
    try {
        $db = Database::getInstance();
        
        // Get item details
        $itemModel = new Item();
        $item = $itemModel->findById($item_id);
        
        if (!$item || $item['status'] !== 'approved' || $item['approval_status'] !== 'approved') {
            flash('error', 'Item not found or not available', 'danger');
            redirect('items.php');
        }
        
        // Validate dates
        $start = new DateTime($start_date);
        $end = new DateTime($end_date);
        $today = new DateTime();
        $today->setTime(0, 0, 0);
        
        if ($start < $today) {
            flash('error', 'Start date cannot be in the past', 'danger');
            redirect("item-details.php?slug={$item['slug']}");
        }
        
        if ($end < $start) {
            flash('error', 'End date must be on or after start date', 'danger');
            redirect("item-details.php?slug={$item['slug']}");
        }
        
        // Calculate number of days (inclusive)
        $interval = $start->diff($end);
        $numberOfDays = $interval->days + 1;
        
        // Calculate amounts
        $dailyRate = $item['price_per_day'];
        $securityDeposit = $item['security_deposit'];
        
        $subtotal = $quantity * $numberOfDays * $dailyRate;
        $totalDeposit = $quantity * $securityDeposit;
        $grandTotal = $subtotal + $totalDeposit;
        
        // Get customer info
        $customerModel = new Customer();
        $customer = $customerModel->findByUserId(Auth::id());
        
        if (!$customer) {
            flash('error', 'Customer profile not found', 'danger');
            redirect("item-details.php?slug={$item['slug']}");
        }
        
        // Get customer wallet balance
        $walletModel = new Wallet();
        $wallet = $walletModel->findByUserId(Auth::id());
        $wallet_balance = $wallet ? floatval($wallet['balance']) : 0;
        $has_sufficient_balance = ($wallet_balance >= $grandTotal);
        
        // Generate order reference
        $orderReference = 'ORD-' . strtoupper(uniqid()) . '-' . time();
        
        // Store booking data in session
        $_SESSION['pending_booking'] = [
            'item_id' => $item_id,
            'item_slug' => $item['slug'],
            'item_title' => $item['title'],
            'customer_id' => $customer['id'],
            'vendor_id' => $item['vendor_id'],
            'start_date' => $start_date,
            'end_date' => $end_date,
            'quantity' => $quantity,
            'number_of_days' => $numberOfDays,
            'daily_rate' => $dailyRate,
            'subtotal' => $subtotal,
            'security_deposit' => $totalDeposit,
            'total_amount' => $grandTotal,
            'order_reference' => $orderReference,
            'wallet_balance' => $wallet_balance,
            'has_sufficient_balance' => $has_sufficient_balance
        ];
        
        // Get payment gateway settings using Factory
        $gatewayFactory = PaymentGatewayFactory::getInstance();
        $gatewayName = $gatewayFactory->getDefaultGatewayName();
        $gatewayConfig = $gatewayFactory->getGatewayConfig($gatewayName);
        
        // Create initial payment record in online_payments table
        $onlinePaymentModel = new OnlinePayment();
        $onlinePaymentModel->create([
            'customer_id' => $customer['id'],
            'transaction_reference' => $orderReference,
            'payment_gateway' => $gatewayName,
            'amount' => $grandTotal,
            'payment_type' => 'order_payment',
            'currency' => 'NGN',
            'customer_email' => Auth::user()['email'],
            'status' => 'pending',
            'metadata' => json_encode([
                'item_id' => $item_id,
                'item_title' => $item['title'],
                'customer_id' => $customer['id']
            ])
        ]);
        
    } catch (Exception $e) {
        error_log("Booking process error: " . $e->getMessage());
        flash('error', 'Error processing booking. Please try again.', 'danger');
        redirect("item-details.php?slug={$item['slug']}");
    }
}

// If we reach here, we have pending booking in session (either just created or from page refresh)
$booking = $_SESSION['pending_booking'];

// Get payment gateway config
$gatewayFactory = PaymentGatewayFactory::getInstance();
$gatewayName = $gatewayFactory->getDefaultGatewayName();
$gatewayConfig = $gatewayFactory->getGatewayConfig($gatewayName);

$page_title = 'Complete Booking - ' . APP_NAME;
?>
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $page_title ?></title>
    <link href="<?= APP_URL ?>/assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="<?= APP_URL ?>/assets/plugins/fontawesome/css/all.min.css" rel="stylesheet">
    <link href="<?= APP_URL ?>/assets/css/style.css" rel="stylesheet">
</head>
<body>
    <div class="container py-5">
        <div class="row justify-content-center">
            <div class="col-md-8 col-lg-6">
                <div class="card border-0 shadow-lg rounded-4">
                    <div class="card-body p-5">
                        <div class="text-center mb-4">
                            <div class="bg-primary bg-opacity-10 rounded-circle d-inline-flex p-3 mb-3">
                                <i class="fas fa-calendar-check fa-3x text-primary"></i>
                            </div>
                            <h2 class="mb-2">Complete Your Booking</h2>
                            <p class="text-muted">Review and pay for your booking</p>
                        </div>
                        
                        <!-- Booking Summary -->
                        <div class="bg-light rounded-3 p-4 mb-4">
                            <h5 class="mb-3">Booking Summary</h5>
                            
                            <div class="d-flex justify-content-between mb-2">
                                <strong>Item:</strong>
                                <span><?= htmlspecialchars($booking['item_title']) ?></span>
                            </div>
                            
                            <div class="d-flex justify-content-between mb-2">
                                <strong>Dates:</strong>
                                <span><?= date('M j, Y', strtotime($booking['start_date'])) ?> - <?= date('M j, Y', strtotime($booking['end_date'])) ?></span>
                            </div>
                            
                            <div class="d-flex justify-content-between mb-2">
                                <strong>Duration:</strong>
                                <span><?= $booking['number_of_days'] ?> day<?= $booking['number_of_days'] > 1 ? 's' : '' ?></span>
                            </div>
                            
                            <div class="d-flex justify-content-between mb-2">
                                <strong>Quantity:</strong>
                                <span><?= $booking['quantity'] ?> item<?= $booking['quantity'] > 1 ? 's' : '' ?></span>
                            </div>
                            
                            <hr>
                            
                            <div class="small mb-3">
                                <div class="text-muted mb-1">Calculation:</div>
                                <div><?= $booking['quantity'] ?> items × <?= $booking['number_of_days'] ?> days × ₦<?= number_format($booking['daily_rate'], 2) ?> = <strong>₦<?= number_format($booking['subtotal'], 2) ?></strong></div>
                                <div class="mt-1">Security Deposit: <?= $booking['quantity'] ?> × ₦<?= number_format($booking['security_deposit'] / $booking['quantity'], 2) ?> = <strong>₦<?= number_format($booking['security_deposit'], 2) ?></strong></div>
                            </div>
                            
                            <hr>
                            
                            <div class="d-flex justify-content-between fs-5 fw-bold text-success">
                                <span>Total Amount:</span>
                                <span>₦<?= number_format($booking['total_amount'], 2) ?></span>
                            </div>
                            
                            <div class="alert alert-info mt-3 mb-0 small">
                                <i class="fas fa-info-circle"></i> Security deposit will be refunded after you return the item in good condition
                            </div>
                            <br>

                            <!-- Cancellation Penalty Warning -->
                            <div class="alert alert-danger border-danger mb-3">
                                <h6 class="mb-2"><i class="fas fa-exclamation-triangle"></i> <strong>Cancellation Policy</strong></h6>
                                <p class="mb-1 small">Please ensure you need this item before booking. Cancellation attracts penalties</p>
                                <small>Penalties apply to rental amount only, not security deposit.</small>
                            </div>
                            
                            <!-- Terms & Conditions Checkbox -->
                            <div class="form-check mb-3 p-3 bg-light rounded">
                                <input class="form-check-input" type="checkbox" id="agreeTerms" required>
                                <label class="form-check-label" for="agreeTerms">
                                    I agree to the 
                                    <a href="<?= APP_URL ?>/terms-and-conditions.php" target="_blank" class="text-primary">Terms & Conditions</a> 
                                    and 
                                    <a href="<?= APP_URL ?>/refund-policy.php" target="_blank" class="text-primary">Refund Policy</a>
                                    <span class="text-danger">*</span>
                                </label>
                            </div>


                        </div>
                        
                        <!-- Payment Buttons -->
                        <?php if ($booking['has_sufficient_balance']): ?>
                            <!-- Show both payment options -->
                            <div class="row g-2 mb-3">
                                <div class="col-md-6">
                                    <button type="button" 
                                            id="walletPaymentBtn" 
                                            class="btn btn-primary btn-lg w-100"
                                            onclick="payWithWallet()"
                                            disabled>
                                        <i class="fas fa-wallet me-2"></i>Pay from Wallet
                                        <div class="small mt-1">Balance: ₦<?= number_format($booking['wallet_balance'], 2) ?></div>
                                    </button>
                                </div>
                                <div class="col-md-6">
                                    <button type="button" 
                                            id="paystackPaymentBtn" 
                                            class="btn btn-success btn-lg w-100"
                                            onclick="initiatePayment()"
                                            disabled>
                                        <i class="fas fa-credit-card me-2"></i>Pay with <?= ucfirst($gatewayName) ?>
                                    </button>
                                </div>
                            </div>
                        <?php else: ?>
                            <!-- Show only Paystack -->
                            <button type="button" 
                                    id="paystackPaymentBtn" 
                                    class="btn btn-success btn-lg w-100 mb-3"
                                    onclick="initiatePayment()"
                                    disabled>
                                <i class="fas fa-lock me-2"></i>Pay with <?= ucfirst($gatewayName) ?>
                            </button>
                            
                            <?php if ($booking['wallet_balance'] > 0): ?>
                                <div class="alert alert-info small mb-3">
                                    <i class="fas fa-info-circle"></i> 
                                    Your wallet balance (₦<?= number_format($booking['wallet_balance'], 2) ?>) is insufficient. 
                                    Need ₦<?= number_format($booking['total_amount'] - $booking['wallet_balance'], 2) ?> more.
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>
                        
                        <div class="text-center">
                            <a href="<?= APP_URL ?>/item-details.php?slug=<?= $booking['item_slug'] ?>" class="btn btn-outline-secondary">
                                <i class="fas fa-arrow-left me-2"></i>Go Back
                            </a>
                        </div>
                        
                        <div class="text-center mt-3">
                            <small class="text-muted">
                                <i class="fas fa-shield-alt"></i> Secure payment powered by <?= ucfirst($gatewayName) ?>
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://js.paystack.co/v1/inline.js"></script>
    <script>
let paymentProcessing = false;

// Enable/disable payment buttons based on terms checkbox
document.getElementById('agreeTerms').addEventListener('change', function() {
    const isChecked = this.checked;
    
    <?php if ($booking['has_sufficient_balance']): ?>
        document.getElementById('walletPaymentBtn').disabled = !isChecked;
        document.getElementById('paystackPaymentBtn').disabled = !isChecked;
    <?php else: ?>
        document.getElementById('paystackPaymentBtn').disabled = !isChecked;
    <?php endif; ?>
});

// Pay with Wallet
function payWithWallet() {
    if (!document.getElementById('agreeTerms').checked) {
        alert('Please agree to Terms & Conditions and Refund Policy');
        return;
    }
    
    if (paymentProcessing) {
        alert('Payment is already processing. Please wait...');
        return;
    }
    
    if (!confirm('Confirm payment of ₦<?= number_format($booking['total_amount'], 2) ?> from your wallet?\n\nYour current balance: ₦<?= number_format($booking['wallet_balance'], 2) ?>\nAfter payment: ₦<?= number_format($booking['wallet_balance'] - $booking['total_amount'], 2) ?>')) {
        return;
    }
    
    paymentProcessing = true;
    
    const btn = document.getElementById('walletPaymentBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Processing...';
    
    // Disable other button
    <?php if ($booking['has_sufficient_balance']): ?>
        document.getElementById('paystackPaymentBtn').disabled = true;
    <?php endif; ?>
    
    // Submit wallet payment
    fetch('<?= APP_URL ?>/payment-wallet.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'reference=<?= $booking['order_reference'] ?>&amount=<?= $booking['total_amount'] ?>'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            btn.innerHTML = '<i class="fas fa-check-circle me-2"></i>Payment Successful! Redirecting...';
            setTimeout(() => {
                window.location.href = '<?= APP_URL ?>/booking-confirmation.php?order=' + data.order_number;
            }, 1000);
        } else {
            alert('Payment failed: ' + (data.error || 'Unknown error'));
            paymentProcessing = false;
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-wallet me-2"></i>Pay from Wallet';
            <?php if ($booking['has_sufficient_balance']): ?>
                document.getElementById('paystackPaymentBtn').disabled = false;
            <?php endif; ?>
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Payment request failed. Please try again.');
        paymentProcessing = false;
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-wallet me-2"></i>Pay from Wallet';
        <?php if ($booking['has_sufficient_balance']): ?>
            document.getElementById('paystackPaymentBtn').disabled = false;
        <?php endif; ?>
    });
}

// Pay with Paystack
function initiatePayment() {
    if (!document.getElementById('agreeTerms').checked) {
        alert('Please agree to Terms & Conditions and Refund Policy');
        return;
    }
    
    if (paymentProcessing) {
        alert('Payment is already processing. Please wait...');
        return;
    }
    
    paymentProcessing = true;
    
    const btn = document.getElementById('paystackPaymentBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Processing...';
    
    // Disable wallet button if exists
    <?php if ($booking['has_sufficient_balance']): ?>
        document.getElementById('walletPaymentBtn').disabled = true;
    <?php endif; ?>
    
    const handler = PaystackPop.setup({
        key: '<?= $gatewayConfig['public_key'] ?>',
        email: '<?= Auth::user()['email'] ?>',
        amount: <?= $booking['total_amount'] * 100 ?>,
        currency: 'NGN',
        ref: '<?= $booking['order_reference'] ?>',
        metadata: {
            custom_fields: [
                {
                    display_name: "Item",
                    variable_name: "item_name",
                    value: "<?= addslashes($booking['item_title']) ?>"
                },
                {
                    display_name: "Customer",
                    variable_name: "customer_name",
                    value: "<?= addslashes(Auth::user()['email']) ?>"
                }
            ]
        },
        callback: function(response) {
            btn.innerHTML = '<i class="fas fa-check-circle me-2"></i>Payment Successful! Redirecting...';
            window.location.href = '<?= APP_URL ?>/payment-callback.php?reference=' + response.reference + '&gateway=<?= $gatewayName ?>';
        },
        onClose: function() {
            paymentProcessing = false;
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-credit-card me-2"></i>Pay with <?= ucfirst($gatewayName) ?>';
            
            // Re-enable wallet button if exists and checkbox is still checked
            <?php if ($booking['has_sufficient_balance']): ?>
                if (document.getElementById('agreeTerms').checked) {
                    document.getElementById('walletPaymentBtn').disabled = false;
                }
            <?php endif; ?>
        }
    });
    
    handler.openIframe();
}
</script>
</body>
</html>