<?php
// Enable error logging (disable display in production)
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error.log');

// Set headers for API
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS'); // Hanya izinkan GET untuk membaca
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');

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

// Database connection
$host = 'localhost';
$user = 'rhlqyjgg_admin';
$pass = 'xub!.&%O1pOU';
$db   = 'rhlqyjgg_dbbengkel';

$conn = new mysqli($host, $user, $pass, $db);
$conn->set_charset('utf8mb4');
if ($conn->connect_error) {
    http_response_code(500);
    error_log('Database connection failed: ' . $conn->connect_error);
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}

function respond($status, $message, $extra = []) {
    echo json_encode(array_merge(['status' => $status, 'message' => $message], $extra));
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    // Ambil ID transaksi dari query parameter jika ada
    $transaksi_id = intval($_GET['id'] ?? 0);

    // SQL query untuk mengambil data transaksi
    // JOIN dengan tabel sparepart untuk mendapatkan nama sparepart
    $sql = 'SELECT 
                t.id, 
                t.sparepart_id, 
                s.nama AS sparepart_nama, 
                t.jenis, 
                t.jumlah, 
                t.ppn, 
                t.created_at, 
                t.keterangan 
            FROM 
                transaksi t
            JOIN 
                sparepart s ON t.sparepart_id = s.id';
    
    $params = [];
    $types = '';

    // Jika ada ID transaksi spesifik, tambahkan klausa WHERE
    if ($transaksi_id > 0) {
        $sql .= ' WHERE t.id = ?';
        $params[] = $transaksi_id;
        $types .= 'i';
    }

    // Urutkan berdasarkan tanggal terbaru
    $sql .= ' ORDER BY t.created_at DESC';

    $stmt = $conn->prepare($sql);
    
    // Bind parameter jika ada
    if ($transaksi_id > 0) {
        $stmt->bind_param($types, ...$params);
    }
    
    $stmt->execute();
    $result = $stmt->get_result();

    if (!$result) {
        respond('error', 'Database query failed: ' . $conn->error);
    }

    $data = [];
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    $stmt->close();

    respond('success', 'Data transaksi berhasil diambil', ['data' => $data]);

} else {
    // Jika metode selain GET digunakan, respon dengan error
    http_response_code(405); // Method Not Allowed
    respond('error', 'Metode tidak diizinkan');
}

$conn->close();
?>