<?php
declare(strict_types=1);
header('Content-Type: application/json');
session_start();
if (!isset($_SESSION['cart_by_user'])) $_SESSION['cart_by_user'] = [];
$uid = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;

$dbHost = getenv('DB_HOST') ?: 'localhost';
$dbUser = getenv('DB_USER') ?: 'root';
$dbPass = getenv('DB_PASSWORD') ?: '';
$dbName = 'listbnb';

$action = $_GET['action'] ?? 'list';

if ($uid > 0) {
  try {
    $pdo = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4", $dbUser, $dbPass, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
    $pdo->exec('CREATE TABLE IF NOT EXISTS user_carts (
      user_id INT UNSIGNED NOT NULL,
      product_id INT UNSIGNED NOT NULL,
      qty INT UNSIGNED NOT NULL DEFAULT 1,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      UNIQUE KEY uc_unique (user_id, product_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
  } catch (Throwable $e) { $pdo = null; }
}

function respond(){
  $uid = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;
  $items = [];
  if ($uid > 0 && isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
    try {
      $stmt = $GLOBALS['pdo']->prepare('SELECT p.id, p.product_title, p.price, p.image1 FROM products p INNER JOIN user_carts uc ON uc.product_id = p.id WHERE uc.user_id = :u ORDER BY uc.created_at DESC');
      $stmt->execute([':u'=>$uid]);
      $items = $stmt->fetchAll();
    } catch (Throwable $e) {}
  } else {
    $items = isset($_SESSION['cart_by_user'][$uid]) ? array_values($_SESSION['cart_by_user'][$uid]) : [];
  }
  echo json_encode(['items'=>$items], JSON_UNESCAPED_SLASHES); exit;
}

if ($action === 'add') {
  $id = (int)($_POST['id'] ?? 0);
  if ($id > 0) {
    try {
      if ($uid > 0 && isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
        $stmt = $GLOBALS['pdo']->prepare('INSERT INTO user_carts(user_id, product_id, qty) VALUES(:u,:p,1) ON DUPLICATE KEY UPDATE qty=VALUES(qty), created_at=CURRENT_TIMESTAMP');
        $stmt->execute([':u'=>$uid, ':p'=>$id]);
      } else {
        $pdo2 = new PDO("mysql:host={$GLOBALS['dbHost']};dbname={$GLOBALS['dbName']};charset=utf8mb4", $GLOBALS['dbUser'], $GLOBALS['dbPass'], [
          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
          PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);
        $stmt = $pdo2->prepare('SELECT id, product_title, price, image1 FROM products WHERE id = :id');
        $stmt->execute([':id'=>$id]);
        $p = $stmt->fetch();
        if ($p) { if (!isset($_SESSION['cart_by_user'][$uid])) $_SESSION['cart_by_user'][$uid] = []; $_SESSION['cart_by_user'][$uid][$id] = $p; }
      }
    } catch (Throwable $e) {}
  }
  respond();
} elseif ($action === 'remove') {
  $id = (int)($_POST['id'] ?? 0);
  if ($uid > 0 && isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
    try {
      $stmt = $GLOBALS['pdo']->prepare('DELETE FROM user_carts WHERE user_id=:u AND product_id=:p');
      $stmt->execute([':u'=>$uid, ':p'=>$id]);
    } catch (Throwable $e) {}
  }
  if (isset($_SESSION['cart_by_user'][$uid])) { unset($_SESSION['cart_by_user'][$uid][$id]); }
  respond();
} else { // list
  respond();
}
