<?php
// ============================================================
// FILE: keranjang_ajax.php — AJAX endpoint tambah ke keranjang
// Returns JSON: { success, jumlah_keranjang, pesan }
// ============================================================
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/auth.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'pesan' => 'Method tidak valid.']);
    exit;
}

$pdo      = db();
$sid      = session_id();
$produkId = (int)($_POST['produk_id'] ?? 0);

if (!$produkId) {
    echo json_encode(['success' => false, 'pesan' => 'Produk tidak ditemukan.']);
    exit;
}

$cekProd = $pdo->prepare("SELECT id, nama, stok FROM produk WHERE id=? AND is_aktif=1 LIMIT 1");
$cekProd->execute([$produkId]);
$prodData = $cekProd->fetch();

if (!$prodData || (float)$prodData['stok'] <= 0) {
    echo json_encode(['success' => false, 'pesan' => 'Stok habis atau produk tidak tersedia.']);
    exit;
}

// Cek apakah sudah ada di keranjang
$cek = $pdo->prepare("SELECT id, jumlah FROM keranjang WHERE session_id=? AND produk_id=?");
$cek->execute([$sid, $produkId]);
$existing = $cek->fetch();

if ($existing) {
    $newJml = min($existing['jumlah'] + 1, (float)$prodData['stok']);
    $pdo->prepare("UPDATE keranjang SET jumlah=? WHERE id=?")->execute([$newJml, $existing['id']]);
} else {
    $pdo->prepare("INSERT INTO keranjang (session_id, produk_id, jumlah) VALUES (?,?,1)")
        ->execute([$sid, $produkId]);
}

// Hitung total item di keranjang
$totalKeranjang = (int)$pdo->prepare("SELECT COALESCE(SUM(jumlah),0) FROM keranjang WHERE session_id=?")
    ->execute([$sid]) ? $pdo->prepare("SELECT COALESCE(SUM(jumlah),0) FROM keranjang WHERE session_id=?") : 0;
$stmtJml = $pdo->prepare("SELECT COALESCE(SUM(jumlah),0) FROM keranjang WHERE session_id=?");
$stmtJml->execute([$sid]);
$totalKeranjang = (int)$stmtJml->fetchColumn();

echo json_encode([
    'success'          => true,
    'pesan'            => htmlspecialchars($prodData['nama'], ENT_QUOTES) . ' ditambahkan ke keranjang.',
    'jumlah_keranjang' => $totalKeranjang,
]);
