<?php
// File: api.php (Dengan tambahan aksi get_orders)

header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
header('Content-Type: application/json');

require_once "config.php";

// Router Aksi
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';

switch ($action) {
    case 'get_products':
        get_products($mysqli);
        break;
    case 'increment_view':
        increment_counter($mysqli, 'view_count');
        break;
    case 'increment_cart':
        increment_counter($mysqli, 'add_to_cart_count');
        break;
    case 'get_product_analytics':
        get_product_analytics($mysqli);
        break;
    case 'save_order':
        save_order($mysqli);
        break;
    // --- AKSI BARU UNTUK DASBOR ---
    case 'get_orders':
        get_orders($mysqli);
        break;
    default:
        echo json_encode(['error' => 'Aksi tidak valid.']);
        break;
}

$mysqli->close();

// --- FUNGSI-FUNGSI ---

// --- FUNGSI BARU UNTUK MENGAMBIL SEMUA PESANAN ---
function get_orders($mysqli) {
    $sql = "SELECT id, customer_name, customer_address, customer_phone, order_details, total_price, payment_method, notes, created_at FROM `orders`";
    $result = $mysqli->query($sql);
    if ($result) {
        $orders = [];
        while ($row = $result->fetch_assoc()) {
            $orders[] = $row;
        }
        echo json_encode($orders, JSON_UNESCAPED_SLASHES);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Gagal mengambil data pesanan: ' . $mysqli->error]);
    }
}

function get_products($mysqli) {
    $sql = "SELECT id, sku, name, price, category, images, description, view_count, add_to_cart_count FROM products ORDER BY created_at DESC";
    $result = $mysqli->query($sql);
    if ($result) {
        $products = [];
        while ($row = $result->fetch_assoc()) {
            $row['id'] = (int)$row['id'];
            $row['price'] = (float)$row['price'];
            $row['category'] = trim($row['category']);
            $row['images'] = json_decode($row['images']) ?: []; 
            $row['view_count'] = (int)$row['view_count'];
            $row['add_to_cart_count'] = (int)$row['add_to_cart_count'];
            $products[] = $row;
        }
        echo json_encode($products, JSON_UNESCAPED_SLASHES);
    } else {
        echo json_encode(['error' => 'Gagal mengambil data produk: ' . $mysqli->error]);
    }
}

function save_order($mysqli) {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405); 
        echo json_encode(['error' => 'Metode request tidak diizinkan.']);
        return;
    }
    
    $data = json_decode(file_get_contents('php://input'), true);

    $name = $data['name'] ?? '';
    $address = $data['address'] ?? '';
    $phone = $data['phone'] ?? '';
    $items = $data['items'] ?? [];
    $total = $data['total'] ?? 0;
    $payment = $data['paymentMethod'] ?? '';
    $notes = $data['notes'] ?? '';

    if (empty($name) || empty($phone) || empty($items)) {
        http_response_code(400); 
        echo json_encode(['error' => 'Data pesanan tidak lengkap: Nama, No. HP, dan item tidak boleh kosong.']);
        return;
    }

    $itemsJson = json_encode($items, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

    $sql = "INSERT INTO orders (customer_name, customer_address, customer_phone, order_details, total_price, payment_method, notes) VALUES (?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $mysqli->prepare($sql);

    if ($stmt === false) {
        http_response_code(500);
        echo json_encode([
            'error' => 'Gagal mempersiapkan statement SQL.',
            'db_error' => $mysqli->error 
        ]);
        return;
    }

    $stmt->bind_param("ssssdss", $name, $address, $phone, $itemsJson, $total, $payment, $notes);
    
    if ($stmt->execute()) {
        echo json_encode([
            'success' => true, 
            'message' => 'Pesanan berhasil disimpan di database.', 
            'order_id' => $mysqli->insert_id
        ]);
    } else {
        http_response_code(500);
        echo json_encode([
            'error' => 'Gagal menyimpan pesanan.', 
            'db_error' => $stmt->error
        ]);
    }
    
    $stmt->close();
}

function increment_counter($mysqli, $column) {
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    if ($id > 0) {
        $stmt = $mysqli->prepare("UPDATE products SET `$column` = `$column` + 1 WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->close();
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['error' => 'ID produk tidak valid.']);
    }
}

function get_product_analytics($mysqli) {
    $sql = "SELECT id, name, view_count, add_to_cart_count FROM products";
    $result = $mysqli->query($sql);
    $products = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];

    usort($products, fn($a, $b) => $b['view_count'] <=> $a['view_count']);
    $by_views = array_slice($products, 0, 10);

    usort($products, fn($a, $b) => $b['add_to_cart_count'] <=> $a['add_to_cart_count']);
    $by_cart = array_slice($products, 0, 10);

    echo json_encode(['by_views' => $by_views, 'by_cart' => $by_cart]);
}

?>
