<?php
/**
 * قالب سبد خرید Dima Shop
 * نسخه: 1.0.0
 */
if (!defined('ABSPATH')) exit;

$cart = Dima_Cart::get_instance();
$items = $cart->get_items();
$subtotal = $cart->get_total();
$coupon_discount = $cart->get_coupon_discount();
$coupon_code = $cart->get_coupon_code();
$final_total = $subtotal - $coupon_discount;
$currency = get_option('dima_currency', 'تومان');
$shop_url = get_permalink(get_option('dima_shop_page'));
$checkout_url = get_permalink(get_option('dima_checkout_page'));

do_action('dima_before_cart');
?>

<div class="dima-cart-page" dir="rtl">
    
    <?php if (empty($items)): ?>
        <!-- حالت خالی -->
        <div class="cart-empty">
            <div class="cart-empty-icon">🛒</div>
            <h2>سبد خرید شما خالی است</h2>
            <p>برای شروع خرید، به فروشگاه مراجعه کنید</p>
            <a href="<?php echo esc_url($shop_url); ?>" class="btn btn-primary btn-large">
                🛍️ مشاهده محصولات
            </a>
        </div>
    <?php else: ?>
        
        <div class="cart-header">
            <h1>🛒 سبد خرید شما</h1>
            <span class="cart-count-badge"><?php echo $cart->get_item_count(); ?> محصول</span>
        </div>
        
        <div class="cart-layout">
            
            <!-- آیتم‌های سبد -->
            <div class="cart-items-section">
                
                <!-- هدر جدول (دسکتاپ) -->
                <div class="cart-table-header">
                    <div class="col-product">محصول</div>
                    <div class="col-price">قیمت</div>
                    <div class="col-quantity">تعداد</div>
                    <div class="col-total">جمع</div>
                    <div class="col-action">حذف</div>
                </div>
                
                <!-- آیتم‌ها -->
                <?php foreach ($items as $item): ?>
                <div class="cart-item" data-product-id="<?php echo esc_attr($item['product_id']); ?>">
                    
                    <!-- تصویر و نام -->
                    <div class="col-product">
                        <div class="product-thumb">
                            <?php if (!empty($item['image'])): ?>
                                <img src="<?php echo esc_url($item['image']); ?>" alt="<?php echo esc_attr($item['title']); ?>">
                            <?php else: ?>
                                <div class="no-image">📦</div>
                            <?php endif; ?>
                        </div>
                        <div class="product-info">
                            <a href="<?php echo esc_url($item['url']); ?>" class="product-title">
                                <?php echo esc_html($item['title']); ?>
                            </a>
                            <?php if (isset($item['original_price']) && $item['original_price'] > $item['price']): ?>
                                <div class="product-discount">
                                    <span class="original-price"><?php echo number_format($item['original_price']); ?></span>
                                    <span class="discount-badge">
                                        -<?php echo round((($item['original_price'] - $item['price']) / $item['original_price']) * 100); ?>٪
                                    </span>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <!-- قیمت واحد -->
                    <div class="col-price">
                        <span class="price-value"><?php echo number_format($item['price']); ?></span>
                        <span class="price-currency"><?php echo esc_html($currency); ?></span>
                    </div>
                    
                    <!-- تعداد -->
                    <div class="col-quantity">
                        <div class="quantity-control">
                            <button type="button" class="qty-btn qty-decrease" data-product-id="<?php echo esc_attr($item['product_id']); ?>">−</button>
                            <input type="number" class="qty-input" value="<?php echo intval($item['quantity']); ?>" min="1" max="99" data-product-id="<?php echo esc_attr($item['product_id']); ?>">
                            <button type="button" class="qty-btn qty-increase" data-product-id="<?php echo esc_attr($item['product_id']); ?>">+</button>
                        </div>
                    </div>
                    
                    <!-- جمع -->
                    <div class="col-total">
                        <span class="total-value"><?php echo number_format($item['subtotal']); ?></span>
                        <span class="total-currency"><?php echo esc_html($currency); ?></span>
                    </div>
                    
                    <!-- حذف -->
                    <div class="col-action">
                        <button type="button" class="remove-btn" data-product-id="<?php echo esc_attr($item['product_id']); ?>" title="حذف از سبد">
                            🗑️
                        </button>
                    </div>
                    
                </div>
                <?php endforeach; ?>
                
                <!-- دکمه‌های پایین -->
                <div class="cart-actions-bottom">
                    <a href="<?php echo esc_url($shop_url); ?>" class="btn btn-outline">
                        ← ادامه خرید
                    </a>
                    <button type="button" class="btn btn-link-delete" id="clear-cart-btn">
                        🗑️ پاک کردن سبد
                    </button>
                </div>
                
            </div>
            
            <!-- خلاصه سفارش -->
            <div class="cart-summary-section">
                <div class="summary-card">
                    <h3>📋 خلاصه سفارش</h3>
                    
                    <div class="summary-row">
                        <span>جمع کل:</span>
                        <span class="summary-value"><?php echo number_format($subtotal); ?> <?php echo esc_html($currency); ?></span>
                    </div>
                    
                    <?php if ($coupon_discount > 0): ?>
                    <div class="summary-row discount-row">
                        <span>تخفیف (<?php echo esc_html($coupon_code); ?>):</span>
                        <span class="summary-value discount-value">-<?php echo number_format($coupon_discount); ?> <?php echo esc_html($currency); ?></span>
                    </div>
                    <?php endif; ?>
                    
                    <div class="summary-row final-row">
                        <span><strong>مبلغ قابل پرداخت:</strong></span>
                        <span class="summary-value final-value">
                            <strong><?php echo number_format($final_total); ?> <?php echo esc_html($currency); ?></strong>
                        </span>
                    </div>
                    
                    <!-- بخش کوپن -->
                    <div class="coupon-section">
                        <label>🎟️ کد تخفیف:</label>
                        <div class="coupon-input-group">
                            <input type="text" id="coupon-code" placeholder="کد تخفیف را وارد کنید" value="<?php echo esc_attr($coupon_code); ?>" <?php echo $coupon_code ? 'disabled' : ''; ?>>
                            <?php if ($coupon_code): ?>
                                <button type="button" class="btn btn-small btn-link-delete" id="remove-coupon-btn">حذف</button>
                            <?php else: ?>
                                <button type="button" class="btn btn-primary" id="apply-coupon-btn">اعمال</button>
                            <?php endif; ?>
                        </div>
                        <div id="coupon-message" class="coupon-message"></div>
                    </div>
                    
                    <!-- دکمه پرداخت -->
                    <a href="<?php echo esc_url($checkout_url); ?>" class="btn btn-primary btn-block btn-large checkout-btn">
                        💳 ادامه و پرداخت
                    </a>
                    
                    <!-- نمادهای اعتماد -->
                    <div class="trust-badges">
                        <div class="trust-item">
                            <span class="trust-icon"></span>
                            <span>پرداخت امن</span>
                        </div>
                        <div class="trust-item">
                            <span class="trust-icon">🚚</span>
                            <span>ارسال سریع</span>
                        </div>
                        <div class="trust-item">
                            <span class="trust-icon">✅</span>
                            <span>ضمانت اصالت</span>
                        </div>
                    </div>
                    
                </div>
            </div>
            
        </div>
        
    <?php endif; ?>
    
