<?php
// modules/coaching/index.php - Coaching Staf manual untuk domain testing.itcprogram.com
if (!isset($conn) || !($conn instanceof mysqli)) {
    require_once __DIR__ . '/../../config/database.php';
    $conn = function_exists('getConnection') ? getConnection() : null;
}
if (!$conn instanceof mysqli) {
    echo "<div class='p-4 bg-red-50 text-red-700 rounded'>Koneksi database gagal.</div>";
    return;
}

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

function coaching_manual_ensure_tables(mysqli $conn): void
{
    $conn->query("CREATE TABLE IF NOT EXISTS `coaching_manual_assignments` (
      `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
      `assignment_no` varchar(50) NOT NULL,
      `coach_employee_id` bigint(20) UNSIGNED DEFAULT NULL,
      `coach_name` varchar(180) NOT NULL,
      `coach_nik` varchar(50) DEFAULT NULL,
      `staff_employee_id` bigint(20) UNSIGNED DEFAULT NULL,
      `staff_name` varchar(180) NOT NULL,
      `staff_nik` varchar(50) DEFAULT NULL,
      `staff_unit` varchar(180) DEFAULT NULL,
      `start_date` date DEFAULT NULL,
      `target_date` date DEFAULT NULL,
      `status` enum('aktif','selesai','batal') NOT NULL DEFAULT 'aktif',
      `notes` text DEFAULT NULL,
      `created_by` bigint(20) UNSIGNED DEFAULT NULL,
      `created_at` datetime NOT NULL DEFAULT current_timestamp(),
      `updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
      PRIMARY KEY (`id`), UNIQUE KEY `uk_assignment_no` (`assignment_no`),
      KEY `idx_status` (`status`), KEY `idx_coach_name` (`coach_name`), KEY `idx_staff_name` (`staff_name`), KEY `idx_staff_unit` (`staff_unit`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    $conn->query("CREATE TABLE IF NOT EXISTS `coaching_manual_sessions` (
      `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
      `assignment_id` bigint(20) UNSIGNED NOT NULL,
      `coaching_date` date NOT NULL,
      `coaching_time` time DEFAULT NULL,
      `coaching_unit` varchar(180) DEFAULT NULL,
      `material_taught` text NOT NULL,
      `coaching_method` varchar(180) DEFAULT NULL,
      `assessment_score` decimal(5,2) DEFAULT NULL,
      `assessment_category` varchar(100) DEFAULT NULL,
      `strengths` text DEFAULT NULL,
      `improvement_notes` text DEFAULT NULL,
      `follow_up` text DEFAULT NULL,
      `next_plan` text DEFAULT NULL,
      `status_after` enum('aktif','selesai','batal') NOT NULL DEFAULT 'aktif',
      `created_by` bigint(20) UNSIGNED DEFAULT NULL,
      `updated_by` bigint(20) UNSIGNED DEFAULT NULL,
      `created_at` datetime NOT NULL DEFAULT current_timestamp(),
      `updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
      PRIMARY KEY (`id`), KEY `idx_assignment_id` (`assignment_id`), KEY `idx_coaching_date` (`coaching_date`), KEY `idx_coaching_unit` (`coaching_unit`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
}

function coaching_user_id(): int
{
    return (int)($_SESSION['user_id'] ?? $_SESSION['user']['id'] ?? 0);
}

function coaching_redirect(string $url): void
{
    echo "<script>window.location.href='" . e($url) . "';</script>";
    exit;
}

function coaching_assignment_no(mysqli $conn): string
{
    $prefix = 'COA-' . date('Ymd') . '-';
    $res = $conn->query("SELECT COUNT(*) AS total FROM coaching_manual_assignments WHERE assignment_no LIKE '" . $conn->real_escape_string($prefix) . "%' ");
    $n = 1;
    if ($res && ($row = $res->fetch_assoc())) $n = ((int)$row['total']) + 1;
    return $prefix . str_pad((string)$n, 3, '0', STR_PAD_LEFT);
}

function coaching_get_assignment(mysqli $conn, int $id): ?array
{
    $stmt = $conn->prepare("SELECT * FROM coaching_manual_assignments WHERE id = ? LIMIT 1");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $row ?: null;
}

function coaching_get_session(mysqli $conn, int $id): ?array
{
    $stmt = $conn->prepare("SELECT * FROM coaching_manual_sessions WHERE id = ? LIMIT 1");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $row ?: null;
}

function coaching_date_id(?string $date): string
{
    if (!$date || $date === '0000-00-00') return '-';
    return date('d/m/Y', strtotime($date));
}

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

// datalist karyawan dan unit
$employees = [];
$resEmp = $conn->query("SELECT e.id, e.nik, e.full_name, COALESCE(u.name, '') AS unit_name FROM employees e LEFT JOIN units u ON u.id = e.unit_id WHERE e.employment_status = 'aktif' ORDER BY e.full_name ASC LIMIT 1000");
if ($resEmp) while ($r = $resEmp->fetch_assoc()) $employees[] = $r;
$units = [];
$resUnit = $conn->query("SELECT id, name FROM units WHERE is_active = 1 ORDER BY name ASC");
if ($resUnit) while ($r = $resUnit->fetch_assoc()) $units[] = $r;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['form_type'] ?? '') === 'assignment') {
    $id = (int)($_POST['id'] ?? 0);
    $coachName = trim($_POST['coach_name'] ?? '');
    $coachNik = trim($_POST['coach_nik'] ?? '');
    $coachEmployeeId = (int)($_POST['coach_employee_id'] ?? 0) ?: null;
    $staffName = trim($_POST['staff_name'] ?? '');
    $staffNik = trim($_POST['staff_nik'] ?? '');
    $staffEmployeeId = (int)($_POST['staff_employee_id'] ?? 0) ?: null;
    $staffUnit = trim($_POST['staff_unit'] ?? '');
    $startDate = trim($_POST['start_date'] ?? '') ?: null;
    $targetDate = trim($_POST['target_date'] ?? '') ?: null;
    $status = in_array($_POST['status'] ?? 'aktif', ['aktif', 'selesai', 'batal'], true) ? $_POST['status'] : 'aktif';
    $notes = trim($_POST['notes'] ?? '');
    $uid = coaching_user_id();

    if ($coachName === '' || $staffName === '') {
        echo "<script>alert('Nama coach dan staf wajib diisi.'); window.history.back();</script>"; exit;
    }

    if ($id > 0) {
        $stmt = $conn->prepare("UPDATE coaching_manual_assignments SET coach_employee_id=?, coach_name=?, coach_nik=?, staff_employee_id=?, staff_name=?, staff_nik=?, staff_unit=?, start_date=?, target_date=?, status=?, notes=? WHERE id=?");
        $stmt->bind_param('ississsssssi', $coachEmployeeId, $coachName, $coachNik, $staffEmployeeId, $staffName, $staffNik, $staffUnit, $startDate, $targetDate, $status, $notes, $id);
        $stmt->execute(); $stmt->close();
    } else {
        $no = coaching_assignment_no($conn);
        $stmt = $conn->prepare("INSERT INTO coaching_manual_assignments (assignment_no, coach_employee_id, coach_name, coach_nik, staff_employee_id, staff_name, staff_nik, staff_unit, start_date, target_date, status, notes, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param('sississsssssi', $no, $coachEmployeeId, $coachName, $coachNik, $staffEmployeeId, $staffName, $staffNik, $staffUnit, $startDate, $targetDate, $status, $notes, $uid);
        $stmt->execute(); $id = (int)$conn->insert_id; $stmt->close();
    }
    coaching_redirect('index.php?module=coaching&action=detail&id=' . $id);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['form_type'] ?? '') === 'session') {
    $id = (int)($_POST['id'] ?? 0);
    $assignmentId = (int)($_POST['assignment_id'] ?? 0);
    $coachingDate = trim($_POST['coaching_date'] ?? date('Y-m-d'));
    $coachingTime = trim($_POST['coaching_time'] ?? '') ?: null;
    $coachingUnit = trim($_POST['coaching_unit'] ?? '');
    $material = trim($_POST['material_taught'] ?? '');
    $method = trim($_POST['coaching_method'] ?? '');
    $scoreRaw = trim($_POST['assessment_score'] ?? '');
    $score = $scoreRaw === '' ? null : (float)$scoreRaw;
    $category = trim($_POST['assessment_category'] ?? '');
    $strengths = trim($_POST['strengths'] ?? '');
    $improvement = trim($_POST['improvement_notes'] ?? '');
    $followUp = trim($_POST['follow_up'] ?? '');
    $nextPlan = trim($_POST['next_plan'] ?? '');
    $statusAfter = in_array($_POST['status_after'] ?? 'aktif', ['aktif', 'selesai', 'batal'], true) ? $_POST['status_after'] : 'aktif';
    $uid = coaching_user_id();

    if ($assignmentId <= 0 || $coachingDate === '' || $material === '') {
        echo "<script>alert('Assignment, tanggal, dan materi wajib diisi.'); window.history.back();</script>"; exit;
    }

    if ($id > 0) {
        $stmt = $conn->prepare("UPDATE coaching_manual_sessions SET coaching_date=?, coaching_time=?, coaching_unit=?, material_taught=?, coaching_method=?, assessment_score=?, assessment_category=?, strengths=?, improvement_notes=?, follow_up=?, next_plan=?, status_after=?, updated_by=? WHERE id=?");
        $stmt->bind_param('sssssdssssssii', $coachingDate, $coachingTime, $coachingUnit, $material, $method, $score, $category, $strengths, $improvement, $followUp, $nextPlan, $statusAfter, $uid, $id);
        $stmt->execute(); $stmt->close();
    } else {
        $stmt = $conn->prepare("INSERT INTO coaching_manual_sessions (assignment_id, coaching_date, coaching_time, coaching_unit, material_taught, coaching_method, assessment_score, assessment_category, strengths, improvement_notes, follow_up, next_plan, status_after, created_by, updated_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param('isssssdssssssii', $assignmentId, $coachingDate, $coachingTime, $coachingUnit, $material, $method, $score, $category, $strengths, $improvement, $followUp, $nextPlan, $statusAfter, $uid, $uid);
        $stmt->execute(); $stmt->close();
    }

    $stmt = $conn->prepare("UPDATE coaching_manual_assignments SET status=? WHERE id=?");
    $stmt->bind_param('si', $statusAfter, $assignmentId);
    $stmt->execute(); $stmt->close();
    coaching_redirect('index.php?module=coaching&action=detail&id=' . $assignmentId);
}

$badge = function(string $status): string {
    $map = [
        'aktif' => 'bg-blue-100 text-blue-700',
        'selesai' => 'bg-emerald-100 text-emerald-700',
        'batal' => 'bg-red-100 text-red-700',
    ];
    return $map[$status] ?? 'bg-slate-100 text-slate-700';
};
?>
<div class="space-y-6">
    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
            <h2 class="text-2xl font-extrabold text-slate-800">Coaching Staf Baru</h2>
            <p class="text-slate-500">Assign coach-staf manual, isi materi coaching, unit pelaksanaan, penilaian, dan riwayat sesi.</p>
        </div>
        <div class="flex flex-wrap gap-2">
            <a href="index.php?module=coaching" class="px-4 py-2 rounded-xl bg-slate-700 text-white hover:bg-slate-800"><i class="fas fa-list mr-2"></i>Daftar</a>
            <a href="index.php?module=coaching&action=form" class="px-4 py-2 rounded-xl bg-blue-600 text-white hover:bg-blue-700"><i class="fas fa-plus mr-2"></i>Assign Coach</a>
        </div>
    </div>

    <datalist id="employeeList">
        <?php foreach ($employees as $emp): ?>
            <option value="<?= e($emp['full_name']) ?>" data-id="<?= (int)$emp['id'] ?>" data-nik="<?= e($emp['nik']) ?>" data-unit="<?= e($emp['unit_name']) ?>"><?= e($emp['nik']) ?> - <?= e($emp['unit_name']) ?></option>
        <?php endforeach; ?>
    </datalist>
    <datalist id="unitList">
        <?php foreach ($units as $u): ?><option value="<?= e($u['name']) ?>"></option><?php endforeach; ?>
    </datalist>

<?php if ($action === 'form'):
    $id = (int)($_GET['id'] ?? 0);
    $row = $id ? coaching_get_assignment($conn, $id) : null;
?>
    <div class="bg-white rounded-2xl shadow p-6">
        <h3 class="text-lg font-bold mb-4"><?= $row ? 'Edit Assignment Coaching' : 'Assign Coach ke Staf' ?></h3>
        <form method="post" class="space-y-5">
            <input type="hidden" name="form_type" value="assignment">
            <input type="hidden" name="id" value="<?= (int)($row['id'] ?? 0) ?>">
            <input type="hidden" name="coach_employee_id" id="coach_employee_id" value="<?= e($row['coach_employee_id'] ?? '') ?>">
            <input type="hidden" name="staff_employee_id" id="staff_employee_id" value="<?= e($row['staff_employee_id'] ?? '') ?>">

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="p-4 rounded-xl border bg-blue-50/40">
                    <h4 class="font-bold text-blue-800 mb-3">Coach / Pembimbing</h4>
                    <label class="text-sm font-semibold">Nama Coach</label>
                    <input list="employeeList" name="coach_name" id="coach_name" value="<?= e($row['coach_name'] ?? '') ?>" class="w-full mt-1 mb-3 px-4 py-2 border rounded-xl" required>
                    <label class="text-sm font-semibold">NIK Coach</label>
                    <input name="coach_nik" id="coach_nik" value="<?= e($row['coach_nik'] ?? '') ?>" class="w-full mt-1 px-4 py-2 border rounded-xl">
                </div>
                <div class="p-4 rounded-xl border bg-emerald-50/40">
                    <h4 class="font-bold text-emerald-800 mb-3">Staf yang Dicoaching</h4>
                    <label class="text-sm font-semibold">Nama Staf</label>
                    <input list="employeeList" name="staff_name" id="staff_name" value="<?= e($row['staff_name'] ?? '') ?>" class="w-full mt-1 mb-3 px-4 py-2 border rounded-xl" required>
                    <label class="text-sm font-semibold">NIK Staf</label>
                    <input name="staff_nik" id="staff_nik" value="<?= e($row['staff_nik'] ?? '') ?>" class="w-full mt-1 mb-3 px-4 py-2 border rounded-xl">
                    <label class="text-sm font-semibold">Unit Staf / Area Awal</label>
                    <input list="unitList" name="staff_unit" id="staff_unit" value="<?= e($row['staff_unit'] ?? '') ?>" class="w-full mt-1 px-4 py-2 border rounded-xl" placeholder="Contoh: IGD / Poliklinik / VK">
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div><label class="text-sm font-semibold">Tanggal Mulai</label><input type="date" name="start_date" value="<?= e($row['start_date'] ?? date('Y-m-d')) ?>" class="w-full mt-1 px-4 py-2 border rounded-xl"></div>
                <div><label class="text-sm font-semibold">Target Selesai</label><input type="date" name="target_date" value="<?= e($row['target_date'] ?? '') ?>" class="w-full mt-1 px-4 py-2 border rounded-xl"></div>
                <div><label class="text-sm font-semibold">Status</label><select name="status" class="w-full mt-1 px-4 py-2 border rounded-xl"><option value="aktif" <?= (($row['status'] ?? 'aktif')==='aktif')?'selected':'' ?>>Aktif</option><option value="selesai" <?= (($row['status'] ?? '')==='selesai')?'selected':'' ?>>Selesai</option><option value="batal" <?= (($row['status'] ?? '')==='batal')?'selected':'' ?>>Batal</option></select></div>
                <div><label class="text-sm font-semibold">No Assignment</label><input readonly value="<?= e($row['assignment_no'] ?? 'Otomatis saat simpan') ?>" class="w-full mt-1 px-4 py-2 border rounded-xl bg-slate-50 text-slate-500"></div>
            </div>
            <div><label class="text-sm font-semibold">Catatan Assignment</label><textarea name="notes" rows="3" class="w-full mt-1 px-4 py-2 border rounded-xl resize-y"><?= e($row['notes'] ?? '') ?></textarea></div>
            <div class="flex justify-end gap-2"><a href="index.php?module=coaching" class="px-5 py-2 rounded-xl border">Batal</a><button class="px-5 py-2 rounded-xl bg-blue-600 text-white">Simpan Assignment</button></div>
        </form>
    </div>

<?php elseif ($action === 'detail'):
    $id = (int)($_GET['id'] ?? 0);
    $row = coaching_get_assignment($conn, $id);
    if (!$row): ?>
        <div class="p-4 bg-red-50 text-red-700 rounded-xl">Assignment tidak ditemukan.</div>
    <?php else:
        $stmt = $conn->prepare("SELECT * FROM coaching_manual_sessions WHERE assignment_id = ? ORDER BY coaching_date DESC, id DESC");
        $stmt->bind_param('i', $id); $stmt->execute(); $sessions = $stmt->get_result();
    ?>
    <div class="bg-white rounded-2xl shadow p-6">
        <div class="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-4">
            <div>
                <div class="text-sm text-slate-500">No Assignment</div>
                <h3 class="text-xl font-extrabold text-slate-800"><?= e($row['assignment_no']) ?></h3>
                <div class="mt-2 inline-flex px-3 py-1 rounded-full text-sm font-semibold <?= $badge($row['status']) ?>"><?= e(strtoupper($row['status'])) ?></div>
            </div>
            <div class="flex flex-wrap gap-2">
                <a href="index.php?module=coaching&action=session_form&assignment_id=<?= (int)$row['id'] ?>" class="px-4 py-2 rounded-xl bg-emerald-600 text-white"><i class="fas fa-clipboard-check mr-2"></i>Isi Sesi/Penilaian</a>
                <a href="index.php?module=coaching&action=form&id=<?= (int)$row['id'] ?>" class="px-4 py-2 rounded-xl bg-amber-500 text-white"><i class="fas fa-edit mr-2"></i>Edit Assignment</a>
            </div>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mt-5 text-sm">
            <div class="p-4 bg-slate-50 rounded-xl"><b>Coach</b><br><?= e($row['coach_name']) ?><br><span class="text-slate-500"><?= e($row['coach_nik']) ?></span></div>
            <div class="p-4 bg-slate-50 rounded-xl"><b>Staf</b><br><?= e($row['staff_name']) ?><br><span class="text-slate-500"><?= e($row['staff_nik']) ?></span></div>
            <div class="p-4 bg-slate-50 rounded-xl"><b>Unit Staf</b><br><?= e($row['staff_unit'] ?: '-') ?></div>
            <div class="p-4 bg-slate-50 rounded-xl"><b>Periode</b><br><?= e(coaching_date_id($row['start_date'])) ?> s.d. <?= e(coaching_date_id($row['target_date'])) ?></div>
        </div>
        <?php if (trim((string)$row['notes']) !== ''): ?><div class="mt-4 p-4 rounded-xl bg-blue-50 text-blue-900"><b>Catatan:</b><br><?= nl2br(e($row['notes'])) ?></div><?php endif; ?>
    </div>

    <div class="bg-white rounded-2xl shadow p-6">
        <h3 class="text-lg font-bold mb-4">Riwayat Sesi Coaching & Penilaian</h3>
        <div class="overflow-x-auto">
            <table class="w-full text-sm">
                <thead class="bg-slate-50"><tr><th class="p-3 text-left">Tanggal</th><th class="p-3 text-left">Unit Coaching</th><th class="p-3 text-left">Materi</th><th class="p-3 text-left">Nilai</th><th class="p-3 text-left">Kategori</th><th class="p-3 text-left">Tindak Lanjut</th><th class="p-3 text-center">Aksi</th></tr></thead>
                <tbody class="divide-y">
                    <?php if ($sessions->num_rows === 0): ?><tr><td colspan="7" class="p-6 text-center text-slate-500">Belum ada sesi coaching.</td></tr><?php endif; ?>
                    <?php while ($s = $sessions->fetch_assoc()): ?>
                    <tr class="align-top hover:bg-slate-50">
                        <td class="p-3 whitespace-nowrap"><?= e(coaching_date_id($s['coaching_date'])) ?><br><span class="text-slate-400"><?= e(substr((string)$s['coaching_time'], 0, 5)) ?></span></td>
                        <td class="p-3"><?= e($s['coaching_unit'] ?: '-') ?></td>
                        <td class="p-3 max-w-sm"><?= nl2br(e($s['material_taught'])) ?></td>
                        <td class="p-3 font-bold"><?= e($s['assessment_score'] !== null ? $s['assessment_score'] : '-') ?></td>
                        <td class="p-3"><?= e($s['assessment_category'] ?: '-') ?></td>
                        <td class="p-3 max-w-xs"><?= nl2br(e($s['follow_up'] ?: '-')) ?></td>
                        <td class="p-3 text-center"><a class="px-3 py-1 rounded-lg bg-amber-500 text-white" href="index.php?module=coaching&action=session_form&assignment_id=<?= (int)$row['id'] ?>&session_id=<?= (int)$s['id'] ?>">Edit</a></td>
                    </tr>
                    <?php endwhile; $stmt->close(); ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

<?php elseif ($action === 'session_form'):
    $assignmentId = (int)($_GET['assignment_id'] ?? 0);
    $assignment = coaching_get_assignment($conn, $assignmentId);
    $sessionId = (int)($_GET['session_id'] ?? 0);
    $session = $sessionId ? coaching_get_session($conn, $sessionId) : null;
    if (!$assignment): ?>
        <div class="p-4 bg-red-50 text-red-700 rounded-xl">Assignment tidak ditemukan.</div>
    <?php else: ?>
    <div class="bg-white rounded-2xl shadow p-6">
        <h3 class="text-lg font-bold mb-1"><?= $session ? 'Edit Sesi Coaching' : 'Isi Sesi Coaching & Penilaian' ?></h3>
        <p class="text-slate-500 mb-5">Coach: <b><?= e($assignment['coach_name']) ?></b> → Staf: <b><?= e($assignment['staff_name']) ?></b></p>
        <form method="post" class="space-y-5">
            <input type="hidden" name="form_type" value="session">
            <input type="hidden" name="id" value="<?= (int)($session['id'] ?? 0) ?>">
            <input type="hidden" name="assignment_id" value="<?= (int)$assignment['id'] ?>">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div><label class="text-sm font-semibold">Tanggal Coaching</label><input type="date" name="coaching_date" value="<?= e($session['coaching_date'] ?? date('Y-m-d')) ?>" class="w-full mt-1 px-4 py-2 border rounded-xl" required></div>
                <div><label class="text-sm font-semibold">Jam</label><input type="time" name="coaching_time" value="<?= e(isset($session['coaching_time']) ? substr((string)$session['coaching_time'],0,5) : '') ?>" class="w-full mt-1 px-4 py-2 border rounded-xl"></div>
                <div class="md:col-span-2"><label class="text-sm font-semibold">Unit Dilakukan Coaching</label><input list="unitList" name="coaching_unit" value="<?= e($session['coaching_unit'] ?? $assignment['staff_unit'] ?? '') ?>" class="w-full mt-1 px-4 py-2 border rounded-xl" placeholder="Contoh: IGD / VK / Ruang Bayi"></div>
            </div>
            <div><label class="text-sm font-semibold">Materi yang Diajarkan</label><textarea name="material_taught" rows="4" class="w-full mt-1 px-4 py-2 border rounded-xl resize-y" required placeholder="Isi manual: komunikasi SBAR, orientasi alat, edukasi pasien, alur transfer, dll."><?= e($session['material_taught'] ?? '') ?></textarea></div>
            <div><label class="text-sm font-semibold">Metode Coaching</label><input name="coaching_method" value="<?= e($session['coaching_method'] ?? '') ?>" class="w-full mt-1 px-4 py-2 border rounded-xl" placeholder="Contoh: demonstrasi, bedside teaching, observasi langsung, diskusi reflektif"></div>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div><label class="text-sm font-semibold">Nilai</label><input type="number" step="0.01" min="0" max="100" name="assessment_score" value="<?= e($session['assessment_score'] ?? '') ?>" class="w-full mt-1 px-4 py-2 border rounded-xl"></div>
                <div><label class="text-sm font-semibold">Kategori Penilaian</label><input name="assessment_category" value="<?= e($session['assessment_category'] ?? '') ?>" class="w-full mt-1 px-4 py-2 border rounded-xl" placeholder="Baik / Cukup / Perlu Bimbingan"></div>
                <div><label class="text-sm font-semibold">Status Setelah Coaching</label><select name="status_after" class="w-full mt-1 px-4 py-2 border rounded-xl"><option value="aktif" <?= (($session['status_after'] ?? $assignment['status'])==='aktif')?'selected':'' ?>>Aktif / lanjut coaching</option><option value="selesai" <?= (($session['status_after'] ?? '')==='selesai')?'selected':'' ?>>Selesai</option><option value="batal" <?= (($session['status_after'] ?? '')==='batal')?'selected':'' ?>>Batal</option></select></div>
            </div>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div><label class="text-sm font-semibold">Hal yang Sudah Baik</label><textarea name="strengths" rows="3" class="w-full mt-1 px-4 py-2 border rounded-xl resize-y"><?= e($session['strengths'] ?? '') ?></textarea></div>
                <div><label class="text-sm font-semibold">Catatan Perbaikan</label><textarea name="improvement_notes" rows="3" class="w-full mt-1 px-4 py-2 border rounded-xl resize-y"><?= e($session['improvement_notes'] ?? '') ?></textarea></div>
                <div><label class="text-sm font-semibold">Tindak Lanjut</label><textarea name="follow_up" rows="3" class="w-full mt-1 px-4 py-2 border rounded-xl resize-y"><?= e($session['follow_up'] ?? '') ?></textarea></div>
                <div><label class="text-sm font-semibold">Rencana Coaching Berikutnya</label><textarea name="next_plan" rows="3" class="w-full mt-1 px-4 py-2 border rounded-xl resize-y"><?= e($session['next_plan'] ?? '') ?></textarea></div>
            </div>
            <div class="flex justify-end gap-2"><a href="index.php?module=coaching&action=detail&id=<?= (int)$assignment['id'] ?>" class="px-5 py-2 rounded-xl border">Batal</a><button class="px-5 py-2 rounded-xl bg-emerald-600 text-white">Simpan Sesi</button></div>
        </form>
    </div>
    <?php endif; ?>

<?php else:
    $q = trim($_GET['q'] ?? '');
    $status = $_GET['status'] ?? '';
    $where = [];
    $types = '';
    $params = [];
    if ($q !== '') { $like = '%' . $q . '%'; $where[] = "(assignment_no LIKE ? OR coach_name LIKE ? OR staff_name LIKE ? OR staff_unit LIKE ?)"; $types .= 'ssss'; array_push($params, $like, $like, $like, $like); }
    if (in_array($status, ['aktif','selesai','batal'], true)) { $where[] = 'status = ?'; $types .= 's'; $params[] = $status; }
    $sql = "SELECT a.*, (SELECT COUNT(*) FROM coaching_manual_sessions s WHERE s.assignment_id = a.id) AS total_sesi FROM coaching_manual_assignments a" . ($where ? ' WHERE ' . implode(' AND ', $where) : '') . " ORDER BY a.updated_at DESC, a.id DESC";
    $stmt = $conn->prepare($sql);
    if ($params) $stmt->bind_param($types, ...$params);
    $stmt->execute(); $list = $stmt->get_result();
?>
    <div class="bg-white rounded-2xl shadow p-5">
        <form method="get" class="grid grid-cols-1 md:grid-cols-5 gap-3 items-end">
            <input type="hidden" name="module" value="coaching">
            <div class="md:col-span-3"><label class="text-sm font-semibold">Cari</label><input name="q" value="<?= e($q) ?>" class="w-full mt-1 px-4 py-2 border rounded-xl" placeholder="Cari coach, staf, unit, no assignment"></div>
            <div><label class="text-sm font-semibold">Status</label><select name="status" class="w-full mt-1 px-4 py-2 border rounded-xl"><option value="">Semua</option><option value="aktif" <?= $status==='aktif'?'selected':'' ?>>Aktif</option><option value="selesai" <?= $status==='selesai'?'selected':'' ?>>Selesai</option><option value="batal" <?= $status==='batal'?'selected':'' ?>>Batal</option></select></div>
            <button class="px-4 py-2 rounded-xl bg-blue-600 text-white">Tampilkan</button>
        </form>
    </div>
    <div class="bg-white rounded-2xl shadow p-6">
        <div class="overflow-x-auto">
            <table class="w-full text-sm">
                <thead class="bg-slate-50"><tr><th class="p-3 text-left">No</th><th class="p-3 text-left">Coach</th><th class="p-3 text-left">Staf</th><th class="p-3 text-left">Unit</th><th class="p-3 text-left">Periode</th><th class="p-3 text-center">Sesi</th><th class="p-3 text-left">Status</th><th class="p-3 text-center">Aksi</th></tr></thead>
                <tbody class="divide-y">
                    <?php if ($list->num_rows === 0): ?><tr><td colspan="8" class="p-8 text-center text-slate-500">Belum ada assignment coaching.</td></tr><?php endif; ?>
                    <?php while ($r = $list->fetch_assoc()): ?>
                    <tr class="hover:bg-slate-50">
                        <td class="p-3 font-semibold"><?= e($r['assignment_no']) ?></td>
                        <td class="p-3"><?= e($r['coach_name']) ?><br><span class="text-slate-400"><?= e($r['coach_nik']) ?></span></td>
                        <td class="p-3"><?= e($r['staff_name']) ?><br><span class="text-slate-400"><?= e($r['staff_nik']) ?></span></td>
                        <td class="p-3"><?= e($r['staff_unit'] ?: '-') ?></td>
                        <td class="p-3"><?= e(coaching_date_id($r['start_date'])) ?> s.d. <?= e(coaching_date_id($r['target_date'])) ?></td>
                        <td class="p-3 text-center font-bold"><?= (int)$r['total_sesi'] ?></td>
                        <td class="p-3"><span class="px-3 py-1 rounded-full text-xs font-bold <?= $badge($r['status']) ?>"><?= e(strtoupper($r['status'])) ?></span></td>
                        <td class="p-3 text-center whitespace-nowrap"><a href="index.php?module=coaching&action=detail&id=<?= (int)$r['id'] ?>" class="px-3 py-1 rounded-lg bg-blue-600 text-white">Detail</a></td>
                    </tr>
                    <?php endwhile; $stmt->close(); ?>
                </tbody>
            </table>
        </div>
    </div>
<?php endif; ?>
</div>
<script>
(function(){
  const opts = Array.from(document.querySelectorAll('#employeeList option')).map(o => ({name:o.value, id:o.dataset.id||'', nik:o.dataset.nik||'', unit:o.dataset.unit||''}));
  function bind(nameId, nikId, hiddenId, unitId){
    const name = document.getElementById(nameId); if(!name) return;
    name.addEventListener('change', function(){
      const found = opts.find(x => x.name === this.value);
      if(!found) return;
      const nik = document.getElementById(nikId); if(nik) nik.value = found.nik;
      const hid = document.getElementById(hiddenId); if(hid) hid.value = found.id;
      const unit = unitId ? document.getElementById(unitId) : null; if(unit && !unit.value) unit.value = found.unit;
    });
  }
  bind('coach_name','coach_nik','coach_employee_id', null);
  bind('staff_name','staff_nik','staff_employee_id', 'staff_unit');
})();
</script>
