<?php
// Menekan output notice/warning dari PHP agar tidak merusak format JSON
error_reporting(0);
ini_set('display_errors', 0);

header('Content-Type: application/json');
require 'config.php'; // Pastikan file ini ada dan benar

// Cek apakah variabel koneksi dari config.php sudah ada, jika tidak, buat baru.
if (!isset($conn) || !$conn) {
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        http_response_code(500);
        die(json_encode(['success' => false, 'error' => 'Koneksi database gagal: ' . $conn->connect_error]));
    }
}
$conn->set_charset('utf8mb4');

// =========================================================================
// Logika untuk mendeteksi 'action' dari GET atau POST (JSON body)
// =========================================================================
$action = $_GET['action'] ?? '';
$request_data = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $json_data = file_get_contents("php://input");
    $decoded_data = json_decode($json_data, true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($decoded_data)) {
        $request_data = $decoded_data;
        $action = $request_data['action'] ?? $action;
    }
}
// =========================================================================


if ($action === 'get_products_list') {
    // FUNGSI UNTUK MEMUAT SEMUA PRODUK SEKALIGUS
    
    // PERBAIKI QUERY INI UNTUK MENGAMBIL KOLOM BARU
    $sql = "SELECT p.id, p.name, p.base_price, p.image_url, p.stock, p.rating, 
                   p.review_count, p.sold_count, p.last_update, 
                   p.is_bestseller, p.promo_type, p.promo_value,
                   c.name as category_name, c.id as category_id
            FROM products p
            LEFT JOIN categories c ON p.category_id = c.id";
            
    $where_clauses = [];
    $params = [];
    $types = '';

    // Filter berdasarkan pencarian masih bisa digunakan
    if (!empty($_GET['q'])) {
        $where_clauses[] = "LOWER(p.name) LIKE LOWER(?)";
        $params[] = '%' . $_GET['q'] . '%';
        $types .= 's';
    }

    if (count($where_clauses) > 0) {
        $sql .= " WHERE " . implode(' AND ', $where_clauses);
    }
    
    // Diurutkan berdasarkan kategori agar pengelompokan di frontend konsisten
    $sql .= " ORDER BY c.name, p.name";
    
    $stmt = $conn->prepare($sql);
    if ($stmt) {
        if ($types) {
            $stmt->bind_param($types, ...$params);
        }
        $stmt->execute();
        $result = $stmt->get_result();
        $products = $result->fetch_all(MYSQLI_ASSOC);
        echo json_encode($products);
    } else {
        // Jika query gagal, kirim pesan error yang jelas
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => 'Query produk gagal: ' . $conn->error]);
    }

} elseif ($action === 'get_product_details') {
    $product_id = $_GET['id'] ?? 0;
    if (!$product_id || !is_numeric($product_id)) {
        http_response_code(400);
        die(json_encode(['success' => false, 'error' => 'ID produk tidak valid']));
    }
    
    $response = [];
    $stmt = $conn->prepare("SELECT p.*, b.name as brand_name, c.name as category_name FROM products p LEFT JOIN brands b ON p.brand_id = b.id LEFT JOIN categories c ON p.category_id = c.id WHERE p.id = ?");
    $stmt->bind_param("i", $product_id);
    $stmt->execute();
    $product_data = $stmt->get_result()->fetch_assoc();
    
    if (!$product_data) {
        http_response_code(404);
        die(json_encode(['success' => false, 'error' => 'Produk tidak ditemukan']));
    }
    
    $response = $product_data;
    $stmt->close();

    $stmt_variants = $conn->prepare("SELECT * FROM product_variants WHERE product_id = ?");
    $stmt_variants->bind_param("i", $product_id);
    $stmt_variants->execute();
    $variants_result = $stmt_variants->get_result()->fetch_all(MYSQLI_ASSOC);
    $response['variants'] = [];
    foreach ($variants_result as $variant) {
        $variant['attributes'] = json_decode($variant['attributes'], true);
        $response['variants'][] = $variant;
    }
    $stmt_variants->close();
    
    $stmt_addons = $conn->prepare("SELECT a.id, a.name, a.price FROM product_addons pa JOIN addons a ON pa.addon_id = a.id WHERE pa.product_id = ?");
    $stmt_addons->bind_param("i", $product_id);
    $stmt_addons->execute();
    $response['addons'] = $stmt_addons->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_addons->close();

    $stmt_groups = $conn->prepare("SELECT * FROM condiment_groups WHERE product_id = ?");
    $stmt_groups->bind_param("i", $product_id);
    $stmt_groups->execute();
    $condiment_groups = $stmt_groups->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_groups->close();

    foreach($condiment_groups as $key => $group) {
        $stmt_options = $conn->prepare("SELECT * FROM condiment_options WHERE group_id = ?");
        $stmt_options->bind_param("i", $group['id']);
        $stmt_options->execute();
        $condiment_groups[$key]['options'] = $stmt_options->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt_options->close();
    }
    $response['condiment_groups'] = $condiment_groups;
    
    echo json_encode($response);

} elseif ($action === 'get_initial_data') {
    $categories_q = $conn->query("SELECT id, name FROM categories ORDER BY name ASC");
    $vouchers_q = $conn->query("SELECT * FROM vouchers WHERE is_active = 1 AND CURDATE() BETWEEN start_date AND end_date");
    $data = [ 'categories' => $categories_q->fetch_all(MYSQLI_ASSOC), 'vouchers' => $vouchers_q->fetch_all(MYSQLI_ASSOC) ];
    echo json_encode($data);

} elseif ($action === 'get_meja') {
    $result = $conn->query("SELECT id, nama_meja, area, kode_meja FROM meja ORDER BY area, id");
    if ($result) {
        echo json_encode($result->fetch_all(MYSQLI_ASSOC));
    } else {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => 'Gagal mengambil data meja']);
    }

} elseif ($action === 'login') {
    $username = $request_data['username'] ?? '';
    $password = $request_data['password'] ?? '';
    if (empty($username) || empty($password)) {
        http_response_code(400);
        die(json_encode(['success' => false, 'error' => 'Username dan password wajib diisi.']));
    }
    $stmt = $conn->prepare("SELECT id, username, full_name, password FROM users WHERE username = ? LIMIT 1");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($user = $result->fetch_assoc()) {
        if (password_verify($password, $user['password'])) {
            echo json_encode(['success' => true, 'user' => ['id' => $user['id'], 'username' => $user['username'], 'fullName' => $user['full_name']]]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Password salah.']);
        }
    } else {
        echo json_encode(['success' => false, 'error' => 'Username tidak ditemukan.']);
    }
    $stmt->close();

} elseif ($action === 'save_transaction') {
    $cart = $request_data['cart'] ?? [];
    if (empty($cart)) {
        http_response_code(400);
        die(json_encode(['success' => false, 'error' => 'Keranjang kosong.']));
    }

    $customerName = $request_data['customerName'] ?? 'Tamu';
    $mejaId = $request_data['mejaId'] ?? null;
    $userId = $request_data['userId'] ?? null;
    $totalAmount = $request_data['totalAmount'] ?? 0; // Ambil totalAmount
    $discountAmount = $request_data['discountAmount'] ?? 0; // Ambil discountAmount
    $finalAmount = $request_data['finalAmount'] ?? 0;
    $paymentMethodId = $request_data['paymentMethodId'] ?? null;
    $cartSnapshot = $request_data['cartSnapshot'] ?? '[]';
    $transaction_code = 'MB-' . time();

    $conn->begin_transaction();

    try {
        // PERBAIKAN 1: Tambahkan kolom total_amount dan discount_amount
        $stmtHeader = $conn->prepare("INSERT INTO transactions (transaction_code, customer_name, user_id, meja_id, total_amount, discount_amount, final_amount, status, payment_method_id, cart_snapshot) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)");
        if (!$stmtHeader) {
            throw new Exception("Prepare statement header gagal: " . $conn->error);
        }
        
        // PERBAIKAN 2: Sesuaikan tipe dan jumlah variabel di bind_param
        // Tipe: ssiidd dis  (9 tipe)
        // Variabel: 9 variabel
        $stmtHeader->bind_param("ssiiddids", $transaction_code, $customerName, $userId, $mejaId, $totalAmount, $discountAmount, $finalAmount, $paymentMethodId, $cartSnapshot);
        
        if (!$stmtHeader->execute()) {
            throw new Exception("Eksekusi statement header gagal: " . $stmtHeader->error);
        }
        $transaction_id = $conn->insert_id;
        $stmtHeader->close();

        // Sisa kode tidak perlu diubah...
        $stmtItem = $conn->prepare("INSERT INTO transaction_items (transaction_id, product_id, product_name, quantity, price_per_item, item_details) VALUES (?, ?, ?, ?, ?, ?)");
        if (!$stmtItem) throw new Exception("Prepare statement item gagal: " . $conn->error);
        
        $stmtUpdateProductStock = $conn->prepare("UPDATE products SET stock = stock - ? WHERE id = ? AND stock >= ?");
        $stmtUpdateVariantStock = $conn->prepare("UPDATE product_variants SET stock = stock - ? WHERE id = ? AND stock >= ?");

        foreach ($cart as $item) {
            $item_details_json = json_encode($item['details'] ?? null);
            $stmtItem->bind_param("iisids", $transaction_id, $item['id'], $item['name'], $item['quantity'], $item['finalPrice'], $item_details_json);
            if (!$stmtItem->execute()) {
                throw new Exception("Eksekusi statement item gagal: " . $stmtItem->error);
            }

            if (isset($item['details']['variant']['id']) && $item['details']['variant']['id'] !== null) {
                // Jika ada variant ID, update stok varian
                $variant_id = $item['details']['variant']['id'];
                $stmtUpdateVariantStock->bind_param("iii", $item['quantity'], $variant_id, $item['quantity']);
                if (!$stmtUpdateVariantStock->execute()) {
                    throw new Exception("Eksekusi update stok varian gagal: " . $stmtUpdateVariantStock->error);
                }
            } else {
                // Jika tidak ada varian (produk simpel), update stok produk utama
                 $stmtUpdateProductStock->bind_param("iii", $item['quantity'], $item['id'], $item['quantity']);
                if (!$stmtUpdateProductStock->execute()) {
                     throw new Exception("Eksekusi update stok produk gagal: " . $stmtUpdateProductStock->error);
                }
            }
        }
        $stmtItem->close();
        $stmtUpdateProductStock->close();
        $stmtUpdateVariantStock->close();
        
        $conn->commit();
        echo json_encode(['success' => true, 'message' => 'Transaksi berhasil disimpan.', 'transaction_code' => $transaction_code]);

    } catch (Exception $e) {
        $conn->rollback();
        http_response_code(400); 
        // Baris ini akan mengirim pesan error yang jelas ke frontend
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    
} elseif ($action === 'get_payment_methods') {
    $result = $conn->query("SELECT id, name, logo_url FROM payment_methods WHERE is_active = 1 ORDER BY id");
    if ($result) {
        echo json_encode($result->fetch_all(MYSQLI_ASSOC));
    } else {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => 'Gagal mengambil metode pembayaran']);
    }
} else {
    http_response_code(404);
    echo json_encode(['success' => false, 'error' => 'Action tidak valid']);
}

$conn->close();
?>