</div>

<style>
.dima-cart-page {
    max-width: 1200px;
    margin: 0 auto;
    padding: 30px 20px;
    font-family: 'Vazir', Tahoma, sans-serif;
}

/* Empty State */
.cart-empty {
    text-align: center;
    padding: 80px 20px;
    background: white;
    border-radius: 20px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.06);
}
.cart-empty-icon {
    font-size: 80px;
    margin-bottom: 20px;
    opacity: 0.6;
}
.cart-empty h2 {
    font-size: 24px;
    color: #1f2937;
    margin-bottom: 10px;
}
.cart-empty p {
    color: #6b7280;
    margin-bottom: 30px;
}

/* Header */
.cart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 2px solid #e5e7eb;
}
.cart-header h1 {
    font-size: 28px;
    color: #1f2937;
    margin: 0;
}
.cart-count-badge {
    background: linear-gradient(135deg, #6366f1, #a855f7);
    color: white;
    padding: 6px 16px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 700;
}

/* Layout */
.cart-layout {
    display: grid;
    grid-template-columns: 1fr 380px;
    gap: 30px;
}

@media (max-width: 968px) {
    .cart-layout {
        grid-template-columns: 1fr;
    }
}

/* Cart Items */
.cart-items-section {
    background: white;
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.06);
}

