<?php
declare(strict_types=1);

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

require_once __DIR__ . '/../config/master_auth.php';
require_once __DIR__ . '/../config/master_db.php';
require_once __DIR__ . '/../config/app.php';

checkAuth();

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

$pdo = master_db();
$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
            }
        }
    }
}

function findOrCreatePosition(PDO $pdo, string $positionName): ?int
{
    $positionName = trim($positionName);
    if ($positionName === '') {
        return null;
    }

    $stmt = $pdo->prepare("SELECT id FROM positions WHERE name = ? LIMIT 1");
    $stmt->execute([$positionName]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        return (int)$row['id'];
    }

    $code = strtoupper(preg_replace('/[^A-Z0-9]+/i', '', substr($positionName, 0, 12)));
    if ($code === '') {
        $code = 'POS' . date('His');
    }

    $stmt = $pdo->prepare("
        INSERT INTO positions (code, name, level_jabatan, sort_order, is_active)
        VALUES (?, ?, 'Staf', 999, 1)
    ");
    $stmt->execute([$code, $positionName]);

    return (int)$pdo->lastInsertId();
}

/**
 * HANDLE SUBMIT
 * Hanya pakai kolom master HR yang aman
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'add' || $action === 'edit') {
        $nik           = trim((string)($_POST['nik'] ?? ''));
        $namaLengkap   = trim((string)($_POST['full_name'] ?? ''));
        $email         = trim((string)($_POST['email'] ?? ''));
        $unitIdRaw     = $_POST['unit_id'] ?? '';
        $unitId        = ($unitIdRaw === '' ? null : (int)$unitIdRaw);
        $positionName  = trim((string)($_POST['position_name'] ?? ''));
        $statusPegawai = trim((string)($_POST['status_pegawai'] ?? 'Tetap'));

        if ($nik === '' || $namaLengkap === '') {
            $error = 'NIK dan Nama Lengkap wajib diisi.';
        } else {
            try {
                $positionId = findOrCreatePosition($pdo, $positionName);

                if ($action === 'add') {
                    $employeeCode = preg_replace('/\D+/', '', $nik);
                    if ($employeeCode === '') {
                        $employeeCode = date('YmdHis');
                    }

                    $stmtCheck = $pdo->prepare("
                        SELECT id
                        FROM employees
                        WHERE nik = ? OR employee_code = ?
                        LIMIT 1
                    ");
                    $stmtCheck->execute([$nik, $employeeCode]);
                    $exists = $stmtCheck->fetch(PDO::FETCH_ASSOC);

                    if ($exists) {
                        $error = 'Data karyawan dengan NIK / employee code tersebut sudah ada di master HR.';
                    } else {
                        $stmt = $pdo->prepare("
                            INSERT INTO employees (
                                employee_code,
                                nik,
                                nama_lengkap,
                                email,
                                unit_id,
                                position_id,
                                status_pegawai,
                                is_active
                            ) VALUES (?, ?, ?, ?, ?, ?, ?, 1)
                        ");
                        $stmt->execute([
                            $employeeCode,
                            $nik,
                            $namaLengkap,
                            $email !== '' ? $email : null,
                            $unitId,
                            $positionId,
                            $statusPegawai !== '' ? $statusPegawai : 'Tetap'
                        ]);

                        $newId = (int)$pdo->lastInsertId();
                        safeLogActivity('create', 'employees', $newId, "Menambah karyawan master: {$namaLengkap}");

                        echo "<script>alert('Data berhasil ditambahkan ke master HR!'); window.location.href='?module=data_perawat';</script>";
                        exit;
                    }
                }

                if ($action === 'edit') {
                    if ($id <= 0) {
                        $error = 'ID data tidak valid.';
                    } else {
                        $stmt = $pdo->prepare("
                            UPDATE employees
                            SET
                                nik = ?,
                                nama_lengkap = ?,
                                email = ?,
                                unit_id = ?,
                                position_id = ?,
                                status_pegawai = ?
                            WHERE id = ?
                        ");
                        $stmt->execute([
                            $nik,
                            $namaLengkap,
                            $email !== '' ? $email : null,
                            $unitId,
                            $positionId,
                            $statusPegawai !== '' ? $statusPegawai : 'Tetap',
                            $id
                        ]);

                        safeLogActivity('update', 'employees', $id, "Mengubah karyawan master: {$namaLengkap}");

                        echo "<script>alert('Data berhasil diubah di master HR!'); window.location.href='?module=data_perawat';</script>";
                        exit;
                    }
                }
            } catch (Throwable $e) {
                $error = 'Gagal menyimpan data: ' . $e->getMessage();
            }
        }
    }
}

/**
 * HANDLE DELETE -> nonaktifkan
 */
if ($action === 'delete' && $id > 0) {
    try {
        $stmt = $pdo->prepare("UPDATE employees SET is_active = 0 WHERE id = ?");
        $stmt->execute([$id]);

        safeLogActivity('delete', 'employees', $id, "Menonaktifkan karyawan master ID: {$id}");

        echo "<script>alert('Data berhasil dinonaktifkan!'); window.location.href='?module=data_perawat';</script>";
        exit;
    } catch (Throwable $e) {
        $error = 'Gagal menonaktifkan data: ' . $e->getMessage();
    }
}

/**
 * Data edit
 */
$editData = null;
if ($action === 'edit' && $id > 0) {
    $stmt = $pdo->prepare("
        SELECT
            e.id,
            e.employee_code,
            e.nik,
            e.nama_lengkap,
            e.email,
            e.unit_id,
            e.position_id,
            e.status_pegawai,
            e.is_active,
            u.name AS unit_name,
            p.name AS position_name
        FROM employees e
        LEFT JOIN units u ON e.unit_id = u.id
        LEFT JOIN positions p ON e.position_id = p.id
        WHERE e.id = ?
        LIMIT 1
    ");
    $stmt->execute([$id]);
    $editData = $stmt->fetch(PDO::FETCH_ASSOC);
}

/**
 * List data master HR
 * Hanya pakai kolom yang aman
 */
$employees = [];
$stmt = $pdo->query("
    SELECT
        e.id,
        e.employee_code,
        e.nik,
        e.nama_lengkap AS full_name,
        e.email,
        e.unit_id,
        e.position_id,
        e.status_pegawai AS employment_status,
        e.is_active,
        u.name AS unit_name,
        p.name AS position_name
    FROM employees e
    LEFT JOIN units u ON e.unit_id = u.id
    LEFT JOIN positions p ON e.position_id = p.id
    WHERE e.is_active = 1
    ORDER BY e.nama_lengkap ASC
");
if ($stmt) {
    $employees = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

/**
 * Dropdown unit
 */
$units = [];
$stmt = $pdo->query("SELECT id, name FROM units WHERE is_active = 1 ORDER BY name ASC");
if ($stmt) {
    $units = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>

<div class="space-y-6">
    <div class="flex justify-between items-center">
        <div>
            <h2 class="text-2xl font-semibold text-gray-800">Data Perawat</h2>
            <p class="text-gray-600">Kelola data perawat dan bidan dari master HR</p>
        </div>
        <button onclick="window.location.href='?module=data_perawat&action=add'" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 flex items-center gap-2">
            <i class="fas fa-plus"></i>
            Tambah Perawat
        </button>
    </div>

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

    <?php if ($action === 'add' || $editData): ?>
    <div class="bg-white rounded-xl shadow-lg p-6">
        <h3 class="text-lg font-semibold mb-4"><?= $action === 'add' ? 'Tambah Perawat Baru' : 'Edit Perawat' ?></h3>
        <form method="POST" class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <input type="hidden" name="action" value="<?= e($action) ?>">
            <?php if ($editData): ?>
            <input type="hidden" name="id" value="<?= (int)$id ?>">
            <?php endif; ?>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">NIK *</label>
                <input type="text" name="nik" required value="<?= e($editData['nik'] ?? '') ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Nama Lengkap *</label>
                <input type="text" name="full_name" required value="<?= e($editData['nama_lengkap'] ?? $editData['full_name'] ?? '') ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                <input type="email" name="email" value="<?= e($editData['email'] ?? '') ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Unit</label>
                <select name="unit_id" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    <option value="">Pilih Unit</option>
                    <?php foreach ($units as $unit): ?>
                    <option value="<?= (int)$unit['id'] ?>" <?= (($editData['unit_id'] ?? '') == $unit['id']) ? 'selected' : '' ?>>
                        <?= e($unit['name']) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Jabatan</label>
                <input type="text" name="position_name" value="<?= e($editData['position_name'] ?? '') ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Status Pegawai</label>
                <input type="text" name="status_pegawai" value="<?= e($editData['status_pegawai'] ?? 'Tetap') ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
            </div>

            <div class="md:col-span-2 flex justify-end space-x-2">
                <a href="?module=data_perawat" class="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">Batal</a>
                <button type="submit" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Simpan</button>
            </div>
        </form>
    </div>
    <?php endif; ?>

    <div class="bg-white rounded-xl shadow-lg overflow-hidden">
        <div class="overflow-x-auto">
            <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">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">Jabatan</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Unit</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status Pegawai</th>
                        <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase">Aksi</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200">
                    <?php foreach ($employees as $emp): ?>
                    <tr class="hover:bg-gray-50">
                        <td class="px-6 py-4 text-sm text-gray-900"><?= e($emp['nik'] ?: $emp['employee_code']) ?></td>
                        <td class="px-6 py-4 text-sm font-medium text-gray-900"><?= e($emp['full_name']) ?></td>
                        <td class="px-6 py-4 text-sm text-gray-600"><?= e($emp['position_name'] ?? '-') ?></td>
                        <td class="px-6 py-4 text-sm text-gray-600"><?= e($emp['unit_name'] ?? '-') ?></td>
                        <td class="px-6 py-4">
                            <span class="px-2 py-1 text-xs rounded-full <?= (($emp['employment_status'] ?? '') === 'Tetap') ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800' ?>">
                                <?= e($emp['employment_status'] ?? '-') ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 text-sm text-center space-x-2">
                            <a href="?module=data_perawat&action=edit&id=<?= (int)$emp['id'] ?>" class="text-blue-600 hover:text-blue-800">
                                <i class="fas fa-edit"></i>
                            </a>
                            <a href="?module=data_perawat&action=delete&id=<?= (int)$emp['id'] ?>" onclick="return confirm('Yakin nonaktifkan data ini?')" class="text-red-600 hover:text-red-800">
                                <i class="fas fa-trash"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>

                    <?php if (empty($employees)): ?>
                    <tr>
                        <td colspan="6" class="px-6 py-8 text-center text-gray-500">
                            <i class="fas fa-user-nurse text-4xl mb-2 text-gray-300"></i>
                            <p>Belum ada data perawat di master HR</p>
                        </td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>