<?php
declare(strict_types=1);

// modules/rotasi_perawat.php
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/app.php';

checkAuth();

$conn = function_exists('getAppConnection') ? getAppConnection() : getConnection();

if (!function_exists('e')) {
    function e($v): string
    {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

if (!$conn) {
    echo "<div class='bg-red-50 border-l-4 border-red-500 p-4 rounded'>
            <p class='text-red-700'>Koneksi database aplikasi gagal.</p>
          </div>";
    return;
}

$module = 'rotasi_perawat';
$action = $_GET['action'] ?? 'list';
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$error = '';

if (!function_exists('safeLogActivity')) {
    function safeLogActivity(string $action, string $table, int $recordId, string $description): void
    {
        if (function_exists('logActivity')) {
            try {
                logActivity($action, $table, $recordId, $description);
            } catch (Throwable $e) {
                // abaikan
            }
        }
    }
}

/**
 * Fallback ambil daftar pegawai aktif bila helper lama tidak ada
 */
if (!function_exists('getEmployeesByUnit')) {
    function getEmployeesByUnit(): array
    {
        $conn = function_exists('getAppConnection') ? getAppConnection() : getConnection();
        $rows = [];

        $sql = "
            SELECT e.*, u.name AS unit_name
            FROM employees e
            LEFT JOIN units u ON e.unit_id = u.id
            WHERE e.employment_status = 'aktif'
            ORDER BY e.full_name ASC
        ";
        $result = $conn->query($sql);
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $rows[] = $row;
            }
        }

        return $rows;
    }
}

/**
 * Fallback ambil unit bila helper lama tidak ada
 */
if (!function_exists('getUnits')) {
    function getUnits(): array
    {
        $conn = function_exists('getAppConnection') ? getAppConnection() : getConnection();
        $rows = [];

        $sql = "SELECT * FROM units WHERE is_active = 1 ORDER BY name ASC";
        $result = $conn->query($sql);
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $rows[] = $row;
            }
        }

        return $rows;
    }
}

// ==============================
// HANDLE ROTASI
// ==============================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'rotasi') {
    $employee_id   = (int)($_POST['employee_id'] ?? 0);
    $to_unit_id    = (int)($_POST['to_unit_id'] ?? 0);
    $mutation_date = trim((string)($_POST['mutation_date'] ?? ''));
    $reason        = trim((string)($_POST['reason'] ?? ''));
    $notes         = trim((string)($_POST['notes'] ?? ''));
    $created_by    = (int)($_SESSION['user_id'] ?? 0);

    if ($employee_id <= 0 || $to_unit_id <= 0 || $mutation_date === '') {
        $error = 'Karyawan, unit tujuan, dan tanggal mutasi wajib diisi.';
    } else {
        $stmtEmp = $conn->prepare("SELECT id, unit_id, full_name FROM employees WHERE id = ? LIMIT 1");
        if (!$stmtEmp) {
            $error = 'Gagal menyiapkan query karyawan.';
        } else {
            $stmtEmp->bind_param("i", $employee_id);
            $stmtEmp->execute();
            $resEmp = $stmtEmp->get_result();
            $emp = $resEmp ? $resEmp->fetch_assoc() : null;
            $stmtEmp->close();

            if (!$emp) {
                $error = 'Data karyawan tidak ditemukan.';
            } else {
                $from_unit_id = (int)($emp['unit_id'] ?? 0);
                $full_name = (string)($emp['full_name'] ?? '-');

                $stmt = $conn->prepare("
                    INSERT INTO employee_mutations
                    (employee_id, from_unit_id, to_unit_id, mutation_date, reason, notes, created_by)
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");

                if (!$stmt) {
                    $error = 'Gagal menyiapkan query mutasi.';
                } else {
                    $stmt->bind_param(
                        "iiisssi",
                        $employee_id,
                        $from_unit_id,
                        $to_unit_id,
                        $mutation_date,
                        $reason,
                        $notes,
                        $created_by
                    );

                    if ($stmt->execute()) {
                        $mutation_id = (int)$conn->insert_id;
                        $stmt->close();

                        $stmtUpdate = $conn->prepare("UPDATE employees SET unit_id = ? WHERE id = ?");
                        if ($stmtUpdate) {
                            $stmtUpdate->bind_param("ii", $to_unit_id, $employee_id);
                            $stmtUpdate->execute();
                            $stmtUpdate->close();
                        }

                        safeLogActivity('create', 'employee_mutations', $mutation_id, "Rotasi karyawan: {$full_name} ke unit baru");

                        echo "<script>alert('Data rotasi berhasil disimpan!'); window.location.href='?module={$module}';</script>";
                        exit;
                    } else {
                        $error = 'Gagal menyimpan rotasi: ' . $stmt->error;
                        $stmt->close();
                    }
                }
            }
        }
    }
}