/* Table Header (Desktop) */
.cart-table-header {
    display: grid;
    grid-template-columns: 2fr 1fr 1fr 1fr 60px;
    gap: 15px;
    padding: 12px 16px;
    background: #f9fafb;
    border-radius: 10px;
    font-weight: 700;
    font-size: 13px;
    color: #6b7280;
    margin-bottom: 15px;
}

@media (max-width: 768px) {
    .cart-table-header { display: none; }
}

/* Cart Item */
.cart-item {
    display: grid;
    grid-template-columns: 2fr 1fr 1fr 1fr 60px;
    gap: 15px;
    padding: 20px 16px;
    border-bottom: 1px solid #f3f4f6;
    align-items: center;
    transition: background 0.2s;
}

.cart-item:hover {
    background: #f9fafb;
}

.cart-item:last-child {
    border-bottom: none;
}

@media (max-width: 768px) {
    .cart-item {
        grid-template-columns: 1fr;
        gap: 12px;
        padding: 20px;
        background: #f9fafb;
        border-radius: 12px;
        margin-bottom: 12px;
        border: 1px solid #e5e7eb;
    }
}

/* Product Column */
.col-product {
    display: flex;
    align-items: center;
    gap: 15px;
}

.product-thumb {
    width: 80px;
    height: 80px;
    border-radius: 12px;
    overflow: hidden;
    background: #f3f4f6;
    flex-shrink: 0;
}

.product-thumb img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.product-thumb .no-image {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32px;
}

.product-info {
    flex: 1;
    min-width: 0;
}

.product-title {
    display: block;
    font-weight: 700;
    color: #1f2937;
    text-decoration: none;
    margin-bottom: 6px;
    font-size: 15px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.product-title:hover {
    color: #6366f1;
}

.product-discount {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 13px;
}

.original-price {
    color: #9ca3af;
    text-decoration: line-through;
}

.discount-badge {
    background: #ef4444;
    color: white;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 700;
}

/* Price */
.col-price, .col-total {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.price-value, .total-value {
    font-weight: 700;
    color: #1f2937;
    font-size: 15px;
}

.price-currency, .total-currency {
    font-size: 12px;
    color: #6b7280;
}

/* Quantity */
.quantity-control {
    display: flex;
    align-items: center;
    gap: 0;
    background: #f3f4f6;
    border-radius: 10px;
    overflow: hidden;
    width: fit-content;
}

.qty-btn {
    width: 36px;
    height: 36px;
    border: none;
    background: transparent;
    cursor: pointer;
    font-size: 18px;
    font-weight: 700;
    color: #4b5563;
    transition: all 0.2s;
}

.qty-btn:hover {
    background: #6366f1;
    color: white;
}

.qty-input {
    width: 50px;
    height: 36px;
    border: none;
    background: white;
    text-align: center;
    font-weight: 700;
    font-size: 15px;
    color: #1f2937;
}

.qty-input:focus {
    outline: none;
}

/* Remove Button */
.remove-btn {
    width: 40px;
    height: 40px;
    border: none;
    background: #fee2e2;
    border-radius: 10px;
    cursor: pointer;
    font-size: 18px;
    transition: all 0.2s;
}

.remove-btn:hover {
    background: #ef4444;
    transform: scale(1.1);
}

/* Bottom Actions */
.cart-actions-bottom {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #e5e7eb;
}

/* Summary Card */
.summary-card {
    background: white;
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.06);
    position: sticky;
    top: 100px;
}

.summary-card h3 {
    font-size: 18px;
    color: #1f2937;
    margin: 0 0 20px 0;
    padding-bottom: 15px;
    border-bottom: 2px solid #f3f4f6;
}

.summary-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f3f4f6;
    font-size: 14px;
}

