<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0); // Set to 0 in production
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error.log');

// Header CORS dan Content-Type JSON
header('Content-Type: application/json; charset=UTF-8');
// PERBAIKAN PENTING: Ganti '*' dengan origin spesifik saat menggunakan kredensial
header('Access-Control-Allow-Origin: https://sumberbarokahsentosa.my.id');
header('Access-Control-Allow-Credentials: true'); // WAJIB ada jika frontend mengirim credentials
header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE'); // Tambahkan semua metode yang Anda gunakan
header('Access-Control-Allow-Headers: Content-Type, Authorization'); // Tambahkan semua header kustom yang Anda kirim

// Handle CORS preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Include database connection
// Assuming koneksi.php establishes $conn (mysqli object)
include 'koneksi.php';

// Function to send JSON response and exit
function respond($status, $message, $data = null) {
    http_response_code($status === 'success' ? 200 : 500); // Set HTTP status code
    echo json_encode(['status' => $status, 'message' => $message, 'data' => $data]);
    exit;
}

// Check database connection
if (!$conn) {
    error_log('Database connection failed: ' . mysqli_connect_error());
    respond('error', 'Koneksi database gagal: ' . mysqli_connect_error());
}

// Check HTTP method
// Anda hanya mengizinkan GET di header CORS, jadi pastikan ini konsisten.
// Jika Anda memang hanya ingin GET, biarkan seperti ini.
// If ($_SERVER['REQUEST_METHOD'] !== 'GET') {
//     error_log('Invalid method: ' . $_SERVER['REQUEST_METHOD']);
//     respond('error', 'Metode harus GET');
// }

try {
    // Get filter parameters from GET request
    $sparepart_type_id = isset($_GET['sparepart_type_id']) ? intval($_GET['sparepart_type_id']) : 0;
    $tire_type = isset($_GET['tire_type']) ? $conn->real_escape_string($_GET['tire_type']) : '';

    // Base query
    $query = "
        SELECT 
            s.id,
            s.nama,
            s.sparepart_type_id,
            st.nama AS sparepart_type,
            s.ukuran,
            s.merk,
            s.jenis_kendaraan,
            s.harga_grosir,
            s.harga_eceran,
            s.stok,
            s.id_suplier,
            su.nama_suplier AS suplier_name,
            s.foto,
            s.tire_type
        FROM sparepart s
        LEFT JOIN sparepart_types st ON s.sparepart_type_id = st.id
        LEFT JOIN suplier su ON s.id_suplier = su.id
    ";

    $conditions = [];
    $params = [];
    $types = ''; // String for bind_param types (e.g., 'is' for int, string)

    // Add conditions based on provided parameters
    if ($sparepart_type_id > 0) {
        $conditions[] = 's.sparepart_type_id = ?';
        $params[] = $sparepart_type_id;
        $types .= 'i';
    }

    if (!empty($tire_type)) {
        $conditions[] = 's.tire_type = ?';
        $params[] = $tire_type;
        $types .= 's';
    }

    // Append WHERE clause if any conditions exist
    if (!empty($conditions)) {
        $query .= ' WHERE ' . implode(' AND ', $conditions);
    }

    $query .= ' ORDER BY s.id DESC'; // Always order by ID

    // Prepare and execute the statement
    $stmt = $conn->prepare($query);
    if (!$stmt) {
        throw new Exception('Gagal menyiapkan query: ' . $conn->error);
    }

    // Bind parameters if there are any
    if (!empty($params)) {
        // Use call_user_func_array for dynamic binding
        $bind_names = array($types);
        for ($i = 0; $i < count($params); $i++) {
            $bind_name = 'bind' . $i;
            $$bind_name = $params[$i];
            $bind_names[] = &$$bind_name;
        }
        call_user_func_array(array($stmt, 'bind_param'), $bind_names);
    }

    $stmt->execute();
    $result = $stmt->get_result();

    if (!$result) {
        throw new Exception('Gagal menjalankan query: ' . $stmt->error);
    }

    $data = [];
    while ($row = $result->fetch_assoc()) {
        // Type casting for consistency
        $row['id'] = (int)$row['id'];
        $row['sparepart_type_id'] = (int)$row['sparepart_type_id'];
        $row['harga_grosir'] = (float)$row['harga_grosir'];
        $row['harga_eceran'] = (float)$row['harga_eceran'];
        $row['stok'] = (int)$row['stok'];
        $row['id_suplier'] = isset($row['id_suplier']) ? (int)$row['id_suplier'] : null;
        $row['ukuran'] = $row['ukuran'] ?? null;
        $row['tire_type'] = $row['tire_type'] ?? null;
        $row['foto'] = $row['foto'] ?? null; // Ensure foto is null if not set

        $data[] = $row;
    }

    $stmt->close();
    respond('success', 'Data berhasil diambil', $data);

} catch (Exception $e) {
    error_log('Error in readbarang.php: ' . $e->getMessage());
    respond('error', 'Terjadi kesalahan: ' . $e->getMessage());
} finally {
    // Ensure database connection is closed
    if ($conn) {
        mysqli_close($conn);
    }
}
?>