// ==============================
// HANDLE RESIGN
// ==============================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'resign') {
    $employee_id = (int)($_POST['employee_id'] ?? 0);
    $resign_date = trim((string)($_POST['resign_date'] ?? ''));
    $notes       = trim((string)($_POST['notes'] ?? ''));

    if ($employee_id <= 0 || $resign_date === '') {
        $error = 'Karyawan dan tanggal resign wajib diisi.';
    } else {
        $stmtEmp = $conn->prepare("SELECT id, full_name, notes FROM employees WHERE id = ? LIMIT 1");
        if (!$stmtEmp) {
            $error = 'Gagal menyiapkan query resign.';
        } else {
            $stmtEmp->bind_param("i", $employee_id);
            $stmtEmp->execute();
            $resEmp = $stmtEmp->get_result();
            $emp = $resEmp ? $resEmp->fetch_assoc() : null;
            $stmtEmp->close();

            if (!$emp) {
                $error = 'Data karyawan tidak ditemukan.';
            } else {
                $full_name = (string)($emp['full_name'] ?? '-');
                $old_notes = trim((string)($emp['notes'] ?? ''));
                $new_notes = trim($old_notes . "\nResign: " . $notes);

                $stmt = $conn->prepare("
                    UPDATE employees
                    SET employment_status = 'resign', resign_date = ?, notes = ?
                    WHERE id = ?
                ");

                if (!$stmt) {
                    $error = 'Gagal menyiapkan update resign.';
                } else {
                    $stmt->bind_param("ssi", $resign_date, $new_notes, $employee_id);

                    if ($stmt->execute()) {
                        safeLogActivity('status_update', 'employees', $employee_id, "Mengubah status kerja menjadi resign untuk {$full_name}");
                        echo "<script>alert('Data resign berhasil disimpan!'); window.location.href='?module={$module}&tab=history';</script>";
                        exit;
                    } else {
                        $error = 'Gagal menyimpan resign: ' . $stmt->error;
                    }

                    $stmt->close();
                }
            }
        }
    }
}

// ==============================
// GET ALL MUTATIONS
// ==============================
$mutations = [];
$result = $conn->query("
    SELECT
        m.*,
        e.full_name,
        u_from.name AS from_unit,
        u_to.name AS to_unit
    FROM employee_mutations m
    JOIN employees e ON m.employee_id = e.id
    LEFT JOIN units u_from ON m.from_unit_id = u_from.id
    LEFT JOIN units u_to ON m.to_unit_id = u_to.id
    ORDER BY m.mutation_date DESC, m.id DESC
");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $mutations[] = $row;
    }
}

// ==============================
// GET RESIGN DATA
// ==============================
$resigns = [];
$result = $conn->query("
    SELECT e.*, u.name AS unit_name
    FROM employees e
    LEFT JOIN units u ON e.unit_id = u.id
    WHERE e.employment_status = 'resign'
    ORDER BY e.resign_date DESC, e.id DESC
");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $resigns[] = $row;
    }
}

// ==============================
// GET ACTIVE EMPLOYEES / UNITS
// ==============================
$employees = getEmployeesByUnit();
$units = getUnits();