.summary-row:last-of-type {
    border-bottom: none;
}

.summary-value {
    font-weight: 700;
    color: #1f2937;
}

.discount-row {
    color: #10b981;
}

.discount-value {
    color: #10b981;
}

.final-row {
    background: linear-gradient(135deg, #eef2ff, #faf5ff);
    padding: 16px;
    border-radius: 12px;
    margin: 15px 0;
    border-bottom: none;
}

.final-value {
    font-size: 20px;
    color: #6366f1;
}

/* Coupon */
.coupon-section {
    margin: 20px 0;
}

.coupon-section label {
    display: block;
    font-weight: 700;
    font-size: 14px;
    color: #374151;
    margin-bottom: 8px;
}

.coupon-input-group {
    display: flex;
    gap: 8px;
}

.coupon-input-group input {
    flex: 1;
    padding: 10px 14px;
    border: 2px solid #e5e7eb;
    border-radius: 10px;
    font-family: inherit;
    font-size: 14px;
}

.coupon-input-group input:focus {
    outline: none;
    border-color: #6366f1;
}

.coupon-message {
    margin-top: 8px;
    font-size: 13px;
    min-height: 20px;
}

.coupon-message.success {
    color: #10b981;
}

.coupon-message.error {
    color: #ef4444;
}

/* Checkout Button */
.checkout-btn {
    margin-top: 20px;
    text-align: center;
    text-decoration: none;
}

/* Trust Badges */
.trust-badges {
    display: flex;
    flex-direction: column;
    gap: 10px;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #e5e7eb;
}

.trust-item {
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 13px;
    color: #6b7280;
}

.trust-icon {
    font-size: 18px;
}

/* Buttons */
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 10px 20px;
    border-radius: 10px;
    font-family: inherit;
    font-weight: 600;
    font-size: 14px;
    cursor: pointer;
    border: none;
    text-decoration: none;
    transition: all 0.2s;
}

