<?php
/**
 * GET /api/cart/list.php
 * Returns the current user's cart lines (with live product info) plus a summary.
 * Lines whose product is no longer active, or whose requested quantity now
 * exceeds available stock, are flagged so the front-end can warn before checkout —
 * they are NOT auto-removed, since that would silently change what the user chose.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

$userId = require_login();

$pdo = Database::connect();

$stmt = $pdo->prepare('
    SELECT ci.id AS cart_item_id, ci.quantity AS cart_quantity,
           p.id AS product_id, p.name, p.selling_price, p.quantity AS stock, p.status, p.owner_id,
           (SELECT image_path FROM product_images pi WHERE pi.product_id = p.id ORDER BY sort_order ASC LIMIT 1) AS thumbnail
    FROM cart_items ci
    JOIN products p ON p.id = ci.product_id
    WHERE ci.user_id = ?
    ORDER BY ci.created_at DESC
');
$stmt->execute([$userId]);
$rows = $stmt->fetchAll();

$items = [];
$subtotal = 0;
$hasIssues = false;

foreach ($rows as $r) {
    $unavailable = $r['status'] !== 'active';
    $overStock = !$unavailable && ((int) $r['cart_quantity'] > (int) $r['stock']);
    if ($unavailable || $overStock) {
        $hasIssues = true;
    }

    $lineTotal = (float) $r['selling_price'] * (int) $r['cart_quantity'];
    if (!$unavailable && !$overStock) {
        $subtotal += $lineTotal;
    }

    $items[] = [
        'cart_item_id'   => (int) $r['cart_item_id'],
        'product_id'     => (int) $r['product_id'],
        'name'           => $r['name'],
        'unit_price'     => (float) $r['selling_price'],
        'quantity'       => (int) $r['cart_quantity'],
        'available_stock'=> (int) $r['stock'],
        'line_total'     => round($lineTotal, 2),
        'thumbnail_url'  => $r['thumbnail'] ? UPLOAD_URL . $r['thumbnail'] : null,
        'unavailable'    => $unavailable,
        'over_stock'     => $overStock,
    ];
}

send_json(true, 'OK', [
    'items' => $items,
    'summary' => [
        'item_count' => count($items),
        'subtotal'   => round($subtotal, 2),
        'has_issues' => $hasIssues,
    ],
]);
