<?php
header('Content-Type: application/json');
require 'config.php'; // Pastikan file ini berisi koneksi database Anda ($servername, $username, etc.)

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die(json_encode(['error' => 'Koneksi database gagal: ' . $conn->connect_error]));
}

$action = $_GET['action'] ?? '';

if ($action === 'get_products') {
    // Bangun query dasar
    $sql = "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";

    // Siapkan untuk filter dan parameter binding
    $where_clauses = [];
    $params = [];
    $types = '';

    // Logika Filter
    if (!empty($_GET['category_id']) && is_numeric($_GET['category_id'])) {
        $where_clauses[] = "p.category_id = ?";
        $params[] = $_GET['category_id'];
        $types .= 'i';
    }
    if (!empty($_GET['min_price']) && is_numeric($_GET['min_price'])) {
        $where_clauses[] = "p.base_price >= ?";
        $params[] = $_GET['min_price'];
        $types .= 'd';
    }
    if (!empty($_GET['max_price']) && is_numeric($_GET['max_price'])) {
        $where_clauses[] = "p.base_price <= ?";
        $params[] = $_GET['max_price'];
        $types .= 'd';
    }
    if (!empty($_GET['min_rating']) && is_numeric($_GET['min_rating'])) {
        $where_clauses[] = "p.rating >= ?";
        $params[] = $_GET['min_rating'];
        $types .= 'd';
    }
    if (!empty($_GET['q'])) {
        $where_clauses[] = "p.name LIKE ?";
        $params[] = '%' . $_GET['q'] . '%';
        $types .= 's';
    }

    if (count($where_clauses) > 0) {
        $sql .= " WHERE " . implode(' AND ', $where_clauses);
    }

    // Logika Sortir (gunakan whitelist untuk keamanan)
    $sort_by = $_GET['sort_by'] ?? 'paling_sesuai';
    $order_clause = " ORDER BY ";
    $sort_whitelist = [
        'terbaru' => 'p.last_update DESC',
        'harga_tertinggi' => 'p.base_price DESC',
        'harga_terendah' => 'p.base_price ASC',
        'ulasan_terbanyak' => 'p.review_count DESC',
        'pembelian_terbanyak' => 'p.sold_count DESC'
    ];
    if (array_key_exists($sort_by, $sort_whitelist)) {
        $sql .= $order_clause . $sort_whitelist[$sort_by];
    }

    // Logika Paginasi
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = 10;
    $offset = ($page - 1) * $limit;
    $sql .= " LIMIT ? OFFSET ?";
    $params[] = $limit;
    $params[] = $offset;
    $types .= 'ii';
    
    // Eksekusi Query
    $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);
        $stmt->close();
        echo json_encode($products);
    } else {
        echo json_encode(['error' => 'Query gagal: ' . $conn->error]);
    }

} elseif ($action === 'get_initial_data') {
    // Action untuk memuat data awal (kategori, brand, dll)
    $categories_q = $conn->query("SELECT id, name FROM categories ORDER BY name ASC");
    $brands_q = $conn->query("SELECT id, name FROM brands ORDER BY name ASC");
    $vouchers_q = $conn->query("SELECT * FROM vouchers");

    $data = [
        'categories' => $categories_q->fetch_all(MYSQLI_ASSOC),
        'brands' => $brands_q->fetch_all(MYSQLI_ASSOC),
        'vouchers' => $vouchers_q->fetch_all(MYSQLI_ASSOC)
    ];
    echo json_encode($data);
} else {
    echo json_encode(['error' => 'Action tidak valid']);
}

$conn->close();
?>