<?php
// CORS untuk preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Allow-Origin: https://drarnya.itcprogram.com');
    header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Authorization, Content-Type');
    http_response_code(200);
    exit;
}
header('Access-Control-Allow-Origin: https://drarnya.itcprogram.com');
header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
header('Content-Type: application/json');

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();
if (!$conn) {
    http_response_code(500);
    echo json_encode(['error' => 'Database connection failed']);
    exit;
}

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

// Helper generate nomor WO yang aman dengan retry mechanism
function generateWoNumber($conn, $maxRetries = 3) {
    $year = date('Y');
    $month = date('m');
    $prefix = "WO/{$year}{$month}/V";
    
    for ($retry = 0; $retry < $maxRetries; $retry++) {
        // Cari nomor terbesar yang sudah ada
        $stmt = $conn->prepare("SELECT wo_number FROM work_orders_v2 
                                WHERE wo_number LIKE ? 
                                ORDER BY id DESC LIMIT 1");
        $likePattern = "WO/{$year}{$month}/V%";
        $stmt->bind_param("s", $likePattern);
        $stmt->execute();
        $result = $stmt->get_result();
        $last = $result->fetch_assoc();
        
        if ($last) {
            // Ekstrak nomor urut dari WO/202604/V0003 -> 0003
            preg_match('/V(\d+)$/', $last['wo_number'], $matches);
            $lastNum = isset($matches[1]) ? (int)$matches[1] : 0;
            $newNum = str_pad($lastNum + 1, 4, '0', STR_PAD_LEFT);
        } else {
            $newNum = '0001';
        }
        
        $wo_number = $prefix . $newNum;
        
        // Double check untuk memastikan tidak ada duplicate
        $checkStmt = $conn->prepare("SELECT id FROM work_orders_v2 WHERE wo_number = ?");
        $checkStmt->bind_param("s", $wo_number);
        $checkStmt->execute();
        if ($checkStmt->get_result()->num_rows === 0) {
            return $wo_number;
        }
        // Jika bentrok, lanjut ke retry berikutnya (akan mencari nomor terbaru lagi)
    }
    
    throw new Exception('Gagal generate nomor WO setelah ' . $maxRetries . ' kali percobaan');
}

try {
    switch ($action) {
        case 'create':
            $input = json_decode(file_get_contents('php://input'), true);
            if (!$input) {
                throw new Exception('Invalid JSON input');
            }
            
            // Validasi required fields
            if (empty($input['judul_order'])) {
                throw new Exception('Judul Order wajib diisi');
            }
            if (empty($input['unit_id'])) {
                throw new Exception('Unit Pelapor wajib dipilih');
            }
            if (empty($input['deskripsi'])) {
                throw new Exception('Deskripsi Masalah wajib diisi');
            }
            
            $wo_number = generateWoNumber($conn);
            $tgl_order = date('Y-m-d H:i:s');
            $requested_by = $input['requested_by'] ?? null;
            $alat_medis_id = !empty($input['alat_medis_id']) ? $input['alat_medis_id'] : null;
            
            // Query dasar
            $sql = "INSERT INTO work_orders_v2 
                    (wo_number, unit_id, judul_order, jenis_order, deskripsi, tgl_order, created_by, requested_by, status";
            
            $values = "VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'open'";
            $params = [
                $wo_number,
                $input['unit_id'],
                $input['judul_order'],
                $input['jenis_order'],
                $input['deskripsi'],
                $tgl_order,
                $user['user_id'],
                $requested_by
            ];
            $types = "sissssss";
            
            // Tambah alat_medis_id jika ada
            if ($alat_medis_id && $input['jenis_order'] === 'alat_medis') {
                $sql .= ", alat_medis_id";
                $values .= ", ?";
                $params[] = $alat_medis_id;
                $types .= "i";
            }
            
            $sql .= ") " . $values . ")";
            
            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception('Prepare statement failed: ' . $conn->error);
            }
            
            $stmt->bind_param($types, ...$params);
            
            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'wo_number' => $wo_number, 'id' => $stmt->insert_id]);
            } else {
                throw new Exception('Gagal menyimpan: ' . $stmt->error);
            }
            break;

        case 'list':
            $status = $_GET['status'] ?? '';
            $unit_id = $_GET['unit_id'] ?? '';
            $search = $_GET['search'] ?? '';
            
            $sql = "SELECT w.*, u.name as unit_name,
                    a.nama_alat as alat_nama,
                    a.nomor_seri,
                    DATEDIFF(w.tgl_selesai, w.tgl_diterima) as kinerja_hari
                    FROM work_orders_v2 w
                    LEFT JOIN units u ON w.unit_id = u.id
                    LEFT JOIN alat_medis a ON w.alat_medis_id = a.id
                    WHERE 1=1";
            
            $params = [];
            $types = "";
            
            if (!empty($status)) {
                $sql .= " AND w.status = ?";
                $params[] = $status;
                $types .= "s";
            }
            
            if (!empty($unit_id)) {
                $sql .= " AND w.unit_id = ?";
                $params[] = $unit_id;
                $types .= "i";
            }
            
            if (!empty($search)) {
                $sql .= " AND (w.wo_number LIKE ? OR w.judul_order LIKE ? OR w.deskripsi LIKE ?)";
                $searchParam = "%{$search}%";
                $params[] = $searchParam;
                $params[] = $searchParam;
                $params[] = $searchParam;
                $types .= "sss";
            }
            
            $sql .= " ORDER BY w.created_at DESC";
            
            $stmt = $conn->prepare($sql);
            if (!empty($params)) {
                $stmt->bind_param($types, ...$params);
            }
            $stmt->execute();
            $result = $stmt->get_result();
            
            $data = [];
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
            echo json_encode($data);
            break;

        case 'detail':
            $id = $_GET['id'] ?? 0;
            if (!$id) {
                throw new Exception('ID required');
            }
            $stmt = $conn->prepare("SELECT w.*, u.name as unit_name,
                    a.nama_alat as alat_nama,
                    a.nomor_seri,
                    DATEDIFF(w.tgl_selesai, w.tgl_diterima) as kinerja_hari
                    FROM work_orders_v2 w
                    LEFT JOIN units u ON w.unit_id = u.id
                    LEFT JOIN alat_medis a ON w.alat_medis_id = a.id
                    WHERE w.id = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $result = $stmt->get_result();
            $data = $result->fetch_assoc();
            echo json_encode($data);
            break;

        case 'update':
            $id = $_GET['id'] ?? 0;
            if (!$id) {
                throw new Exception('ID required');
            }
            $input = json_decode(file_get_contents('php://input'), true);
            if (!$input) {
                throw new Exception('Invalid JSON input');
            }
            
            $allowed = ['tgl_diterima', 'penerima', 'tgl_dikerjakan', 'tgl_selesai', 'keterangan', 'status'];
            $updates = [];
            $params = [];
            $types = "";
            
            foreach ($allowed as $field) {
                if (array_key_exists($field, $input)) {
                    $updates[] = "$field = ?";
                    $params[] = $input[$field];
                    $types .= "s";
                }
            }
            
            if (empty($updates)) {
                throw new Exception('No field to update');
            }
            
            $params[] = $id;
            $types .= "i";
            $sql = "UPDATE work_orders_v2 SET " . implode(', ', $updates) . " WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param($types, ...$params);
            
            if ($stmt->execute()) {
                echo json_encode(['success' => true]);
            } else {
                throw new Exception('Update failed: ' . $stmt->error);
            }
            break;

        case 'delete':
            $id = $_GET['id'] ?? 0;
            if (!$id) {
                throw new Exception('ID required');
            }
            $stmt = $conn->prepare("DELETE FROM work_orders_v2 WHERE id = ?");
            $stmt->bind_param("i", $id);
            if ($stmt->execute()) {
                echo json_encode(['success' => true]);
            } else {
                throw new Exception('Delete failed: ' . $stmt->error);
            }
            break;

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