<?php
// kiosk_client.php (VERSI PERBAIKAN)

header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

require 'config.php'; // Tetap diperlukan untuk koneksi DB saat proses transaksi

// =================================================================
// FUNGSI HELPER (DIPINDAHKAN KE ATAS)
// =================================================================
/**
 * Menyajikan data dari cache lama jika ada, atau menampilkan pesan error.
 * @param string $cache_file Path ke file cache.
 */
function serve_stale_cache_or_fail($cache_file) {
    if (file_exists($cache_file)) {
        // Sajikan data lama dari cache
        readfile($cache_file);
    } else {
        // Gagal total, tidak ada koneksi dan tidak ada cache
        http_response_code(503); // Service Unavailable
        echo json_encode(['success' => false, 'error' => 'Tidak dapat terhubung ke server dan tidak ada data cache.']);
    }
}


// =================================================================
// PENANGANAN AKSI (ACTION HANDLER)
// =================================================================
$action = $_GET['action'] ?? $_POST['action'] ?? '';

// AKSI 1: MENGAMBIL DATA PRODUK (DENGAN CACHING)
if ($action === 'get_products') {
    // URL server cloud Anda
    $server_url = 'http://localhost/bener/kiosk/kiosk_server.php';
    $cache_file = 'products_cache.json';
    $cache_time_seconds = 60 * 5; // Cache berlaku selama 5 menit

    // Coba ambil dari cache terlebih dahulu jika masih valid
    if (file_exists($cache_file) && (time() - filemtime($cache_file) < $cache_time_seconds)) {
        readfile($cache_file);
        exit();
    }

    // Jika cache tidak valid, coba ambil dari server cloud
    $context = stream_context_create(['http' => ['timeout' => 10]]); // Timeout 10 detik
    $json_data = @file_get_contents($server_url, false, $context);

    if ($json_data !== false) {
        // Berhasil mengambil data dari server
        json_decode($json_data);
        if (json_last_error() === JSON_ERROR_NONE) {
            // Data valid, simpan ke cache
            file_put_contents($cache_file, $json_data);
            echo $json_data;
        } else {
            // Data dari server bukan JSON, gunakan cache lama jika ada
            serve_stale_cache_or_fail($cache_file);
        }
    } else {
        // Gagal terhubung ke server cloud, gunakan cache lama jika ada
        serve_stale_cache_or_fail($cache_file);
    }
} 

// AKSI 2: MEMPROSES TRANSAKSI (Logika ini tetap sama, karena terjadi di lokal)
elseif ($action === 'process_transaction') {
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        echo json_encode(['success' => false, 'error' => 'Koneksi database lokal gagal: ' . $conn->connect_error]);
        exit();
    }
    
    // --- MULAI PASTE KODE PROSES TRANSAKSI DARI kiosk_api.php LAMA DI SINI ---
    
    $cartData = json_decode($_POST['cartData'] ?? '{}', true);

    if (empty($cartData) || !isset($cartData['customerName']) || !isset($cartData['items']) || empty($cartData['items'])) {
        echo json_encode(['success' => false, 'error' => 'Data keranjang tidak lengkap atau tidak valid.']);
        $conn->close();
        exit();
    }

    $customerName = $cartData['customerName'];
    $customerPhone = $cartData['customerPhone'] ?? null;
    $items = $cartData['items'];
    $totalAmount = $cartData['total'];
    $brand = $cartData['brand'] ?? '001';
    $cab = $cartData['cab'] ?? '002';
    $transaction_code = 'TRX-' . time() . '-' . rand(100, 999);

    $conn->begin_transaction();

    try {
        // 1. Simpan header transaksi
        $stmtHeader = $conn->prepare("INSERT INTO transactions (transaction_code, customer_name, customer_phone, total_amount, brand, cab) VALUES (?, ?, ?, ?, ?, ?)");
        if (!$stmtHeader) throw new Exception("Prepare statement header gagal: " . $conn->error);
        
        $stmtHeader->bind_param("sssdss", $transaction_code, $customerName, $customerPhone, $totalAmount, $brand, $cab);
        $stmtHeader->execute();
        $transaction_id = $conn->insert_id;
        $stmtHeader->close();

        // 2. Loop melalui setiap item, simpan, dan potong stok
        $stmtItem = $conn->prepare("INSERT INTO transaction_items (transaction_id, product_id, variant_ref_id, product_name, quantity, price_per_item, item_details, brand, cab) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        if (!$stmtItem) throw new Exception("Prepare statement item gagal: " . $conn->error);
        
        $stmtUpdateStock = $conn->prepare("UPDATE product_variants SET stock = stock - ? WHERE id = ? AND stock >= ?");
        if (!$stmtUpdateStock) throw new Exception("Prepare statement update stok gagal: " . $conn->error);

        foreach ($items as $item) {
            $details = [
                'variant' => $item['variant'],
                'addons' => $item['addons'],
                'condiments' => $item['condiments'],
                'note' => $item['note']
            ];
            $item_details_json = json_encode($details);
            $variant_id = $item['variant']['id'];

            $stmtItem->bind_param("iisssisss", $transaction_id, $item['productId'], $variant_id, $item['name'], $item['quantity'], $item['finalPrice'], $item_details_json, $brand, $cab);
            $stmtItem->execute();

            $stmtUpdateStock->bind_param("iii", $item['quantity'], $variant_id, $item['quantity']);
            $stmtUpdateStock->execute();

            if ($stmtUpdateStock->affected_rows === 0) {
                throw new Exception("Stok untuk produk '" . $item['name'] . "' tidak mencukupi.");
            }
        }
        $stmtItem->close();
        $stmtUpdateStock->close();
        
        $conn->commit();
        echo json_encode(['success' => true, 'message' => 'Transaksi berhasil diproses.', 'transaction_code' => $transaction_code]);

    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    
    // --- AKHIR DARI PASTE KODE PROSES TRANSAKSI ---

    $conn->close();
}

// JIKA TIDAK ADA AKSI YANG SESUAI
else {
    http_response_code(400); // Bad Request
    echo json_encode(['success' => false, 'error' => 'Aksi tidak valid atau tidak disediakan.']);
}
?>