<?php
// api/alat_medis.php
header('Content-Type: application/json');

// CORS untuk izin akses dari subdomain
header('Access-Control-Allow-Origin: https://drarnya.itcprogram.com');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Authorization, Content-Type');

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

require_once '../config/database.php';
require_once 'auth.php';

// Validasi token
$user = validateToken();
if (!$user) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$conn = getConnection();
$action = $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'list':
            $sql = "SELECT a.*, u.name as unit_name 
                    FROM alat_medis a 
                    LEFT JOIN units u ON a.unit_id = u.id 
                    ORDER BY a.nama_alat";
            $result = $conn->query($sql);
            if (!$result) {
                throw new Exception('Query error: ' . $conn->error);
            }
            $data = [];
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
            echo json_encode($data);
            break;

        case 'detail':
            $id = (int)$_GET['id'];
            $stmt = $conn->prepare("SELECT a.*, u.name as unit_name 
                                    FROM alat_medis a 
                                    LEFT JOIN units u ON a.unit_id = u.id 
                                    WHERE a.id = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $result = $stmt->get_result();
            $data = $result->fetch_assoc();
            echo json_encode($data);
            break;

        case 'create':
            $input = json_decode(file_get_contents('php://input'), true);
            if (empty($input['nama_alat'])) {
                throw new Exception('Nama alat wajib diisi');
            }
            
            $stmt = $conn->prepare("INSERT INTO alat_medis 
                (nama_alat, nomor_seri, tgl_pembelian, tgl_disahkan_unit, unit_id, penerima, jumlah, keterangan) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            
            $stmt->bind_param("sssssiss", 
                $input['nama_alat'],
                $input['nomor_seri'],
                $input['tgl_pembelian'],
                $input['tgl_disahkan_unit'],
                $input['unit_id'],
                $input['penerima'],
                $input['jumlah'],
                $input['keterangan']
            );
            
            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'id' => $conn->insert_id]);
            } else {
                throw new Exception('Gagal simpan: ' . $stmt->error);
            }
            break;

        case 'update':
            $id = (int)$_GET['id'];
            $input = json_decode(file_get_contents('php://input'), true);
            
            $stmt = $conn->prepare("UPDATE alat_medis SET 
                nama_alat = ?, nomor_seri = ?, tgl_pembelian = ?, 
                tgl_disahkan_unit = ?, unit_id = ?, penerima = ?, 
                jumlah = ?, keterangan = ? WHERE id = ?");
            
            $stmt->bind_param("sssssissi", 
                $input['nama_alat'],
                $input['nomor_seri'],
                $input['tgl_pembelian'],
                $input['tgl_disahkan_unit'],
                $input['unit_id'],
                $input['penerima'],
                $input['jumlah'],
                $input['keterangan'],
                $id
            );
            
            if ($stmt->execute()) {
                echo json_encode(['success' => true]);
            } else {
                throw new Exception('Gagal update: ' . $stmt->error);
            }
            break;

        case 'delete':
            $id = (int)$_GET['id'];
            $stmt = $conn->prepare("DELETE FROM alat_medis WHERE id = ?");
            $stmt->bind_param("i", $id);
            if ($stmt->execute()) {
                echo json_encode(['success' => true]);
            } else {
                throw new Exception('Gagal hapus: ' . $stmt->error);
            }
            break;

        default:
            http_response_code(400);
            echo json_encode(['error' => 'Action tidak dikenal']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}