<?php
require_once 'config.php';
require_once 'includes/cart.php';
require_once 'includes/order.php';
require_once 'includes/auth.php';

$pageTitle = 'Checkout';
$cart = new Cart();
$orderModel = new Order();
$auth = new Auth();

$cartItems = $cart->getItems();
$cartTotal = $cart->getTotal();

// Redirect if cart is empty
if (empty($cartItems)) {
    header('Location: cart.php');
    exit;
}

// Check if user is logged in
$isLoggedIn = isLoggedIn();
$user = null;
if ($isLoggedIn) {
    $user = $auth->getUser($_SESSION['user_id']);
}

// Handle checkout form submission
$error = '';
$success = false;
$orderNumber = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!$isLoggedIn) {
        $error = 'Please login to complete your order.';
    } else {
        $shippingAddress = sanitize($_POST['address'] . ', ' . $_POST['city'] . ', ' . $_POST['state'] . ' ' . $_POST['zip'] . ', ' . $_POST['country']);
        $paymentMethod = sanitize($_POST['payment_method']);
        $notes = sanitize($_POST['notes'] ?? '');
        
        if (empty($_POST['address']) || empty($_POST['city']) || empty($_POST['zip'])) {
            $error = 'Please fill in all required shipping details.';
        } else {
            $result = $orderModel->create(
                $_SESSION['user_id'],
                $cart->getOrderItems(),
                $shippingAddress,
                $paymentMethod,
                $notes
            );
            
            if ($result['success']) {
                $cart->clear();
                $success = true;
                $orderNumber = $result['order_number'];
            } else {
                $error = 'Failed to create order. Please try again.';
            }
        }
    }
}

require_once 'includes/header.php';
?>

<!-- Checkout Page -->
<section class="checkout-page">
    <div class="container">
        <?php if ($success): ?>
            <div class="order-success">
                <div class="order-success-icon">&#10003;</div>
                <h1>Order Confirmed!</h1>
                <p class="order-number">Order Number: <?php echo htmlspecialchars($orderNumber); ?></p>
                <p style="color: var(--medium-gray); margin-bottom: var(--spacing-xl);">
                    Thank you for your purchase! A confirmation email has been sent to your registered email address.
                </p>
                <a href="<?php echo SITE_URL; ?>/account.php" class="btn btn-primary">View Order</a>
                <a href="<?php echo SITE_URL; ?>/products.php" class="btn btn-secondary" style="margin-left: var(--spacing-md);">Continue Shopping</a>
            </div>
        <?php else: ?>
            <h1 class="section-title" style="margin-bottom: var(--spacing-xl);">Checkout</h1>
            
            <?php if ($error): ?>
                <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>
            
            <?php if (!$isLoggedIn): ?>
                <div class="alert alert-warning">
                    Please <a href="<?php echo SITE_URL; ?>/login.php?redirect=checkout.php">login</a> or <a href="<?php echo SITE_URL; ?>/register.php?redirect=checkout.php">register</a> to complete your purchase.
                </div>
            <?php endif; ?>
            
            <div class="checkout-grid">
                <!-- Checkout Form -->
                <div class="checkout-form">
                    <form method="POST">
                        <h2>Shipping Information</h2>
                        
                        <div class="form-group">
                            <label for="full_name">Full Name *</label>
                            <input type="text" id="full_name" name="full_name" required value="<?php echo $user ? htmlspecialchars($user['full_name']) : ''; ?>">
                        </div>
                        
                        <div class="form-group">
                            <label for="email">Email *</label>
                            <input type="email" id="email" name="email" required value="<?php echo $user ? htmlspecialchars($user['email']) : ''; ?>">
                        </div>
                        
                        <div class="form-group">
                            <label for="phone">Phone</label>
                            <input type="tel" id="phone" name="phone" value="<?php echo $user ? htmlspecialchars($user['phone'] ?? '') : ''; ?>">
                        </div>
                        
                        <div class="form-group">
                            <label for="address">Address *</label>
                            <input type="text" id="address" name="address" required value="<?php echo $user ? htmlspecialchars($user['address'] ?? '') : ''; ?>">
                        </div>
                        
                        <div class="form-row">
                            <div class="form-group">
                                <label for="city">City *</label>
                                <input type="text" id="city" name="city" required>
                            </div>
                            <div class="form-group">
                                <label for="state">State/Province</label>
                                <input type="text" id="state" name="state">
                            </div>
                        </div>
                        
                        <div class="form-row">
                            <div class="form-group">
                                <label for="zip">ZIP/Postal Code *</label>
                                <input type="text" id="zip" name="zip" required>
                            </div>
                            <div class="form-group">
                                <label for="country">Country *</label>
                                <select id="country" name="country" required>
                                    <option value="">Select Country</option>
                                    <option value="US">United States</option>
                                    <option value="CA">Canada</option>
                                    <option value="UK">United Kingdom</option>
                                    <option value="AU">Australia</option>
                                    <option value="SG">Singapore</option>
                                    <option value="MY">Malaysia</option>
                                    <option value="OTHER">Other</option>
                                </select>
                            </div>
                        </div>
                        
                        <h2 style="margin-top: var(--spacing-xl);">Payment Method</h2>
                        
                        <div class="form-group">
                            <label>
                                <input type="radio" name="payment_method" value="credit_card" checked> Credit Card
                            </label>
                        </div>
                        
                        <div class="form-group">
                            <label>
                                <input type="radio" name="payment_method" value="paypal"> PayPal
                            </label>
                        </div>
                        
                        <div class="form-group">
                            <label for="notes">Order Notes</label>
                            <textarea id="notes" name="notes" rows="3" placeholder="Special instructions for your order..."></textarea>
                        </div>
                        
                        <button type="submit" class="btn btn-primary btn-large btn-block" <?php echo !$isLoggedIn ? 'disabled' : ''; ?>>
                            Place Order - <?php echo formatPrice($cartTotal); ?>
                        </button>
                    </form>
                </div>
                
                <!-- Order Summary -->
                <div class="checkout-summary">
                    <h3>Order Summary</h3>
                    
                    <?php foreach ($cartItems as $item): ?>
                        <div class="checkout-item">
                            <div>
                                <span><?php echo htmlspecialchars($item['name']); ?></span>
                                <?php if ($item['size'] || $item['color']): ?>
                                    <br><small style="color: var(--medium-gray);"><?php echo $item['size'] ? $item['size'] : ''; ?> <?php echo $item['color'] ? '/ ' . $item['color'] : ''; ?></small>
                                <?php endif; ?>
                                <br><small>x<?php echo $item['quantity']; ?></small>
                            </div>
                            <span><?php echo formatPrice($item['price'] * $item['quantity']); ?></span>
                        </div>
                    <?php endforeach; ?>
                    
                    <div class="checkout-item" style="border-top: 1px solid var(--lighter-gray); margin-top: var(--spacing-md); padding-top: var(--spacing-md);">
                        <span>Subtotal</span>
                        <span><?php echo formatPrice($cartTotal); ?></span>
                    </div>
                    <div class="checkout-item">
                        <span>Shipping</span>
                        <span>Free</span>
                    </div>
                    <div class="checkout-total">
                        <span>Total</span>
                        <span><?php echo formatPrice($cartTotal); ?></span>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</section>

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