<?php
// ========================================
// صفحه سبد خرید
// پروژه فروشگاه کیف‌لند
// ========================================

require_once 'config/database.php';
require_once 'config/settings.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';

$pageTitle = 'سبد خرید | کیف‌لند';
$settings = SiteSettings::getInstance();
$db = Database::getInstance()->getConnection();

Auth::trackVisit('cart');

$cartItems = [];
$total = 0;

if(Auth::isLoggedIn()) {
    $stmt = $db->prepare("SELECT c.*, p.name, p.price, p.discount_price, p.image, p.stock 
                          FROM cart c 
                          JOIN products p ON c.product_id = p.id 
                          WHERE c.user_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $cartItems = $stmt->fetchAll();
}

foreach($cartItems as &$item) {
    $item['final_price'] = $item['discount_price'] ?? $item['price'];
    $item['subtotal'] = $item['final_price'] * $item['quantity'];
    $total += $item['subtotal'];
}

// محاسبه هزینه ارسال و تخفیف
$shipping_cost = getShippingCost($total);
$discount_amount = 0;
$tax_amount = calculateTax($total, $settings->get('tax_rate'));
$final_total = $total + $shipping_cost + $tax_amount - $discount_amount;

// به‌روزرسانی سبد
if($_SERVER['REQUEST_METHOD'] === 'POST') {
    if(isset($_POST['update_cart'])) {
        foreach($_POST['quantity'] as $cart_id => $quantity) {
            $quantity = intval($quantity);
            if($quantity > 0) {
                $stmt = $db->prepare("UPDATE cart SET quantity = ? WHERE id = ? AND user_id = ?");
                $stmt->execute([$quantity, $cart_id, $_SESSION['user_id']]);
            } else {
                $stmt = $db->prepare("DELETE FROM cart WHERE id = ? AND user_id = ?");
                $stmt->execute([$cart_id, $_SESSION['user_id']]);
            }
        }
        header('Location: cart.php');
        exit;
    }
    
    if(isset($_POST['remove_item'])) {
        $cart_id = intval($_POST['remove_item']);
        $stmt = $db->prepare("DELETE FROM cart WHERE id = ? AND user_id = ?");
        $stmt->execute([$cart_id, $_SESSION['user_id']]);
        header('Location: cart.php');
        exit;
    }
}

include 'includes/header.php';
?>

<section class="cart-page">
    <h1>سبد خرید</h1>
    
    <?php if(count($cartItems) > 0): ?>
    <form method="POST" class="cart-form">
        <div class="cart-layout">
            <!-- لیست آیتم‌ها -->
            <div class="cart-items">
                <table class="cart-table">
                    <thead>
                        <tr>
                            <th>محصول</th>
                            <th>قیمت</th>
                            <th>تعداد</th>
                            <th>جمع کل</th>
                            <th>عملیات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($cartItems as $item): ?>
                        <tr>
                            <td>
                                <div class="cart-product">
                                    <img src="uploads/products/<?= $item['image'] ?>" 
                                         alt="<?= htmlspecialchars($item['name']) ?>" 
                                         onerror="this.src='assets/images/no-image.svg'">
                                    <div>
                                        <h4><?= htmlspecialchars($item['name']) ?></h4>
                                        <?php if($item['stock'] < $item['quantity']): ?>
                                        <span class="badge badge-warning">موجودی کافی نیست</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <?php if($item['discount_price']): ?>
                                <span style="text-decoration: line-through; color: var(--text-secondary); font-size: 0.9rem;"><?= formatPrice($item['price']) ?></span>
                                <br>
                                <?php endif; ?>
                                <strong><?= formatPrice($item['final_price']) ?></strong>
                            </td>
                            <td>
                                <input type="number" name="quantity[<?= $item['id'] ?>]" 
                                       value="<?= $item['quantity'] ?>" 
                                       min="1" max="<?= $item['stock'] ?>" 
                                       style="width: 60px; padding: 8px; border: 1px solid var(--border-color); border-radius: var(--radius-sm); text-align: center;">
                            </td>
                            <td><strong><?= formatPrice($item['subtotal']) ?></strong></td>
                            <td>
                                <button type="submit" name="remove_item" value="<?= $item['id'] ?>" 
                                        class="btn btn-danger btn-sm" 
                                        onclick="return confirm('آیا از حذف این محصول مطمئن هستید؟')">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                
                <div class="cart-actions">
                    <a href="products.php" class="btn btn-outline">
                        <i class="fas fa-arrow-right"></i>
                        ادامه خرید
                    </a>
                    <button type="submit" name="update_cart" class="btn btn-primary">
                        <i class="fas fa-sync"></i>
                        به‌روزرسانی سبد
                    </button>
                </div>
            </div>
            
            <!-- خلاصه سفارش -->
            <div class="cart-summary">
                <h3>خلاصه سفارش</h3>
                
                <div class="summary-row">
                    <span>جمع کل محصولات:</span>
                    <span><?= formatPrice($total) ?></span>
                </div>
                
                <?php if($discount_amount > 0): ?>
                <div class="summary-row discount">
                    <span>تخفیف:</span>
                    <span>-<?= formatPrice($discount_amount) ?></span>
                </div>
                <?php endif; ?>
                
                <div class="summary-row">
                    <span>هزینه ارسال:</span>
                    <span><?= $shipping_cost > 0 ? formatPrice($shipping_cost) : 'رایگان' ?></span>
                </div>
                
                <div class="summary-row">
                    <span>مالیات (<?= $settings->get('tax_rate') ?>٪):</span>
                    <span><?= formatPrice($tax_amount) ?></span>
                </div>
                
                <div class="summary-row total">
                    <span>مبلغ نهایی:</span>
                    <span><?= formatPrice($final_total) ?></span>
                </div>
                
                <?php if($total < $settings->get('free_shipping_threshold')): ?>
                <div class="free-shipping-progress">
                    <p>برای ارسال رایگان، <?= formatPrice($settings->get('free_shipping_threshold') - $total) ?> دیگر خرید کنید</p>
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: <?= min(100, ($total / $settings->get('free_shipping_threshold')) * 100) ?>%"></div>
                    </div>
                </div>
                <?php else: ?>
                <div class="free-shipping-achieved">
                    <i class="fas fa-check-circle"></i>
                    <span>ارسال شما رایگان است!</span>
                </div>
                <?php endif; ?>
                
                <a href="checkout.php" class="btn btn-primary btn-block btn-lg">
                    <i class="fas fa-credit-card"></i>
                    تکمیل خرید
                </a>
                
                <div class="trust-badges">
                    <div class="badge-item">
                        <i class="fas fa-shield-alt"></i>
                        <span>پرداخت امن</span>
                    </div>
                    <div class="badge-item">
                        <i class="fas fa-undo"></i>
                        <span>بازگشت ۷ روزه</span>
                    </div>
                    <div class="badge-item">
                        <i class="fas fa-headset"></i>
                        <span>پشتیبانی</span>
                    </div>
                </div>
            </div>
        </div>
    </form>
    <?php else: ?>
    <div class="empty-cart">
        <i class="fas fa-shopping-cart"></i>
        <h2>سبد خرید شما خالی است</h2>
        <p>می‌توانید از صفحه محصولات، کالای مورد نظر خود را انتخاب کنید</p>
        <a href="products.php" class="btn btn-primary btn-lg">
            <i class="fas fa-shopping-bag"></i>
            مشاهده محصولات
        </a>
    </div>
    <?php endif; ?>
</section>

<style>
.cart-page { padding: 40px 5%; min-height: 80vh; }
.cart-page h1 { margin-bottom: 30px; font-size: 2rem; }
.cart-layout { display: grid; grid-template-columns: 1fr 380px; gap: 30px; }
.cart-items { background: var(--bg-card); padding: 20px; border-radius: var(--radius-lg); border: 1px solid var(--border-color); }
.cart-table { width: 100%; border-collapse: collapse; }
.cart-table th { background: var(--bg-secondary); padding: 15px; text-align: right; font-weight: 600; color: var(--text-secondary); border-bottom: 2px solid var(--border-color); }
.cart-table td { padding: 20px 15px; border-bottom: 1px solid var(--border-color); vertical-align: middle; }
.cart-product { display: flex; align-items: center; gap: 15px; }
.cart-product img { width: 80px; height: 80px; object-fit: cover; border-radius: var(--radius-md); }
.cart-product h4 { font-size: 1rem; margin-bottom: 5px; }
.cart-actions { padding: 20px; display: flex; justify-content: space-between; gap: 10px; }
.cart-summary { background: var(--bg-card); padding: 25px; border-radius: var(--radius-lg); border: 1px solid var(--border-color); height: fit-content; position: sticky; top: 100px; }
.cart-summary h3 { margin-bottom: 20px; font-size: 1.3rem; }
.summary-row { display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px solid var(--border-color); }
.summary-row:last-child { border-bottom: none; }
.summary-row.total { font-size: 1.2rem; font-weight: bold; border-top: 2px solid var(--border-color); margin-top: 15px; padding-top: 15px; }
.empty-cart { text-align: center; padding: 80px 20px; }
.empty-cart i { font-size: 6rem; color: var(--text-secondary); margin-bottom: 30px; }
.empty-cart h2 { font-size: 1.8rem; margin-bottom: 15px; }
.empty-cart p { color: var(--text-secondary); margin-bottom: 30px; }
.free-shipping-progress { margin: 20px 0; padding: 15px; background: rgba(16, 185, 129, 0.1); border-radius: var(--radius-md); }
.free-shipping-progress p { margin-bottom: 10px; font-size: 0.9rem; }
.free-shipping-achieved { display: flex; align-items: center; gap: 10px; padding: 15px; background: rgba(16, 185, 129, 0.1); border-radius: var(--radius-md); color: var(--success); margin: 20px 0; }
.trust-badges { display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-top: 30px; padding-top: 20px; border-top: 1px solid var(--border-color); }
.badge-item { text-align: center; }
.badge-item i { font-size: 1.5rem; color: var(--primary); margin-bottom: 8px; }
.badge-item span { font-size: 0.8rem; color: var(--text-secondary); }
@media (max-width: 1024px) {
    .cart-layout { grid-template-columns: 1fr; }
    .cart-summary { position: static; }
    .cart-table { font-size: 0.9rem; }
    .cart-product img { width: 60px; height: 60px; }
}
</style>

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