<?php
session_start();
header('Content-Type: application/json');
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/auth.php';

if (!isLoggedIn()) { echo json_encode(['status'=>'error','message'=>'Silakan login.']); exit; }

$kelasId = (int)($_POST['kelas_id'] ?? 0);
$userId = $_SESSION['user_id'];

if ($kelasId <= 0) { echo json_encode(['status'=>'error','message'=>'ID kelas tidak valid.']); exit; }

// Check duplicate
$chk = $pdo->prepare("SELECT id FROM keranjang WHERE user_id = ? AND kelas_id = ?");
$chk->execute([$userId, $kelasId]);
if ($chk->fetch()) { echo json_encode(['status'=>'error','message'=>'Kelas sudah ada di keranjang.']); exit; }

// Check slot
$kls = $pdo->prepare("SELECT sisa_slot, nama_kelas FROM kelas WHERE id = ? AND status = 'aktif'");
$kls->execute([$kelasId]);
$kelas = $kls->fetch();
if (!$kelas) { echo json_encode(['status'=>'error','message'=>'Kelas tidak ditemukan.']); exit; }
if ($kelas['sisa_slot'] <= 0) { echo json_encode(['status'=>'error','message'=>'Slot sudah penuh.']); exit; }

// Insert
$pdo->prepare("INSERT INTO keranjang (user_id, kelas_id) VALUES (?, ?)")->execute([$userId, $kelasId]);

// Get updated cart info
$cnt = $pdo->prepare("SELECT COUNT(*) FROM keranjang WHERE user_id = ?");
$cnt->execute([$userId]);
$cartCount = (int)$cnt->fetchColumn();

$tot = $pdo->prepare("SELECT COALESCE(SUM(k.harga),0) FROM keranjang kr JOIN kelas k ON kr.kelas_id=k.id WHERE kr.user_id=?");
$tot->execute([$userId]);
$cartTotal = (int)$tot->fetchColumn();

echo json_encode(['status'=>'success','message'=>$kelas['nama_kelas'].' ditambahkan!','cart_count'=>$cartCount,'cart_total'=>$cartTotal]);
