<?php
/**
 * Shopping Cart View Page
 * Displays cart contents and allows quantity updates
 */

require __DIR__ . '/_bootstrap.php';

use Symfony\Component\HttpFoundation\Response;
use App\DBModel\ShoppingCartModel;
use App\DBModel\ProductModel;
use App\DBModel\ProductCategoryModel;
use App\DBModel\ProductImageModel;
use App\DBModel\ProductOptionAssignmentModel;
use App\DBModel\ProductOptionValueModel;
use App\Service\ShoppingCartService;
use App\Service\ProductService;

// Get models
$cartModel = new ShoppingCartModel($db);
$productModel = new ProductModel($db);
$productCategoryModel = new ProductCategoryModel($db);
$productImageModel = new ProductImageModel($db);
$productOptionAssignmentModel = new ProductOptionAssignmentModel($db);
$productOptionValueModel = new ProductOptionValueModel($db);

// Create ProductService
$productService = new ProductService(
    $productModel,
    $productCategoryModel,
    $productOptionAssignmentModel,
    $productOptionValueModel
);

// Create ShoppingCartService with ProductService dependency
$cartService = new ShoppingCartService(
    $cartModel,
    $productService,
    $db
);

try {
    // Get customer ID or session ID for cart
    $customerId = $customer['id'] ?? null;
    $sessionId = $session->getId();

    // Get cart items with full product details
    $cartItems = $cartService->getCartItems($customerId, $sessionId);

    // Calculate cart totals
    $totals = $cartService->calculateTotals($customerId, $sessionId);

    // Format cart items for display (slug already included from service)
    $formattedItems = [];
    foreach ($cartItems as $item) {
        $formattedItems[] = [
            'id'           => $item['cart_item_id'],
            'product_id'   => $item['product_id'],
            'product_name' => $item['product_name'],
            'product_sku'  => $item['product_sku'],
            'product_slug' => $item['product_slug'] ?? '',
            'product_image'=> $item['product_image'],
            'quantity'     => $item['quantity'],
            'price'        => $item['unit_price'],
            'options'      => $item['options_display'] ?? '',
            'subtotal'     => $item['subtotal'],
            'max_quantity' => $item['stock_qty'],
            'vendor_id'    => $item['vendor_id'],
            'vendor_name'  => $item['vendor_name'],
            'is_dropship'  => $item['is_dropship'],
        ];
    }

    $html = $twig->render('public/store/cart.html.twig', [
        'page_title'           => 'Shopping Cart - Malewitch Store',
        'cart_items'           => $formattedItems,
        'totals'               => $totals,
        'vendor_groups'        => $totals['vendor_groups'] ?? [],
        'has_multiple_vendors' => $totals['has_multiple_vendors'] ?? false,
        'cart_empty'           => empty($cartItems),
        'customer'             => $customer,
        'error_message'        => null
    ]);

    $response = new Response($html);
    $response->send();

} catch (Exception $e) {
    error_log("Shopping cart error: " . $e->getMessage());

    $html = $twig->render('public/store/cart.html.twig', [
        'page_title' => 'Shopping Cart',
        'cart_items' => [],
        'totals' => [
            'subtotal' => 0,
            'tax' => 0,
            'shipping' => 0,
            'total' => 0
        ],
        'cart_empty' => true,
        'error_message' => 'Unable to load cart. Please try again later.'
    ]);

    $response = new Response($html);
    $response->send();
}
