<?php
session_start();
require_once '../includes/product-card.php';
require_once '../config/database.php';
require_once '../models/user.php';

$page_title = 'السلة';
$base_path = '../';

$database = new Database();
$conn = $database->getConnection();
$user_model = new User($conn);

$cart_items = [];
$total = 0;
$discount = 0;
$applied_coupon = null;

if (isset($_SESSION['user_id'])) {
    $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);
    
    foreach ($cart_items as $item) {
        $total += $item['price'] * $item['quantity'];
    }
    
    if (isset($_SESSION['applied_coupon'])) {
        $applied_coupon = $_SESSION['applied_coupon'];
        $discount = $applied_coupon['discount'];
    }
}

$final_total = $total - $discount;

try {
    $stmt = $conn->prepare("SELECT setting_value FROM settings WHERE setting_key = 'store_name'");
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    $site_name = $result ? $result['setting_value'] : 'Roz Skin';
    $logo_text = $site_name;
} catch (PDOException $e) {
    $site_name = 'Roz Skin';
    $logo_text = 'Roz Skin';
}

$cart_count = count($cart_items);
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?> - <?php echo $site_name; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Tajawal', -apple-system, BlinkMacSystemFont, sans-serif;
        }
        
        body {
            background: #F7F7F7;
            color: #111111;
            line-height: 1.6;
            -webkit-font-smoothing: antialiased;
        }
        
        /* Navigation */
        .nav {
            position: sticky;
            top: 0;
            z-index: 100;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            border-bottom: 1px solid #EFEFEF;
        }
        
        .nav-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 16px 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .nav-logo {
            font-size: 22px;
            font-weight: 800;
            color: #E57393;
            text-decoration: none;
            letter-spacing: -0.5px;
        }
        
        .nav-back {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #F7F7F7;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
        }
        
        .nav-back:active {
            transform: scale(0.95);
            background: #EFEFEF;
        }
        
        /* Container */
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }
        
        /* Page Header */
        .page-header {
            text-align: center;
            padding: 24px 0;
            background: white;
            margin-bottom: 20px;
        }
        
        .page-title {
            font-size: 28px;
            font-weight: 800;
            color: #111111;
            margin-bottom: 8px;
        }
        
        .page-subtitle {
            font-size: 15px;
            color: #767676;
        }
        
        /* Cart Layout */
        .cart-layout {
            display: grid;
            grid-template-columns: 1fr;
            gap: 20px;
        }
        
        /* Cart Items */
        .cart-items {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        
        .cart-item {
            background: white;
            border-radius: 16px;
            padding: 16px;
            display: flex;
            gap: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        
        .item-image {
            width: 90px;
            height: 90px;
            border-radius: 12px;
            overflow: hidden;
            background: #F7F7F7;
            flex-shrink: 0;
        }
        
        .item-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .item-details {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        
        .item-name {
            font-size: 15px;
            font-weight: 700;
            color: #111111;
            line-height: 1.4;
        }
        
        .item-price {
            font-size: 18px;
            font-weight: 800;
            color: #E57393;
        }
        
        .item-actions {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: auto;
        }
        
        .quantity-control {
            display: flex;
            align-items: center;
            gap: 12px;
            background: #F7F7F7;
            border-radius: 50px;
            padding: 6px;
        }
        
        .qty-btn {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: white;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            color: #111111;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: all 0.2s;
        }
        
        .qty-btn:active {
            transform: scale(0.95);
        }
        
        .qty-value {
            min-width: 24px;
            text-align: center;
            font-weight: 700;
            font-size: 15px;
        }
        
        .remove-btn {
            background: transparent;
            border: none;
            color: #EF4444;
            cursor: pointer;
            padding: 8px;
            font-size: 18px;
            transition: all 0.2s;
        }
        
        .remove-btn:active {
            transform: scale(0.9);
        }
        
        /* Summary */
        .cart-summary {
            background: white;
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }
        
        .summary-title {
            font-size: 18px;
            font-weight: 800;
            margin-bottom: 20px;
            color: #111111;
        }
        
        .summary-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid #F7F7F7;
        }
        
        .summary-row:last-child {
            border-bottom: none;
            padding-top: 16px;
            margin-top: 8px;
            border-top: 2px solid #F7F7F7;
        }
        
        .summary-label {
            font-size: 15px;
            color: #767676;
        }
        
        .summary-value {
            font-size: 15px;
            font-weight: 700;
            color: #111111;
        }
        
        .summary-total {
            font-size: 24px;
            font-weight: 800;
            color: #E57393;
        }
        
        /* Buttons */
        .btn {
            width: 100%;
            padding: 16px;
            border-radius: 12px;
            border: none;
            font-size: 16px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            text-decoration: none;
        }
        
        .btn-primary {
            background: #E57393;
            color: white;
            box-shadow: 0 4px 12px rgba(229, 115, 147, 0.3);
            margin-bottom: 12px;
        }
        
        .btn-primary:active {
            transform: translateY(1px);
            box-shadow: 0 2px 6px rgba(229, 115, 147, 0.3);
        }
        
        .btn-secondary {
            background: white;
            color: #E57393;
            border: 2px solid #E57393;
        }
        
        .btn-secondary:active {
            background: #FFF5F7;
        }
        
        /* Coupon */
        .coupon-section {
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #F7F7F7;
        }
        
        .coupon-label {
            font-size: 14px;
            font-weight: 700;
            margin-bottom: 8px;
            display: block;
            color: #111111;
        }
        
        .coupon-input-group {
            display: flex;
            gap: 8px;
        }
        
        .coupon-input {
            flex: 1;
            padding: 12px;
            border: 1px solid #EFEFEF;
            border-radius: 12px;
            font-size: 15px;
            background: #F7F7F7;
        }
        
        .coupon-input:focus {
            outline: none;
            border-color: #E57393;
            background: white;
        }
        
        .coupon-btn {
            padding: 12px 20px;
            background: #E57393;
            color: white;
            border: none;
            border-radius: 12px;
            font-weight: 700;
            cursor: pointer;
            white-space: nowrap;
        }
        
        .coupon-btn:active {
            transform: scale(0.98);
        }
        
        .coupon-message {
            margin-top: 8px;
            font-size: 13px;
        }
        
        /* Empty Cart */
        .empty-cart {
            text-align: center;
            padding: 60px 20px;
            background: white;
            border-radius: 16px;
        }
        
        .empty-icon {
            width: 100px;
            height: 100px;
            margin: 0 auto 20px;
            border-radius: 50%;
            background: #F7F7F7;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 48px;
            color: #EFEFEF;
        }
        
        .empty-title {
            font-size: 24px;
            font-weight: 800;
            margin-bottom: 12px;
            color: #111111;
        }
        
        .empty-text {
            font-size: 15px;
            color: #767676;
            margin-bottom: 24px;
        }
        
        /* Responsive */
        @media (min-width: 768px) {
            .container {
                padding: 0 40px;
            }
            
            .cart-layout {
                grid-template-columns: 1fr 380px;
                gap: 24px;
            }
        
            .cart-summary {
                position: sticky;
                top: 90px;
            }
            
            .item-image {
                width: 100px;
                height: 100px;
            }
            
            .page-title {
                font-size: 32px;
            }
        }
        
        /* Toast Notification */
        .toast {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: #111111;
            color: white;
            padding: 12px 24px;
            border-radius: 50px;
            font-size: 14px;
            font-weight: 700;
            z-index: 1000;
            opacity: 0;
            transition: opacity 0.3s;
        }
        
        .toast.show {
            opacity: 1;
        }
        
        .toast.success {
            background: #10B981;
        }
        
        .toast.error {
            background: #EF4444;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="nav">
        <div class="nav-content">
            <button class="nav-back" onclick="window.history.back()">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M15 18l-6-6 6-6"/>
                </svg>
            </button>
            <a href="index.php" class="nav-logo"><?php echo htmlspecialchars($logo_text); ?></a>
            <div style="width: 40px;"></div>
        </div>
    </nav>

    <!-- Page Header -->
    <div class="page-header">
        <h1 class="page-title">سلة التسوق</h1>
        <p class="page-subtitle"><?php echo $cart_count; ?> منتج في السلة</p>
    </div>

    <!-- Cart Content -->
    <div class="container">
        <?php if (empty($cart_items)): ?>
            <!-- Empty Cart -->
            <div class="empty-cart">
                <div class="empty-icon">
                    <i class="fas fa-shopping-cart"></i>
                </div>
                <h2 class="empty-title">السلة فارغة</h2>
                <p class="empty-text">لم تقم بإضافة أي منتجات بعد</p>
                <a href="products.php" class="btn btn-primary" style="max-width: 300px; margin: 0 auto;">
                    <i class="fas fa-shopping-bag"></i>
                    تسوق الآن
                </a>
            </div>
        <?php else: ?>
            <div class="cart-layout">
                <!-- Cart Items -->
                <div class="cart-items">
                    <?php foreach ($cart_items as $item): ?>
                        <div class="cart-item">
                            <div class="item-image">
                                <?php
                                $image_path = $item['image'];
                                if (strpos($image_path, 'uploads/') === 0) {
                                    $image_path = '../' . $image_path;
                                } elseif (strpos($image_path, '../uploads/') !== 0) {
                                    $image_path = '../uploads/products/' . basename($image_path);
                                }
                                ?>
                                <img src="<?php echo htmlspecialchars($image_path); ?>" 
                                     alt="<?php echo htmlspecialchars($item['name']); ?>"
                                     onerror="this.src='../uploads/products/placeholder.svg'">
                            </div>
                            <div class="item-details">
                                <div class="item-name"><?php echo htmlspecialchars($item['name']); ?></div>
                                <div class="item-price"><?php echo number_format($item['price'], 0); ?> ج.م</div>
                                <div class="item-actions">
                                    <div class="quantity-control">
                                        <button class="qty-btn" onclick="updateQuantity(<?php echo $item['id']; ?>, -1)">
                                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                <line x1="5" y1="12" x2="19" y2="12"/>
                                            </svg>
                                        </button>
                                        <span class="qty-value" id="qty-<?php echo $item['id']; ?>"><?php echo $item['quantity']; ?></span>
                                        <button class="qty-btn" onclick="updateQuantity(<?php echo $item['id']; ?>, 1)">
                                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                <line x1="12" y1="5" x2="12" y2="19"/>
                                                <line x1="5" y1="12" x2="19" y2="12"/>
                                            </svg>
                                        </button>
                                    </div>
                                    <button class="remove-btn" onclick="removeItem(<?php echo $item['id']; ?>)">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

                <!-- Cart Summary -->
                <div class="cart-summary">
                    <h3 class="summary-title">ملخص الطلب</h3>
                    
                    <div class="summary-row">
                        <span class="summary-label">المجموع الفرعي</span>
                        <span class="summary-value"><?php echo number_format($total, 0); ?> ج.م</span>
                    </div>
                    
                    <?php if ($applied_coupon): ?>
                        <div class="summary-row">
                            <span class="summary-label">
                                <span style="display: flex; align-items: center; gap: 8px;">
                                    <i class="fas fa-tag"></i>
                                    خصم (<?php echo htmlspecialchars($applied_coupon['code']); ?>)
                                    <button onclick="removeCoupon()" style="background: transparent; border: none; color: #EF4444; cursor: pointer; font-size: 12px;">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </span>
                            </span>
                            <span style="font-weight: 700;">-<?php echo number_format($discount, 0); ?> ج.م</span>
                        </div>
                    <?php endif; ?>
                    
                    <div class="summary-row">
                        <span class="summary-label">الشحن</span>
                        <span class="summary-value" style="color: #10B981;">مجاني</span>
                    </div>
                    
                    <div class="summary-row">
                        <span class="summary-label" style="font-size: 17px; font-weight: 700; color: #111111;">الإجمالي</span>
                        <span class="summary-total" id="grandTotal"><?php echo number_format($final_total, 0); ?> ج.م</span>
                    </div>
                    
                    <div style="margin-top: 20px;">
                        <a href="checkout.php" class="btn btn-primary">
                            <i class="fas fa-credit-card"></i>
                            إتمام الطلب
                        </a>
                        <a href="products.php" class="btn btn-secondary">
                            <i class="fas fa-arrow-right"></i>
                            متابعة التسوق
                        </a>
                    </div>
                    
                    <?php if (!$applied_coupon): ?>
                        <div class="coupon-section">
                            <label class="coupon-label">كود الخصم</label>
                            <div class="coupon-input-group">
                                <input type="text" id="coupon-code" class="coupon-input" placeholder="أدخل الكود">
                                <button onclick="applyCoupon()" class="coupon-btn">تطبيق</button>
                            </div>
                            <div id="coupon-message" class="coupon-message"></div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Toast -->
    <div id="toast" class="toast"></div>

<script>
// Show Toast
function showToast(message, type = 'success') {
    const toast = document.getElementById('toast');
    toast.textContent = message;
    toast.className = 'toast show ' + type;
    
    setTimeout(() => {
        toast.className = 'toast';
    }, 3000);
}

// Update Quantity
function updateQuantity(itemId, change) {
    const qtyElement = document.getElementById('qty-' + itemId);
    let currentQty = parseInt(qtyElement.textContent);
    let newQty = currentQty + change;
    
    if (newQty < 1) return;
    
    fetch('../api/cart/update.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            item_id: itemId,
            quantity: newQty
        })
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            qtyElement.textContent = newQty;
            updateTotals();
            showToast('تم تحديث الكمية', 'success');
        }
    })
    .catch(() => {
        showToast('حدث خطأ', 'error');
    });
}