$defaultTab = $_GET['tab'] ?? 'rotasi';
if (!in_array($defaultTab, ['rotasi', 'resign', 'history'], true)) {
    $defaultTab = 'rotasi';
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rotasi / Resign Perawat</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        body { font-family: 'Poppins', sans-serif; background: #f8fafc; }
        .tab-button.active {
            background: #3b82f6;
            color: white;
        }
    </style>
</head>
<body class="p-6">
    <div class="mb-6">
        <h1 class="text-2xl font-bold text-gray-800">Rotasi / Resign Perawat</h1>
        <p class="text-gray-600">Manajemen mutasi dan resign karyawan</p>
    </div>

    <?php if ($error !== ''): ?>
    <div class="mb-4 bg-red-50 border-l-4 border-red-500 p-4 rounded">
        <p class="text-red-700"><?= e($error) ?></p>
    </div>
    <?php endif; ?>

    <!-- Tabs -->
    <div class="flex space-x-2 mb-6 border-b border-gray-200">
        <button onclick="showTab('rotasi')" id="tabRotasiBtn" class="tab-button px-6 py-3 text-sm font-medium rounded-t-lg bg-gray-100 hover:bg-gray-200">Form Rotasi</button>
        <button onclick="showTab('resign')" id="tabResignBtn" class="tab-button px-6 py-3 text-sm font-medium rounded-t-lg bg-gray-100 hover:bg-gray-200">Form Resign</button>
        <button onclick="showTab('history')" id="tabHistoryBtn" class="tab-button px-6 py-3 text-sm font-medium rounded-t-lg bg-gray-100 hover:bg-gray-200">Riwayat</button>
    </div>

    <!-- Tab Rotasi -->
    <div id="tabRotasi" class="tab-content">
        <div class="bg-white rounded-xl shadow-lg p-6">
            <h2 class="text-lg font-semibold mb-4">Form Rotasi/Mutasi Perawat</h2>
            <form method="POST" action="?module=<?= e($module) ?>&action=rotasi" class="space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Pilih Perawat *</label>
                        <select name="employee_id" required class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                            <option value="">-- Pilih Perawat --</option>
                            <?php foreach ($employees as $emp): ?>
                            <option value="<?= (int)$emp['id'] ?>">
                                <?= e($emp['full_name']) ?> (<?= e($emp['unit_name'] ?? 'Tanpa Unit') ?>)
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Unit Tujuan *</label>
                        <select name="to_unit_id" required class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                            <option value="">-- Pilih Unit Tujuan --</option>
                            <?php foreach ($units as $unit): ?>
                            <option value="<?= (int)$unit['id'] ?>"><?= e($unit['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Tanggal Mutasi *</label>
                        <input type="date" name="mutation_date" required value="<?= date('Y-m-d') ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Alasan</label>
                        <input type="text" name="reason" class="w-full px-4 py-2 border border-gray-300 rounded-lg" placeholder="Contoh: Pengembangan karir">
                    </div>
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Catatan</label>
                        <textarea name="notes" rows="3" class="w-full px-4 py-2 border border-gray-300 rounded-lg"></textarea>
                    </div>
                </div>
                <div class="flex justify-end">
                    <button type="submit" class="px-6 py-2 bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-lg hover:from-blue-700 hover:to-indigo-700">
                        <i class="fas fa-exchange-alt mr-2"></i> Proses Rotasi
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Tab Resign -->
    <div id="tabResign" class="tab-content hidden">
        <div class="bg-white rounded-xl shadow-lg p-6">
            <h2 class="text-lg font-semibold mb-4">Form Resign Perawat</h2>
            <form method="POST" action="?module=<?= e($module) ?>&action=resign" class="space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Pilih Perawat *</label>
                        <select name="employee_id" required class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                            <option value="">-- Pilih Perawat --</option>
                            <?php foreach ($employees as $emp): ?>
                            <option value="<?= (int)$emp['id'] ?>">
                                <?= e($emp['full_name']) ?> (<?= e($emp['unit_name'] ?? 'Tanpa Unit') ?>)
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Tanggal Resign *</label>
                        <input type="date" name="resign_date" required value="<?= date('Y-m-d') ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                    </div>
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Catatan / Alasan Resign</label>
                        <textarea name="notes" rows="3" required class="w-full px-4 py-2 border border-gray-300 rounded-lg" placeholder="Contoh: Pindah kerja, pensiun, dll"></textarea>
                    </div>
                </div>
                <div class="flex justify-end">
                    <button type="submit" class="px-6 py-2 bg-gradient-to-r from-red-600 to-pink-600 text-white rounded-lg hover:from-red-700 hover:to-pink-700">
                        <i class="fas fa-sign-out-alt mr-2"></i> Proses Resign
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Tab History -->
    <div id="tabHistory" class="tab-content hidden">
        <div class="space-y-6">
            <!-- Riwayat Rotasi -->
            <div class="bg-white rounded-xl shadow-lg overflow-hidden">
                <div class="bg-gradient-to-r from-blue-600 to-indigo-600 px-6 py-3">
                    <h3 class="text-white font-semibold"><i class="fas fa-exchange-alt mr-2"></i> Riwayat Rotasi/Mutasi</h3>
                </div>
                <div class="overflow-x-auto p-4">
                    <table class="w-full">
                        <thead class="bg-gray-50 border-b border-gray-200">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Tanggal</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nama</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Dari Unit</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Ke Unit</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Alasan</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php if (empty($mutations)): ?>
                            <tr>
                                <td colspan="5" class="px-6 py-4 text-center text-gray-500">Belum ada data rotasi</td>
                            </tr>
                            <?php else: ?>
                                <?php foreach ($mutations as $m): ?>
                                <tr>
                                    <td class="px-6 py-4 text-sm"><?= function_exists('formatTanggal') ? formatTanggal($m['mutation_date']) : e($m['mutation_date']) ?></td>
                                    <td class="px-6 py-4 text-sm font-medium"><?= e($m['full_name']) ?></td>
                                    <td class="px-6 py-4 text-sm"><?= e($m['from_unit'] ?? '-') ?></td>
                                    <td class="px-6 py-4 text-sm"><?= e($m['to_unit'] ?? '-') ?></td>
                                    <td class="px-6 py-4 text-sm"><?= e($m['reason'] ?? '-') ?></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Riwayat Resign -->
            <div class="bg-white rounded-xl shadow-lg overflow-hidden">
                <div class="bg-gradient-to-r from-red-600 to-pink-600 px-6 py-3">
                    <h3 class="text-white font-semibold"><i class="fas fa-user-minus mr-2"></i> Riwayat Resign</h3>
                </div>
                <div class="overflow-x-auto p-4">
                    <table class="w-full">
                        <thead class="bg-gray-50 border-b border-gray-200">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Tanggal Resign</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">NIK</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nama</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Unit Terakhir</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Profesi</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php if (empty($resigns)): ?>
                            <tr>
                                <td colspan="5" class="px-6 py-4 text-center text-gray-500">Belum ada data resign</td>
                            </tr>
                            <?php else: ?>
                                <?php foreach ($resigns as $r): ?>
                                <tr>
                                    <td class="px-6 py-4 text-sm"><?= function_exists('formatTanggal') ? formatTanggal($r['resign_date']) : e($r['resign_date']) ?></td>
                                    <td class="px-6 py-4 text-sm"><?= e($r['nik']) ?></td>
                                    <td class="px-6 py-4 text-sm font-medium"><?= e($r['full_name']) ?></td>
                                    <td class="px-6 py-4 text-sm"><?= e($r['unit_name'] ?? '-') ?></td>
                                    <td class="px-6 py-4 text-sm"><?= e(ucfirst((string)($r['profession'] ?? '-'))) ?></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        function showTab(tab) {
            document.querySelectorAll('.tab-content').forEach(el => el.classList.add('hidden'));
            document.querySelectorAll('.tab-button').forEach(el => el.classList.remove('active', 'bg-blue-600', 'text-white'));

            document.getElementById('tab' + tab.charAt(0).toUpperCase() + tab.slice(1)).classList.remove('hidden');
            document.getElementById('tab' + tab.charAt(0).toUpperCase() + tab.slice(1) + 'Btn').classList.add('active', 'bg-blue-600', 'text-white');
        }

        showTab('<?= e($defaultTab) ?>');
    </script>
</body>
</html>