<?php
require_once 'includes/User.php';
require_once 'includes/cart.php';
require_once 'includes/db_config.php';
require_once 'includes/session_helper.php';
require_once 'includes/pricing.php';

safe_session_start();

if (!User::isLoggedIn()) { 
    header("Location: /allura/login.php"); 
    exit(); 
}

$errors = isset($_SESSION['checkout_errors']) ? $_SESSION['checkout_errors'] : array();
$form_data = isset($_SESSION['checkout_data']) ? $_SESSION['checkout_data'] : array();

unset($_SESSION['checkout_errors']);
unset($_SESSION['checkout_data']);

$me = User::getCurrentUser();
$items = getCartItems();
$cart_items = isset($_SESSION['cart_items']) ? $_SESSION['cart_items'] : array();

if (empty($items) && empty($cart_items)) {
    header("Location: /allura/cart.php");
    exit();
}

$hasSub = false;
$subInfo = null;
try {
    $db = getDBConnection();
    $stmt = $db->prepare("
        SELECT * FROM subscriptions 
        WHERE user_id = ? AND status = 'active' AND end_date >= CURDATE() AND usage_count < max_usage
        ORDER BY created_at DESC LIMIT 1
    ");
    $stmt->execute([$me['id']]);
    $subInfo = $stmt->fetch(PDO::FETCH_ASSOC);
    $hasSub = !empty($subInfo);
} catch (PDOException $e) {
    $hasSub = false;
}

$details = array();
$tot = 0;

try {
    $db = getDBConnection();
    
    if (!empty($items)) {
        $ph = str_repeat('?,', count($items) - 1) . '?';
        $sql = "SELECT id, name, price FROM services WHERE id IN ($ph)";
        
        $ids = array_column($items, 'service_id');
        $st = $db->prepare($sql);
        $st->execute($ids);
        $rows = $st->fetchAll(PDO::FETCH_ASSOC);
        
        $map = array();
        foreach ($rows as $svc) { 
            $map[$svc['id']] = $svc; 
        }
        
        foreach ($items as $it) {
            $sid = $it['service_id'];
            if (isset($map[$sid])) {
                $svc = $map[$sid];
                $base_price = $svc['price'];
                $options_price = 0;
                
              
                if (isset($it['selected_options']) && is_array($it['selected_options'])) {
                    foreach ($it['selected_options'] as $key => $opt) {
                        if ($key === 'addons' && is_array($opt)) {
                            
                            foreach ($opt as $addon) {
                                if (isset($addon['price'])) {
                                    $options_price += floatval($addon['price']);
                                }
                            }
                        } elseif (is_array($opt)) {
                           
                            if (isset($opt['price'])) {
                                $options_price += floatval($opt['price']);
                            } elseif (isset($opt['price_modifier'])) {
                                $options_price += floatval($opt['price_modifier']);
                            }
                        }
                    }
                }
                
                if (TieredPricing::isTieredService($sid)) {
                    $tiered_total = TieredPricing::calculateTotalWithTiers($sid, $it['quantity'], $base_price);
                    $tp = $tiered_total + $options_price;
                } else {
                    $tp = ($base_price + $options_price) * $it['quantity'];
                }
                $tot += $tp;
                
                $details[] = [
                    'service_id' => $sid,
                    'name' => $svc['name'],
                    'price' => $base_price,
                    'options_price' => $options_price,
                    'quantity' => $it['quantity'],
                    'total_price' => $tp,
                    'selected_options' => $it['selected_options'] ?? null,
                    'type' => 'regular'
                ];
            }
        }
    }
    
    if (!empty($cart_items)) {
        $service_ids = array_unique(array_column($cart_items, 'service_id'));
        if (!empty($service_ids)) {
            $ph = str_repeat('?,', count($service_ids) - 1) . '?';
            $sql = "SELECT id, name, price, category FROM services WHERE id IN ($ph)";
            
            $st = $db->prepare($sql);
            $st->execute($service_ids);
            $service_rows = $st->fetchAll(PDO::FETCH_ASSOC);
            
            $service_map = [];
            foreach ($service_rows as $svc) { 
                $service_map[$svc['id']] = $svc; 
            }
            
            foreach ($cart_items as $index => $item) {
                $sid = $item['service_id'];
                if (isset($service_map[$sid])) {
                    $svc = $service_map[$sid];
                    $base_price = $svc['price'];
                    $quantity = $item['quantity'];
                    $options_price = 0;
                    
                    $selected_options = json_decode($item['selected_options'], true);
                    $options_text = [];
                    
                    if ($selected_options) {
                        foreach ($selected_options as $option_type => $option_data) {
                            if ($option_type === 'addons' && is_array($option_data)) {
                              
                                foreach ($option_data as $addon) {
                                    if (isset($addon['price'])) {
                                        $options_price += floatval($addon['price']);
                                        $options_text[] = $addon['name'];
                                    }
                                }
                            } elseif (is_array($option_data)) {
                               
                                if (isset($option_data['price'])) {
                                    $options_price += floatval($option_data['price']);
                                } elseif (isset($option_data['price_modifier'])) {
                                    $options_price += floatval($option_data['price_modifier']);
                                }
                                if (isset($option_data['name'])) {
                                    $options_text[] = $option_data['name'];
                                }
                            }
                        }
                    }
                    
                    if (TieredPricing::isTieredService($sid)) {
                        $tiered_total = TieredPricing::calculateTotalWithTiers($sid, $quantity, $base_price);
                        $total_price = $tiered_total + $options_price;
                    } else {
                        $total_price = ($base_price + $options_price) * $quantity;
                    }
                    $tot += $total_price;
                    
                    $details[] = [
                        'service_id' => $sid,
                        'cart_index' => $index,
                        'name' => $svc['name'],
                        'price' => $base_price,
                        'options_price' => $options_price,
                        'quantity' => $quantity,
                        'total_price' => $total_price,
                        'selected_options' => $selected_options,
                        'options_text' => implode(', ', $options_text),
                        'type' => 'custom',
                        'category' => $svc['category']
                    ];
                }
            }
        }
    }
} catch (PDOException $e) {
    $error = "Error fetching cart items: " . $e->getMessage();
}

$discount_amount = 0;
$offer_title = '';
$offer_id = null;
$customer_type = 'new'; 

if ($tot > 0) {
    try {
        $stmt = $db->prepare("
            SELECT u.*, 
                   COUNT(o.id) as order_count,
                   CASE 
                       WHEN EXISTS(SELECT 1 FROM subscriptions s WHERE s.user_id = u.id AND s.status = 'active') THEN 'subscribed'
                       WHEN COUNT(o.id) >= 5 THEN 'regular'
                       WHEN COUNT(o.id) > 0 THEN 'normal'
                       ELSE 'new'
                   END as customer_type
            FROM users u 
            LEFT JOIN orders o ON u.id = o.user_id 
            WHERE u.id = ?
            GROUP BY u.id
        ");
        $stmt->execute([$me['id']]);
        $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
        $customer_type = $user_data['customer_type'] ?? 'new';
        
        $stmt = $db->prepare("
            SELECT * FROM offers 
            WHERE status = 'active' 
            AND start_date <= CURDATE() 
            AND end_date >= CURDATE()
            AND (target_customers = 'all' OR target_customers = ?)
            AND min_order_amount <= ?
            AND (usage_limit IS NULL OR used_count < usage_limit)
            ORDER BY discount_value DESC
            LIMIT 1
        ");
        $stmt->execute([$customer_type, $tot]);
        $offer = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($offer) {
            if ($offer['discount_type'] === 'percentage') {
                $discount_amount = ($tot * $offer['discount_value']) / 100;
                if ($offer['max_discount_amount'] && $discount_amount > $offer['max_discount_amount']) {
                    $discount_amount = $offer['max_discount_amount'];
                }
            } else {
                $discount_amount = $offer['discount_value'];
            }
            $discount_amount = min($discount_amount, $tot);
            $offer_title = $offer['title'];
            $offer_id = $offer['id'];
        }
    } catch (PDOException $e) {
        error_log("Error applying discount in checkout: " . $e->getMessage());
    }
}

$discounted_total = $tot - $discount_amount;
$tax = $discounted_total * 0.08;
$grand = $discounted_total + $tax;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkout - Allura Dry Clean</title>
    <?php include 'includes/header.php'; ?>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="checkout-container">
        <div class="checkout-form">
            <a href="cart.php" class="checkout-btn-back">← Back to Cart</a>
            <h2>Checkout</h2>
            
            <?php if ($discount_amount > 0): ?>
            <div class="checkout-customer-offer-info">
                <div class="checkout-offer-header">
                    <span class="checkout-offer-icon">🎉</span>
                    <h4 class="checkout-offer-title">Special Offer for You!</h4>
                </div>
                <p class="checkout-offer-description">
                    <?php 
                        echo "As a " . ($customer_type == 'new' ? 'new' : ($customer_type == 'regular' ? 'valued' : ($customer_type == 'subscribed' ? 'subscribed' : 'regular'))) . " customer";
                        echo ", you get discount: <strong style='color: #00aaff;'>" . htmlspecialchars($offer_title) . "</strong>";
                    ?>
                </p>
            </div>
            <?php endif; ?>
            
            <?php if (!empty($errors)): ?>
                <div class="error-message">
                    <?php foreach ($errors as $error): ?>
                        <div><?php echo htmlspecialchars($error); ?></div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            
            <?php if (isset($error)): ?>
                <div class="error-message"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>
            
            <form id="checkoutForm" method="POST" action="/allura/php/process_checkout.php">
                <div class="checkout-form-group">
                    <label for="customer_name">Full Name *</label>
                    <input type="text" id="customer_name" name="customer_name" 
                           value="<?php echo htmlspecialchars(isset($form_data['customer_name']) ? $form_data['customer_name'] : $me['name']); ?>" required>
                </div>
                
                <div class="checkout-form-row">
                    <div class="checkout-form-group">
                        <label for="customer_phone">Phone Number *</label>
                        <input type="tel" id="customer_phone" name="customer_phone" 
                               value="<?php echo htmlspecialchars(isset($form_data['customer_phone']) ? $form_data['customer_phone'] : $me['phone']); ?>" required>
                    </div>
                    <div class="checkout-form-group">
                        <label for="payment_method">Payment Method *</label>
                        <select id="payment_method" name="payment_method" required>
                            <option value="">Select payment method</option>
                            <option value="cash" <?php echo (isset($form_data['payment_method']) && $form_data['payment_method'] == 'cash') ? 'selected' : ''; ?>>
                                💵 Cash on Delivery
                            </option>
                            <option value="card" <?php echo (isset($form_data['payment_method']) && $form_data['payment_method'] == 'card') ? 'selected' : ''; ?>>
                                💳 Credit/Debit Card
                            </option>
                            <option value="online" <?php echo (isset($form_data['payment_method']) && $form_data['payment_method'] == 'online') ? 'selected' : ''; ?>>
                                📱 Online Payment
                            </option>
                        </select>
                    </div>
                </div>
                
                <!-- Payment Details Container -->
                <div id="payment_details" class="payment-details-container"></div>
                
                <div class="checkout-form-group">
                    <label for="customer_address">Delivery Address *</label>
                    <textarea id="customer_address" name="customer_address" rows="3" required><?php echo htmlspecialchars(isset($form_data['customer_address']) ? $form_data['customer_address'] : $me['address']); ?></textarea>
                </div>
                
                <div class="checkout-form-group">
                    <label>Estimated Delivery</label>
                    <div class="checkout-delivery-info">
                        <p style="margin: 0; color: #666; font-size: 0.9rem;">
                            <strong>Delivery will be calculated based on your selected services:</strong><br>
                            • Standard Delivery: 3-5 business days<br>
                            • Express Delivery: Same day to 48 hours
                        </p>
                        <p style="margin: 0.5rem 0 0 0; color: #00aaff; font-weight: 600; font-size: 0.9rem;">
                            Exact delivery date will be confirmed after order processing.
                        </p>
                    </div>
                </div>
                
                <?php if ($hasSub): ?>
                <div class="checkout-form-group sub-del-opt">
                    <div class="sub-exp-card">
                        <div class="sub-hdr">
                            <h4><i class="fas fa-crown"></i> Express Delivery</h4>
                            <span class="sub-badge">Available</span>
                        </div>
                        <div class="sub-details">
                            <p><strong>Plan:</strong> <?php echo htmlspecialchars($subInfo['plan_name']); ?></p>
                            <p><strong>Remaining:</strong> <?php echo ($subInfo['max_usage'] - $subInfo['usage_count']); ?></p>
                            <p><strong>Valid Until:</strong> <?php echo date('F j, Y', strtotime($subInfo['end_date'])); ?></p>
                        </div>
                        <div class="sub-opt">
                            <div class="subscription-option">
                                <label class="sub-chk">
                                    <input type="checkbox" id="use_subscription" name="use_subscription" value="1">
                                    <span class="checkmark"></span>
                                    <div class="opt-content">
                                        <div class="opt-header">
                                            <i class="fas fa-bolt"></i>
                                            <strong>Use Express Delivery Plan</strong>
                                            <span class="express-badge">Same day - 48h</span>
                                        </div>
                                        <div class="opt-description">
                                            <small>✓ Priority processing • ✓ Fast delivery (0-2 days) • Uses 1 order from your plan</small>
                                        </div>
                                        <div class="opt-action">
                                            <span class="click-hint"> Click here to activate express delivery</span>
                                        </div>
                                    </div>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <div class="checkout-form-group">
                    <label for="notes">Special Instructions (Optional)</label>
                    <textarea id="notes" name="notes" rows="3" 
                              placeholder="Any special instructions for your order..."><?php echo isset($form_data['notes']) ? htmlspecialchars($form_data['notes']) : ''; ?></textarea>
                </div>
                
                <button type="submit" class="btn-checkout">Place Order</button>
            </form>
        </div>
        
        <div class="checkout-order-summary">
            <h3>Order Summary</h3>
            
            <div class="order-items">
                <?php foreach ($details as $item): ?>
                <div class="checkout-order-item">
                    <div class="checkout-item-details">
                        <div class="checkout-item-name"><?php echo htmlspecialchars($item['name']); ?></div>
                        <div class="checkout-item-quantity">
                            Qty: <?php echo $item['quantity']; ?> × SAR <?php echo number_format($item['price'], 2); ?>
                            <?php if (isset($item['options_price']) && $item['options_price'] > 0): ?>
                            <span style="color: #00aaff;"> + SAR <?php echo number_format($item['options_price'], 2); ?></span>
                            <?php endif; ?>
                        </div>
                        <?php if (isset($item['options_text']) && !empty($item['options_text'])): ?>
                        <div class="checkout-item-options"><?php echo htmlspecialchars($item['options_text']); ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="checkout-item-price">SAR <?php echo number_format($item['total_price'], 2); ?></div>
                </div>
                <?php endforeach; ?>
            </div>
            
            <?php if ($discount_amount > 0): ?>
            <div class="checkout-discount-info">
                <h4 class="checkout-discount-title">🎉 Discount Applied!</h4>
                <p class="checkout-discount-description"><strong style="color: #00aaff;"><?php echo htmlspecialchars($offer_title); ?></strong></p>
                <p class="checkout-discount-amount">You save: SAR <?php echo number_format($discount_amount, 2); ?></p>
            </div>
            <?php endif; ?>
            
            <div class="order-totals">
                <div class="checkout-summary-row">
                    <span>Subtotal:</span>
                    <span>SAR <?php echo number_format($tot, 2); ?></span>
                </div>
                <?php if ($discount_amount > 0): ?>
                <div class="checkout-summary-row checkout-discount-row">
                    <span>Discount (<?php echo htmlspecialchars($offer_title); ?>):</span>
                    <span>-SAR <?php echo number_format($discount_amount, 2); ?></span>
                </div>
                <?php endif; ?>
                <div class="checkout-summary-row">
                    <span>Tax (8%):</span>
                    <span>SAR <?php echo number_format($tax, 2); ?></span>
                </div>
                <div class="checkout-summary-row checkout-total-row">
                    <span>Total:</span>
                    <span>SAR <?php echo number_format($grand, 2); ?></span>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/js/all.min.js"></script>
    <script src="/allura/js/checkout.js"></script>
</body>
</html>