// Remove Item
function removeItem(itemId) {
    if (!confirm('هل تريد حذف هذا المنتج؟')) return;
    
    fetch('../api/cart/remove.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            item_id: itemId
        })
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            location.reload();
        }
    })
    .catch(() => {
        showToast('حدث خطأ', 'error');
    });
}

// Update Totals
function updateTotals() {
    location.reload();
}

// Apply Coupon
function applyCoupon() {
    const code = document.getElementById('coupon-code').value.trim();
    
    if (!code) {
        showCouponMessage('الرجاء إدخال كود الخصم', 'error');
        return;
    }
    
    const cartTotal = parseFloat(document.getElementById('subTotal').textContent.replace(/[^\d.]/g, ''));
    
    fetch('../api/apply_coupon.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: 'coupon_code=' + code + '&cart_total=' + cartTotal
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            showCouponMessage(data.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showCouponMessage(data.message, 'error');
        }
    })
    .catch(() => {
        showCouponMessage('حدث خطأ', 'error');
    });
}

// Remove Coupon
function removeCoupon() {
    fetch('../api/remove_coupon.php')
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            location.reload();       
        }
    });
}

// Show Coupon Message
function showCouponMessage(message, type) {
    const messageDiv = document.getElementById('coupon-message');
    messageDiv.textContent = message;
    messageDiv.className = 'coupon-message ' + (type === 'success' ? 'text-green-600' : 'text-red-600'); 
}
</script>

</body>
</html>
