<?php
session_start();
require_once '../includes/product-card.php';
require_once '../config/database.php';
require_once '../models/user.php';

$page_title = 'إتمام الطلب';
$base_path = '../';

// Check login
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php?redirect=checkout');
    exit;
}

$database = new Database();
$conn = $database->getConnection();

// Initialize user model for footer
$user_model = new User($conn);

// Get cart items
$stmt = $conn->prepare("
    SELECT c.*, p.name, p.price, p.image 
    FROM cart c 
    JOIN products p ON c.product_id = p.id 
    WHERE c.user_id = ?
");
$stmt->execute([$_SESSION['user_id']]);
$cart_items = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($cart_items)) {
    header('Location: cart.php');
    exit;
}

// Calculate totals
$subtotal = 0;
foreach ($cart_items as $item) {
    $subtotal += $item['price'] * $item['quantity'];
}
$shipping = 0;
$tax = $subtotal * 0.15;
$total = $subtotal + $shipping + $tax;

// Get user data
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Get saved addresses
try {
    $stmt = $conn->prepare("SELECT * FROM user_addresses WHERE user_id = ? ORDER BY is_default DESC, created_at DESC");
    $stmt->execute([$_SESSION['user_id']]);
    $saved_addresses = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $saved_addresses = [];
}

// Get default address
$default_address = !empty($saved_addresses) ? $saved_addresses[0] : null;
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <title><?php echo $page_title; ?> - Roz Skin</title>
    
    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    
    <style>
        * {
            font-family: 'Tajawal', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
        }
        
        body {
            font-family: 'Tajawal', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: linear-gradient(135deg, #fff5f7 0%, #ffe8f0 50%, #ffd6e8 100%);
            background-attachment: fixed;
            min-height: 100vh;
        }
        
        .address-option:has(input:checked) {
            border-color: #E57393;
            background: #FFF5F7;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav id="mainNav" style="background: rgba(255, 255, 255, 0.8); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid rgba(229, 115, 147, 0.08); position: fixed; top: 0; left: 0; right: 0; z-index: 1000; transition: transform 0.3s ease;">
        <div style="max-width: 1400px; margin: 0 auto; padding: 0 24px;">
            <div style="display: flex; align-items: center; justify-content: space-between; height: 60px;">
                
                <!-- Actions - Right Side -->
                <div style="display: flex; align-items: center; gap: 20px;">
                    <!-- Burger Menu -->
                    <button id="burgerBtn" onclick="toggleBurgerMenu()" style="background: transparent; border: none; padding: 8px; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.2s;" onmouseover="this.style.opacity='0.7'" onmouseout="this.style.opacity='1'">
                        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#E57393" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <line x1="3" y1="12" x2="21" y2="12"></line>
                            <line x1="3" y1="6" x2="21" y2="6"></line>
                            <line x1="3" y1="18" x2="21" y2="18"></line>
                        </svg>
                    </button>
                </div>

                <!-- Logo - Left Side -->
                <a href="index.php" style="font-size: 22px; font-weight: 800; background: linear-gradient(135deg, #E57393 0%, #D1537A 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; text-decoration: none; letter-spacing: -0.3px;">
                    Roz Skin
                </a>
            </div>
        </div>
    </nav>

    <!-- Floating Cart Button -->
    <button onclick="window.location.href='cart.php'" title="السلة" style="position: fixed; bottom: 24px; right: 24px; z-index: 999; background: linear-gradient(135deg, #E57393 0%, #D1537A 100%); border: none; width: 56px; height: 56px; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 16px rgba(229, 115, 147, 0.4); transition: all 0.3s;" onmouseover="this.style.transform='scale(1.1)'; this.style.boxShadow='0 6px 24px rgba(229, 115, 147, 0.5)'" onmouseout="this.style.transform='scale(1)'; this.style.boxShadow='0 4px 16px rgba(229, 115, 147, 0.4)'">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <circle cx="9" cy="21" r="1"></circle>
            <circle cx="20" cy="21" r="1"></circle>
            <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
        </svg>
        <?php
        $cart_count = 0;
        if (isset($_SESSION['user_id'])) {
            try {
                require_once '../models/cart.php';
                $cart_model = new Cart($conn);
                $cart_count = $cart_model->getCartCount($_SESSION['user_id']);
            } catch (Exception $e) {
                $cart_count = 0;
            }
        }
        if ($cart_count > 0): ?>
            <span id="cartBadge" style="position: absolute; top: -4px; right: -4px; background: white; color: #E57393; font-size: 11px; font-weight: 800; min-width: 22px; height: 22px; border-radius: 11px; display: flex; align-items: center; justify-content: center; padding: 0 6px; box-shadow: 0 2px 8px rgba(0,0,0,0.15);"><?php echo $cart_count; ?></span>
        <?php else: ?>
            <span id="cartBadge" style="display: none;"></span>
        <?php endif; ?>
    </button>

    <script>
        // Hide/Show navbar on scroll
        let lastScrollTop = 0;
        const navbar = document.getElementById('mainNav');
        
        window.addEventListener('scroll', function() {
            let scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            
            if (scrollTop > lastScrollTop && scrollTop > 100) {
                navbar.style.transform = 'translateY(-100%)';
            } else {
                navbar.style.transform = 'translateY(0)';
            }
            
            lastScrollTop = scrollTop;
        });
    </script>

    <div style="height: 60px;"></div>

    <!-- Burger Menu Overlay -->
    <div id="burgerMenu" style="position: fixed; top: 0; right: -100%; width: 320px; height: 100vh; background: white; box-shadow: -4px 0 20px rgba(0,0,0,0.1); z-index: 9999; transition: right 0.3s ease; overflow-y: auto;">
        <div style="padding: 20px;">
            <!-- Close Button -->
            <button onclick="toggleBurgerMenu()" style="background: rgba(229, 115, 147, 0.1); border: none; width: 40px; height: 40px; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; margin-bottom: 30px; transition: all 0.3s;" onmouseover="this.style.background='rgba(229, 115, 147, 0.2)'" onmouseout="this.style.background='rgba(229, 115, 147, 0.1)'">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#E57393" stroke-width="2.5">
                    <line x1="18" y1="6" x2="6" y2="18"></line>
                    <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
            </button>

            <!-- Menu Items -->
            <div style="display: flex; flex-direction: column; gap: 8px;">
                <?php if (isset($_SESSION['user_id'])): ?>
                    <a href="account.php" style="display: flex; align-items: center; gap: 12px; padding: 14px 16px; border-radius: 12px; text-decoration: none; color: #333; font-weight: 600; transition: all 0.3s;" onmouseover="this.style.background='rgba(229, 115, 147, 0.1)'" onmouseout="this.style.background='transparent'">
                        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#E57393" stroke-width="2">
                            <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                            <circle cx="12" cy="7" r="4"></circle>
                        </svg>
                        حسابي
                    </a>
                <?php else: ?>
                    <a href="login.php" style="display: flex; align-items: center; gap: 12px; padding: 14px 16px; border-radius: 12px; text-decoration: none; color: #333; font-weight: 600; transition: all 0.3s;" onmouseover="this.style.background='rgba(229, 115, 147, 0.1)'" onmouseout="this.style.background='transparent'">
                        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#E57393" stroke-width="2">
                            <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"></path>
                            <polyline points="10 17 15 12 10 7"></polyline>
                            <line x1="15" y1="12" x2="3" y2="12"></line>
                        </svg>
                        تسجيل الدخول
                    </a>
                <?php endif; ?>

                <a href="blog.php" style="display: flex; align-items: center; gap: 12px; padding: 14px 16px; border-radius: 12px; text-decoration: none; color: #333; font-weight: 600; transition: all 0.3s;" onmouseover="this.style.background='rgba(229, 115, 147, 0.1)'" onmouseout="this.style.background='transparent'">
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#E57393" stroke-width="2">
                        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
                        <polyline points="14 2 14 8 20 8"></polyline>
                        <line x1="16" y1="13" x2="8" y2="13"></line>
                        <line x1="16" y1="17" x2="8" y2="17"></line>
                    </svg>
                    روز فيد
                </a>

                <div style="height: 1px; background: rgba(229, 115, 147, 0.1); margin: 12px 0;"></div>

                <a href="products.php" style="display: flex; align-items: center; gap: 12px; padding: 14px 16px; border-radius: 12px; text-decoration: none; color: #333; font-weight: 600; transition: all 0.3s;" onmouseover="this.style.background='rgba(229, 115, 147, 0.1)'" onmouseout="this.style.background='transparent'">
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#E57393" stroke-width="2">
                        <circle cx="9" cy="21" r="1"></circle>
                        <circle cx="20" cy="21" r="1"></circle>
                        <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
                    </svg>
                    المنتجات
                </a>

                <a href="services.php" style="display: flex; align-items: center; gap: 12px; padding: 14px 16px; border-radius: 12px; text-decoration: none; color: #333; font-weight: 600; transition: all 0.3s;" onmouseover="this.style.background='rgba(229, 115, 147, 0.1)'" onmouseout="this.style.background='transparent'">
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#E57393" stroke-width="2">
                        <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
                        <line x1="16" y1="2" x2="16" y2="6"></line>
                        <line x1="8" y1="2" x2="8" y2="6"></line>
                        <line x1="3" y1="10" x2="21" y2="10"></line>
                    </svg>
                    الخدمات
                </a>
            </div>
        </div>
    </div>

    <!-- Burger Menu Backdrop -->
    <div id="burgerBackdrop" onclick="toggleBurgerMenu()" style="position: fixed; top: 0; left: 0; width: 100%; height: 100vh; background: rgba(0,0,0,0.5); z-index: 9998; display: none; opacity: 0; transition: opacity 0.3s;"></div>

    <script>
        function toggleBurgerMenu() {
            const menu = document.getElementById('burgerMenu');
            const backdrop = document.getElementById('burgerBackdrop');
            const isOpen = menu.style.right === '0px';
            
            if (isOpen) {
                menu.style.right = '-100%';
                backdrop.style.display = 'none';
                backdrop.style.opacity = '0';
                document.body.style.overflow = '';
            } else {
                menu.style.right = '0';
                backdrop.style.display = 'block';
                setTimeout(() => backdrop.style.opacity = '1', 10);
                document.body.style.overflow = 'hidden';
            }
        }
    </script>

<!-- Hero -->
<section class="py-6 bg-gradient-to-r from-pink-50 to-purple-50">
    <div class="container mx-auto px-4">
        <div class="flex items-center gap-2 text-sm text-gray-600 mb-3">
            <a href="index.php" class="hover:text-[#E57393]">الرئيسية</a>
            <span class="text-xs">◀</span>
            <a href="cart.php" class="hover:text-[#E57393]">السلة</a>
            <span class="text-xs">◀</span>
            <span class="text-[#E57393]">إتمام الطلب</span>
        </div>
        <h1 class="text-3xl font-bold">إتمام الطلب</h1>
    </div>
</section>

<!-- Progress Steps -->
<section class="py-4 bg-white border-b">
    <div class="container mx-auto px-4">
        <div class="flex items-center justify-center gap-3">
            <div class="flex items-center gap-2">
                <div class="w-8 h-8 rounded-full bg-[#E57393] text-white flex items-center justify-center text-sm font-bold">1</div>
                <span class="text-sm font-bold text-[#E57393]">الشحن</span>
            </div>
            <div class="w-12 h-0.5 bg-gray-300"></div>
            <div class="flex items-center gap-2">
                <div class="w-8 h-8 rounded-full bg-gray-300 text-gray-600 flex items-center justify-center text-sm font-bold">2</div>
                <span class="text-sm text-gray-600">الدفع</span>
            </div>
            <div class="w-12 h-0.5 bg-gray-300"></div>
            <div class="flex items-center gap-2">
                <div class="w-8 h-8 rounded-full bg-gray-300 text-gray-600 flex items-center justify-center text-sm font-bold">3</div>
                <span class="text-sm text-gray-600">تأكيد</span>
            </div>
        </div>
    </div>
</section>

<!-- Main Content -->
<section class="py-8 bg-gray-50">
    <div class="container mx-auto px-4">
        
        <?php if (isset($_SESSION['error'])): ?>
        <div class="bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded-lg mb-6">
            <span style="margin-left: 8px;">⚠️</span>
            <?php echo htmlspecialchars($_SESSION['error']); ?>
            <?php unset($_SESSION['error']); ?>
        </div>
        <?php endif; ?>
        
        <form id="checkoutForm" method="POST" action="../api/orders/create.php">
            <!-- Hidden fields for user info (used when saved address is selected) -->
            <input type="hidden" name="user_email" value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>">
            <input type="hidden" name="user_phone" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>">
            <input type="hidden" name="user_name" value="<?php echo htmlspecialchars($user['name'] ?? ''); ?>">
            
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                
                <!-- Left: Forms -->
                <div class="lg:col-span-2 space-y-6">
                    
                    <!-- Saved Addresses -->
                    <?php if (!empty($saved_addresses)): ?>
                    <div class="bg-white rounded-lg shadow-sm p-6">
                        <div class="flex items-center justify-between mb-4">
                            <h2 class="text-xl font-bold">عناوين الشحن المحفوظة</h2>
                            <button type="button" onclick="toggleNewAddress()" class="text-[#E57393] text-sm hover:underline">
                                + عنوان جديد
                            </button>
                        </div>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                            <?php foreach ($saved_addresses as $addr): ?>
                            <label class="address-option border-2 rounded-lg p-3 cursor-pointer hover:border-[#E57393] transition">
                                <div class="flex items-start gap-2">
                                    <input type="radio" name="address_id" value="<?php echo $addr['id']; ?>" 
                                           <?php echo $addr['is_default'] ? 'checked' : ''; ?>
                                           class="mt-1">
                                    <div class="flex-1 text-sm">
                                        <div class="font-bold text-gray-800"><?php echo htmlspecialchars($addr['label']); ?></div>
                                        <div class="text-gray-600 mt-1"><?php echo htmlspecialchars($addr['address']); ?></div>
                                        <?php if ($addr['is_default']): ?>
                                            <span class="inline-block mt-2 px-2 py-1 bg-[#E57393] text-white text-xs rounded">افتراضي</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- New Address Form -->
                    <div id="newAddressForm" class="bg-white rounded-lg shadow-sm p-6" <?php echo !empty($saved_addresses) ? 'style="display:none"' : ''; ?>>
                        <h2 class="text-xl font-bold mb-4">معلومات الشحن</h2>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div class="md:col-span-2">
                                <label class="block text-sm font-bold mb-1">الاسم الكامل *</label>
                                <input type="text" name="full_name" required
                                       value="<?php echo htmlspecialchars($user['name'] ?? ''); ?>"
                                       class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:border-[#E57393]">
                            </div>
                            
                            <div>
                                <label class="block text-sm font-bold mb-1">رقم الجوال *</label>
                                <input type="tel" name="phone" required
                                       value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>"
                                       class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:border-[#E57393]">
                            </div>
                            
                            <div>
                                <label class="block text-sm font-bold mb-1">البريد الإلكتروني (اختياري)</label>
                                <input type="email" name="email"
                                       value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>"
                                       placeholder="example@email.com"
                                       class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:border-[#E57393]">
                            </div>
                            
                            <div class="md:col-span-2">
                                <label class="block text-sm font-bold mb-1">العنوان *</label>
                                <input type="text" name="address_line1" required
                                       placeholder="الشارع، رقم المبنى، المنطقة"
                                       class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:border-[#E57393]">
                            </div>
                            
                            <div>
                                <label class="block text-sm font-bold mb-1">المدينة *</label>
                                <input type="text" name="city" required
                                       placeholder="المدينة"
                                       class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:border-[#E57393]">
                            </div>
                            
                            <div>
                                <label class="block text-sm font-bold mb-1">الرمز البريدي</label>
                                <input type="text" name="postal_code"
                                       placeholder="اختياري"
                                       class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:border-[#E57393]">
                            </div>
                            
                            <div class="md:col-span-2">
                                <label class="block text-sm font-bold mb-1">ملاحظات (اختياري)</label>
                                <textarea name="notes" rows="2"
                                          class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:border-[#E57393]"></textarea>
                            </div>
                            
                            <div class="md:col-span-2">
                                <label class="flex items-center gap-2">
                                    <input type="checkbox" name="save_address" value="1">
                                    <span class="text-sm">حفظ العنوان للمستقبل</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Payment Method -->
                    <div class="bg-white rounded-lg shadow-sm p-6">
                        <h2 class="text-xl font-bold mb-4">طريقة الدفع</h2>
                        
                        <label class="flex items-center gap-3 p-3 border-2 rounded-lg cursor-pointer hover:border-[#E57393]">
                            <input type="radio" name="payment_method" value="cod" checked>
                            <div style="width: 40px; height: 40px; border-radius: 50%; background: rgba(34, 197, 94, 0.1); display: flex; align-items: center; justify-content: center; font-size: 20px;">
                                💵
                            </div>
                            <div>
                                <div class="font-bold">الدفع عند الاستلام</div>
                                <div class="text-xs text-gray-600">ادفع نقداً عند الاستلام</div>
                            </div>
                        </label>
                    </div>
                    
                </div>
                
                <!-- Right: Summary -->
                <div class="lg:col-span-1">
                    <div class="bg-white rounded-lg shadow-sm p-6 sticky top-4">
                        <h3 class="text-lg font-bold mb-4">ملخص الطلب</h3>
                        
                        <!-- Items -->
                        <div class="space-y-2 mb-4 max-h-48 overflow-y-auto">
                            <?php foreach ($cart_items as $item): 
                                // Fix image path
                                $image_path = $item['image'];
                                if (strpos($image_path, 'uploads/') === 0) {
                                    $image_path = '../' . $image_path;
                                } elseif (strpos($image_path, '../uploads/') !== 0) {
                                    $image_path = '../uploads/products/' . $image_path;
                                }
                            ?>
                            <div class="flex gap-2 text-sm">
                                <img src="<?php echo htmlspecialchars($image_path); ?>" 
                                     onerror="this.src='../uploads/products/placeholder.svg'"
                                     class="w-12 h-12 object-cover rounded">
                                <div class="flex-1">
                                    <div class="font-bold text-xs"><?php echo htmlspecialchars($item['name']); ?></div>
                                    <div class="text-gray-600 text-xs">الكمية: <?php echo $item['quantity']; ?></div>
                                </div>
                                <div class="font-bold text-[#E57393] text-sm">
                                    <?php echo number_format($item['price'] * $item['quantity'], 2); ?> ج.م
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        
                        <!-- Coupon -->
                        <div class="border-t pt-4 mb-4">
                            <div class="flex gap-2">
                                <input type="text" id="couponCode" placeholder="كود الخصم"
                                       class="flex-1 px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#E57393]">
                                <button type="button" onclick="applyCoupon()" 
                                        class="px-4 py-2 bg-[#E57393] text-white rounded-lg text-sm font-bold hover:bg-[#D65D7A]">
                                    تطبيق
                                </button>
                            </div>
                            <div id="couponMsg" class="text-xs mt-1"></div>
                        </div>
                        
                        <!-- Totals -->
                        <div class="border-t pt-4 space-y-2 text-sm">
                            <div class="flex justify-between">
                                <span>المجموع الفرعي</span>
                                <span id="subtotalDisplay"><?php echo number_format($subtotal, 2); ?> ج.م</span>
                            </div>
                            <div id="discountRow" class="flex justify-between text-green-600" style="display:none">
                                <span>الخصم</span>
                                <span id="discountDisplay">0.00 ج.م</span>
                            </div>
                            <div class="flex justify-between">
                                <span>الشحن</span>
                                <span class="text-green-600">مجاني</span>
                            </div>
                            <div class="flex justify-between">
                                <span>الضريبة (15%)</span>
                                <span id="taxDisplay"><?php echo number_format($tax, 2); ?> ج.م</span>
                            </div>
                            <div class="flex justify-between font-bold text-lg border-t pt-2">
                                <span>الإجمالي</span>
                                <span class="text-[#E57393]" id="totalDisplay"><?php echo number_format($total, 2); ?> ج.م</span>
                            </div>
                        </div>
                        
                        <!-- Submit -->
                        <button type="button" id="submitOrderBtn" class="w-full mt-4 bg-[#E57393] text-white py-3 rounded-lg font-bold hover:bg-[#D65D7A] transition">
                            إتمام الطلب
                        </button>
                        
                        <div class="text-center text-xs text-gray-500 mt-3">
                            🔒 معاملة آمنة
                        </div>
                    </div>
                </div>
                
            </div>
        </form>
    </div>
</section>

<script>
const originalSubtotal = <?php echo $subtotal; ?>;
let discount = 0;
let appliedCouponCode = null;

function toggleNewAddress() {
    const form = document.getElementById('newAddressForm');
    form.style.display = form.style.display === 'none' ? 'block' : 'none';
    
    if (form.style.display === 'block') {
        document.querySelectorAll('input[name="address_id"]').forEach(r => r.checked = false);
    }
}

function applyCoupon() {
    const code = document.getElementById('couponCode').value.trim();
    const msg = document.getElementById('couponMsg');
    
    if (!code) {
        msg.className = 'text-xs mt-1 text-red-600';
        msg.textContent = 'أدخل كود الخصم';
        return;
    }
    
    msg.className = 'text-xs mt-1 text-blue-600';
    msg.innerHTML = '⏳ جاري التحقق...';
    
    fetch('../api/apply_coupon.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({code: code, subtotal: originalSubtotal})
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            discount = data.discount;
            appliedCouponCode = code;
            updateTotals();
            
            msg.className = 'text-xs mt-1 text-green-600';
            msg.innerHTML = '✓ ' + data.message;
            
            // Add hidden input
            let input = document.getElementById('couponInput');
            if (!input) {
                input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'coupon_code';
                input.id = 'couponInput';
                document.getElementById('checkoutForm').appendChild(input);
            }
            input.value = code;
        } else {
            msg.className = 'text-xs mt-1 text-red-600';
            msg.innerHTML = '✗ ' + data.message;
        }
    })
    .catch(() => {
        msg.className = 'text-xs mt-1 text-red-600';
        msg.textContent = 'حدث خطأ';
    });
}

function updateTotals() {
    const newSubtotal = originalSubtotal - discount;
    const newTax = newSubtotal * 0.15;
    const newTotal = newSubtotal + newTax;
    
    if (discount > 0) {
        document.getElementById('discountRow').style.display = 'flex';
        document.getElementById('discountDisplay').textContent = '-' + discount.toFixed(2) + ' ج.م';
    }
    
    document.getElementById('taxDisplay').textContent = newTax.toFixed(2) + ' ج.م';
    document.getElementById('totalDisplay').textContent = newTotal.toFixed(2) + ' ج.م';
}

// Handle button click and validate before submit
document.getElementById('submitOrderBtn').addEventListener('click', function(e) {
    e.preventDefault(); // Prevent default form submission
    console.log('✓ Submit button clicked!');
    
    const form = document.getElementById('checkoutForm');
    const hasAddress = document.querySelector('input[name="address_id"]:checked');
    const formVisible = document.getElementById('newAddressForm').style.display !== 'none';
    
    console.log('Has saved address selected:', hasAddress ? 'Yes (ID: ' + hasAddress.value + ')' : 'No');
    console.log('New address form visible:', formVisible);
    
    // Check if address is selected
    if (!hasAddress && !formVisible) {
        alert('اختر عنوان الشحن أو املأ عنوان جديد');
        console.log('ERROR: No address selected');
        return false;
    }
    
    // Validate new address form if visible
    if (formVisible && !hasAddress) {
        const fullName = document.querySelector('input[name="full_name"]').value;
        const phone = document.querySelector('input[name="phone"]').value;
        const address = document.querySelector('input[name="address_line1"]').value;
        const city = document.querySelector('input[name="city"]').value;
        
        console.log('Form data:', {fullName, phone, address, city});
        
        if (!fullName || !phone || !address || !city) {
            alert('الرجاء ملء الحقول المطلوبة (الاسم، الجوال، العنوان، المدينة)');
            console.log('ERROR: Missing required fields');
            return false;
        }
    }
    
    console.log('✓ Validation passed, submitting form...');
    
    // Show loading
    this.disabled = true;
    this.innerHTML = '⏳ جاري المعالجة...';
    
    // Submit the form
    form.submit();
});

// Log form info
const checkoutForm = document.getElementById('checkoutForm');
console.log('Form found:', checkoutForm ? 'Yes' : 'No');
console.log('Form action:', checkoutForm ? checkoutForm.action : 'N/A');
</script>

<!-- Simple Footer -->
<footer style="background: white; border-top: 1px solid rgba(229, 115, 147, 0.1); padding: 40px 20px; margin-top: 60px;">
    <div style="max-width: 1400px; margin: 0 auto; text-align: center;">
        <div style="font-size: 24px; font-weight: 800; background: linear-gradient(135deg, #E57393 0%, #D1537A 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; margin-bottom: 20px;">
            Roz Skin
        </div>
        <p style="color: #666; font-size: 14px; margin-bottom: 20px;">
            متجر إلكتروني متخصص في منتجات العناية بالبشرة والجمال الطبيعية 100%
        </p>
        <div style="display: flex; gap: 15px; justify-content: center; margin-bottom: 20px;">
            <a href="https://facebook.com" target="_blank" style="width: 40px; height: 40px; border-radius: 50%; background: rgba(229, 115, 147, 0.1); display: flex; align-items: center; justify-content: center; text-decoration: none; transition: all 0.3s; font-size: 20px;" onmouseover="this.style.background='#E57393'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='rgba(229, 115, 147, 0.1)'; this.style.transform='scale(1)'">
                📘
            </a>
            <a href="https://instagram.com" target="_blank" style="width: 40px; height: 40px; border-radius: 50%; background: rgba(229, 115, 147, 0.1); display: flex; align-items: center; justify-content: center; text-decoration: none; transition: all 0.3s; font-size: 20px;" onmouseover="this.style.background='#E57393'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='rgba(229, 115, 147, 0.1)'; this.style.transform='scale(1)'">
                📷
            </a>
            <a href="https://wa.me/201234567890" target="_blank" style="width: 40px; height: 40px; border-radius: 50%; background: rgba(229, 115, 147, 0.1); display: flex; align-items: center; justify-content: center; text-decoration: none; transition: all 0.3s; font-size: 20px;" onmouseover="this.style.background='#E57393'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='rgba(229, 115, 147, 0.1)'; this.style.transform='scale(1)'">
                💬
            </a>
        </div>
        <p style="color: #999; font-size: 13px;">
            © 2024 Roz Skin. جميع الحقوق محفوظة.
        </p>
    </div>
</footer>

</body>
</html>
