<?php
// Enable error logging (disable display in production)
error_reporting(E_ALL);
ini_set('display_errors', 0); // Nonaktifkan tampilan error di production
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, POST, DELETE, PUT, OPTIONS');
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;
}

// Fungsi respond (dipindahkan ke sini agar dikenal)
function respond($status, $message, $extra = []) {
    echo json_encode(array_merge(['status' => $status, 'message' => $message], $extra));
    exit;
}

// Configuration
$baseUrl = 'https://api-bengkel.sumberbarokahsentosa.my.id'; // Tanpa trailing slash
$uploadDir = __DIR__ . '/Uploads/'; // Path fisik di server
$uploadUrl = '/Uploads/'; // Path relatif untuk URL publik

// Pastikan folder Uploads ada dan dapat ditulis
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}
if (!is_writable($uploadDir)) {
    http_response_code(500);
    error_log('Upload directory not writable: ' . $uploadDir);
    respond('error', 'Upload directory not writable'); // Gunakan fungsi respond
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

// GET: Fetch all sparepart types
if ($method === 'GET') {
    $result = $conn->query('SELECT id, nama, foto FROM sparepart_types');
    if (!$result) {
        error_log('Query error: ' . $conn->error);
        respond('error', 'Database query failed');
    }
    $data = [];
    while ($row = $result->fetch_assoc()) {
        // Konversi path file lokal ke URL publik jika perlu
        // Jika foto sudah disimpan sebagai URL lengkap, tidak perlu diubah lagi
        // Jika foto disimpan sebagai nama file saja, maka tambahkan base URL dan upload URL
        // Asumsi di sini foto disimpan sebagai URL lengkap
        if ($row['foto'] && substr($row['foto'], 0, 4) !== 'http') {
            // Ini jika Anda menyimpan hanya nama file atau path relatif di DB
            $row['foto'] = $baseUrl . $uploadUrl . basename($row['foto']);
        }
        $data[] = $row;
    }
    respond('success', 'Data retrieved successfully', ['data' => $data]);
}

// POST: Add new sparepart type
elseif ($method === 'POST') {
    // Hapus bagian penanganan JSON-based delete action di POST.
    // Metode DELETE seharusnya hanya ditangani oleh blok DELETE di bawah.
    // Ini menghindari kebingungan dan mengikuti prinsip RESTful.

    // Add new type
    $nama = $conn->real_escape_string($_POST['nama'] ?? '');
    if (empty($nama) || !preg_match('/^[a-zA-Z0-9\s]+$/', $nama)) {
        respond('error', 'Name must contain only letters, numbers, and spaces');
    }

    $foto = null;
    if (isset($_FILES['foto']) && $_FILES['foto']['error'] === UPLOAD_ERR_OK) {
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        $maxFileSize = 2 * 1024 * 1024;
        $fileType = mime_content_type($_FILES['foto']['tmp_name']);
        $fileSize = $_FILES['foto']['size'];

        if (!in_array($fileType, $allowedTypes)) {
            respond('error', 'Only JPEG, PNG, or GIF files allowed');
        }
        if ($fileSize > $maxFileSize) {
            respond('error', 'File size exceeds 2MB limit');
        }

        $fileName = 'type_' . time() . '_' . preg_replace('/[^a-zA-Z0-9.]/', '_', $_FILES['foto']['name']);
        $targetPath = $uploadDir . $fileName; // Path fisik untuk menyimpan file
        $fotoUrl = $baseUrl . $uploadUrl . $fileName; // URL publik untuk disimpan di DB

        if (!move_uploaded_file($_FILES['foto']['tmp_name'], $targetPath)) {
            error_log('Failed to upload file: ' . $_FILES['foto']['name']);
            respond('error', 'Failed to upload file');
        }
        $foto = $fotoUrl; // Simpan URL publik ke database
    }

    $stmt = $conn->prepare('INSERT INTO sparepart_types (nama, foto) VALUES (?, ?)');
    if (!$stmt) {
        error_log('Prepare error: ' . $conn->error);
        respond('error', 'Database error: Failed to prepare query');
    }
    $stmt->bind_param('ss', $nama, $foto);
    if ($stmt->execute()) {
        $id = $conn->insert_id;
        respond('success', 'Sparepart type added successfully', [
            'id' => $id,
            'nama' => $nama,
            'foto' => $foto
        ]);
    } else {
        error_log('Query error: ' . $stmt->error);
        respond('error', 'Failed to add sparepart type: ' . $stmt->error);
    }
    $stmt->close();
}

// PUT: Update sparepart type
elseif ($method === 'PUT') {
    $input = json_decode(file_get_contents('php://input'), true);
    // Asumsi update dilakukan berdasarkan ID, bukan nama lama ke nama baru
    $id = intval($input['id'] ?? 0);
    $namaBaru = $conn->real_escape_string($input['nama_baru'] ?? '');

    if ($id <= 0) {
        respond('error', 'ID tipe sparepart tidak valid.');
    }
    if (empty($namaBaru) || !preg_match('/^[a-zA-Z0-9\s]+$/', $namaBaru)) {
        respond('error', 'New name must contain only letters, numbers, and spaces');
    }

    $stmt = $conn->prepare('UPDATE sparepart_types SET nama = ? WHERE id = ?');
    $stmt->bind_param('si', $namaBaru, $id);
    if ($stmt->execute()) {
        if ($stmt->affected_rows > 0) {
            respond('success', 'Sparepart type updated successfully');
        } else {
            respond('success', 'No changes made or type not found');
        }
    } else {
        error_log('Query error: ' . $stmt->error);
        respond('error', 'Failed to update sparepart type: ' . $stmt->error);
    }
    $stmt->close();
}

// DELETE: Delete sparepart type by ID
elseif ($method === 'DELETE') {
    parse_str($_SERVER['QUERY_STRING'], $params);
    $id = intval($params['id'] ?? 0);

    if ($id <= 0) {
        respond('error', 'Invalid ID');
    }

    // Cek ketergantungan sparepart (nama tabel yang benar: sparepart)
    $stmt = $conn->prepare('SELECT COUNT(*) as count FROM sparepart WHERE sparepart_type_id = ?'); // Perbaikan: sparepart
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $count = $result->fetch_assoc()['count'];
    $stmt->close();

    if ($count > 0) {
        respond('error', 'Cannot delete type because it is used by ' . $count . ' sparepart(s)');
    }

    // Ambil foto sparepart type untuk dihapus fisiknya
    $stmt = $conn->prepare('SELECT foto FROM sparepart_types WHERE id = ?');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        respond('error', 'Sparepart type not found');
    }

    $row = $result->fetch_assoc();
    $stmt->close();
    
    $foto_url_db = $row['foto']; // Ini adalah URL lengkap yang tersimpan di DB
    
    // Konversi URL ke path fisik di server untuk unlink
    // Contoh: 'https://api-bengkel.sumberbarokahsentosa.my.id/Uploads/type_123.jpg'
    // Perlu menjadi '/path/to/your/server/Uploads/type_123.jpg'
    $filename_from_url = basename($foto_url_db); // Ambil nama file saja dari URL
    $physical_filepath = $uploadDir . $filename_from_url;

    // Hapus file foto jika ada dan path fisiknya benar
    if ($foto_url_db && file_exists($physical_filepath) && is_file($physical_filepath)) {
        if (!unlink($physical_filepath)) {
            error_log('Failed to delete physical file: ' . $physical_filepath);
            // Anda bisa memilih untuk tidak merespon error ke client jika penghapusan DB lebih penting
            // respond('error', 'Failed to delete associated photo file'); // Opsional
        }
    }

    // Hapus sparepart type dari database
    $stmt = $conn->prepare('DELETE FROM sparepart_types WHERE id = ?');
    $stmt->bind_param('i', $id);
    if ($stmt->execute()) {
        if ($stmt->affected_rows > 0) {
            respond('success', 'Sparepart type deleted successfully');
        } else {
            respond('error', 'Sparepart type not found or no changes made');
        }
    } else {
        error_log('Delete error: ' . $stmt->error);
        respond('error', 'Failed to delete sparepart type: ' . $stmt->error);
    }
    $stmt->close();
}

$conn->close();
?>