<?php
/**
 * Shopping Cart Page
 * CMTC Shopping
 */
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/navbar.php';

$cart_items = [];
$total_price = 0;

if (isset($_SESSION['user_id'])) {
    $uid = intval($_SESSION['user_id']);
    $stmt_c = $db->prepare("
        SELECT ci.id as cart_item_id, ci.quantity, ci.color_id, ci.size_id,
               p.*,
               (SELECT image_path FROM product_images WHERE product_id = p.id AND is_main = 1 LIMIT 1) as main_image,
               pc.color_name, ps.size_name
        FROM cart_items ci
        JOIN carts c ON ci.cart_id = c.id
        JOIN products p ON ci.product_id = p.id
        LEFT JOIN product_colors pc ON ci.color_id = pc.id
        LEFT JOIN product_sizes ps ON ci.size_id = ps.id
        WHERE c.user_id = ?
        ORDER BY ci.id DESC
    ");
    $stmt_c->execute([$uid]);
    $db_items = $stmt_c->fetchAll();

    foreach ($db_items as $item) {
        $unit_price = !empty($item['promo_price']) ? floatval($item['promo_price']) : floatval($item['price']);
        $subtotal = $unit_price * intval($item['quantity']);
        $total_price += $subtotal;

        $cart_items[] = [
            'cart_item_id' => $item['cart_item_id'],
            'product' => $item,
            'quantity' => $item['quantity'],
            'color_name' => $item['color_name'],
            'size_name' => $item['size_name'],
            'unit_price' => $unit_price,
            'subtotal' => $subtotal
        ];
    }
}
?>

<div class="container my-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold mb-0"><i class="bi bi-cart3 text-primary me-2"></i>ตะกร้าสินค้าของคุณ</h3>
        <a href="<?php echo base_url('index.php'); ?>" class="btn btn-outline-primary btn-sm"><i class="bi bi-arrow-left me-1"></i>เลือกซื้อสินค้าเพิ่ม</a>
    </div>

    <?php if (count($cart_items) > 0): ?>
        <div class="row g-4">
            <div class="col-lg-8">
                <div class="card border-0 shadow-sm glass-card p-4">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead>
                                <tr>
                                    <th>สินค้า</th>
                                    <th class="text-center">จำนวน</th>
                                    <th class="text-end">ราคา</th>
                                    <th class="text-end">รวม</th>
                                    <th class="text-center">ลบ</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($cart_items as $c): ?>
                                    <tr>
                                         <td>
                                             <div class="d-flex align-items-center gap-3">
                                                 <?php if (!empty($c['product']['main_image'])): ?>
                                                     <img src="<?php echo base_url('uploads/products/' . sanitize($c['product']['main_image'])); ?>" class="rounded" width="55" height="55" style="object-fit: cover;">
                                                 <?php else: ?>
                                                     <div class="bg-light text-muted d-flex align-items-center justify-content-center rounded" style="width: 55px; height: 55px;"><i class="bi bi-image"></i></div>
                                                 <?php endif; ?>
                                                 <div>
                                                     <h6 class="fw-bold mb-0"><?php echo sanitize($c['product']['name']); ?></h6>
                                                     <div class="small text-muted">
                                                         <code>SKU: <?php echo sanitize($c['product']['sku']); ?></code>
                                                         <?php if (!empty($c['color_name']) || !empty($c['size_name'])): ?>
                                                             <span class="ms-2">
                                                                 <?php echo !empty($c['color_name']) ? 'สี: ' . sanitize($c['color_name']) : ''; ?>
                                                                 <?php echo !empty($c['size_name']) ? ' ไซส์: ' . sanitize($c['size_name']) : ''; ?>
                                                             </span>
                                                         <?php endif; ?>
                                                     </div>
                                                 </div>
                                             </div>
                                         </td>
                                         <td class="text-center fw-bold"><?php echo $c['quantity']; ?></td>
                                         <td class="text-end"><?php echo format_price($c['unit_price']); ?></td>
                                         <td class="text-end fw-bold text-primary"><?php echo format_price($c['subtotal']); ?></td>
                                         <td class="text-center">
                                             <button class="btn btn-sm btn-outline-danger btn-remove-cart" data-id="<?php echo $c['cart_item_id']; ?>">
                                                 <i class="bi bi-trash"></i>
                                             </button>
                                         </td>
                                     </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="col-lg-4">
                <div class="card border-0 shadow-sm glass-card p-4">
                    <h5 class="fw-bold mb-3">สรุปคำสั่งซื้อ</h5>
                    <div class="d-flex justify-content-between mb-2">
                        <span class="text-muted">ยอดรวมสินค้า</span>
                        <span class="fw-bold"><?php echo format_price($total_price); ?></span>
                    </div>
                    <div class="d-flex justify-content-between mb-3">
                        <span class="text-muted">ค่าจัดส่ง</span>
                        <span class="text-success fw-bold">ฟรี</span>
                    </div>
                    <hr>
                    <div class="d-flex justify-content-between mb-4">
                        <span class="fw-bold fs-5">ยอดชำระสุทธิ</span>
                        <span class="fw-bold fs-5 text-primary"><?php echo format_price($total_price); ?></span>
                    </div>

                    <?php if (isset($_SESSION['user_id'])): ?>
                        <a href="<?php echo base_url('views/checkout.php'); ?>" class="btn btn-primary w-100 py-2 fw-bold shadow">
                            <i class="bi bi-credit-card me-1"></i> ไปที่หน้าชำระเงิน
                        </a>
                    <?php else: ?>
                        <a href="<?php echo base_url('login.php'); ?>" class="btn btn-warning w-100 py-2 fw-bold shadow">
                            <i class="bi bi-box-arrow-in-right me-1"></i> กรุณาเข้าสู่ระบบก่อนสั่งซื้อ
                        </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    <?php else: ?>
        <div class="card border-0 shadow-sm glass-card p-5 text-center my-4">
            <i class="bi bi-cart-x text-muted mb-3" style="font-size: 4rem;"></i>
            <h4 class="fw-bold">ยังไม่มีสินค้าในตะกร้า</h4>
            <p class="text-muted">คุณยังไม่ได้เลือกสินค้าใดๆ ลงในตะกร้า</p>
            <div>
                <a href="<?php echo base_url('index.php'); ?>" class="btn btn-primary px-4 mt-2">
                    <i class="bi bi-bag-plus me-1"></i> เลือกชมสินค้าในร้าน
                </a>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
$(document).ready(function() {
    $('.btn-remove-cart').on('click', function() {
        var itemId = $(this).data('id');
        $.post('<?php echo base_url("api/cart_handler.php"); ?>', { action: 'remove', item_id: itemId }, function(res) {
            location.reload();
        }, 'json');
    });
});
</script>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