.btn-primary {
    background: linear-gradient(135deg, #6366f1, #a855f7);
    color: white;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(99, 102, 241, 0.3);
}

.btn-outline {
    background: white;
    color: #6366f1;
    border: 2px solid #6366f1;
}

.btn-outline:hover {
    background: #6366f1;
    color: white;
}

.btn-link-delete {
    background: transparent;
    color: #ef4444;
}

.btn-link-delete:hover {
    background: #fee2e2;
}

.btn-block {
    width: 100%;
}

.btn-large {
    padding: 14px 28px;
    font-size: 16px;
}

.btn-small {
    padding: 6px 12px;
    font-size: 12px;
}

/* Loading */
.cart-item.loading {
    opacity: 0.5;
    pointer-events: none;
}

/* Animations */
@keyframes fadeOut {
    from { opacity: 1; transform: translateX(0); }
    to { opacity: 0; transform: translateX(50px); }
}

.cart-item.removing {
    animation: fadeOut 0.3s ease forwards;
}
</style>

<script>
jQuery(document).ready(function($) {
    
    // افزایش تعداد
    $(document).on('click', '.qty-increase', function() {
        var productId = $(this).data('product-id');
        var $input = $(this).siblings('.qty-input');
        var newQty = parseInt($input.val()) + 1;
        updateQuantity(productId, newQty);
    });
    
    // کاهش تعداد
    $(document).on('click', '.qty-decrease', function() {
        var productId = $(this).data('product-id');
        var $input = $(this).siblings('.qty-input');
        var newQty = parseInt($input.val()) - 1;
        if (newQty < 1) newQty = 1;
        updateQuantity(productId, newQty);
    });
    
    // تغییر دستی تعداد
    $(document).on('change', '.qty-input', function() {
        var productId = $(this).data('product-id');
        var newQty = parseInt($(this).val());
        if (isNaN(newQty) || newQty < 1) newQty = 1;
        if (newQty > 99) newQty = 99;
        updateQuantity(productId, newQty);
    });
    
    // حذف محصول
    $(document).on('click', '.remove-btn', function() {
        var productId = $(this).data('product-id');
        var $item = $(this).closest('.cart-item');
        
        if (!confirm('آیا از حذف این محصول مطمئن هستید؟')) return;
        
        $item.addClass('removing');
        
        setTimeout(function() {
            $.ajax({
                url: dima_shop.ajax_url,
                type: 'POST',
                data: {
                    action: 'dima_update_cart',
                    product_id: productId,
                    quantity: 0,
                    nonce: dima_shop.nonce
                },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    }
                }
            });
        }, 300);
    });
    
    // اعمال کوپن
    $('#apply-coupon-btn').on('click', function() {
        var code = $('#coupon-code').val().trim();
        var $btn = $(this);
        var $msg = $('#coupon-message');
        
        if (!code) {
            $msg.html('<span style="color:#ef4444;">لطفاً کد تخفیف را وارد کنید</span>');
            return;
        }
        
        $btn.prop('disabled', true).text('در حال بررسی...');
        
        $.ajax({
            url: dima_shop.ajax_url,
            type: 'POST',
            data: {
                action: 'dima_apply_coupon',
                coupon_code: code,
                nonce: dima_shop.nonce
            },
            success: function(response) {
                if (response.success) {
                    $msg.html('<span style="color:#10b981;">✅ ' + response.data.message + '</span>').addClass('success');
                    setTimeout(function() { location.reload(); }, 1000);
                } else {
                    $msg.html('<span style="color:#ef4444;"> ' + response.data.message + '</span>').addClass('error');
                    $btn.prop('disabled', false).text('اعمال');
                }
            }
        });
    });
    
    // حذف کوپن
    $('#remove-coupon-btn').on('click', function() {
        if (!confirm('حذف کد تخفیف؟')) return;
        
        $.ajax({
            url: dima_shop.ajax_url,
            type: 'POST',
            data: {
                action: 'dima_remove_coupon',
                nonce: dima_shop.nonce
            },
            success: function(response) {
                if (response.success) location.reload();
            }
        });
    });
    
    // پاک کردن کل سبد
    $('#clear-cart-btn').on('click', function() {
        if (!confirm('آیا از پاک کردن تمام محصولات سبد مطمئن هستید؟')) return;
        
        // حذف همه آیتم‌ها
        $('.remove-btn').first().click();
    });
    
    // تابع به‌روزرسانی تعداد
    function updateQuantity(productId, quantity) {
        var $item = $('.cart-item[data-product-id="' + productId + '"]');
        $item.addClass('loading');
        
        $.ajax({
            url: dima_shop.ajax_url,
            type: 'POST',
            data: {
                action: 'dima_update_cart',
                product_id: productId,
                quantity: quantity,
                nonce: dima_shop.nonce
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    $item.removeClass('loading');
                    alert(response.data.message || 'خطا در بروزرسانی');
                }
            },
            error: function() {
                $item.removeClass('loading');
                alert('خطا در ارتباط با سرور');
            }
        });
    }
    
});
</script>

<?php do_action('dima_after_cart'); ?>