<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once __DIR__ . '/../../config/database.php';
$conn = getConnection();

if (!function_exists('e')) {
    function e($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('coaching_employee_name_from_db')) {
    function coaching_employee_name_from_db(mysqli $conn, int $id): string {
        $sql = "SELECT COALESCE(NULLIF(full_name,''), NULLIF(nama,''), CONCAT('Staff #', id)) AS full_name FROM employees WHERE id = ? LIMIT 1";
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param('i', $id);
            $stmt->execute();
            $res = $stmt->get_result();
            $row = $res ? $res->fetch_assoc() : null;
            $stmt->close();
            return (string)($row['full_name'] ?? '-');
        }
        return '-';
    }
}

$vendorAutoload = __DIR__ . '/../../vendor/autoload.php';
if (!file_exists($vendorAutoload)) {
    exit('vendor/autoload.php tidak ditemukan. PhpWord belum siap.');
}
require_once $vendorAutoload;
if (!class_exists('\PhpOffice\PhpWord\PhpWord')) {
    exit('Library PhpWord tidak tersedia.');
}

$id = (int)($_GET['id'] ?? 0);
$month = trim((string)($_GET['month'] ?? date('Y-m')));
if ($id > 0) {
    $sql = "SELECT cs.*, csa.*, cc.competency_name, COALESCE(u.name,'-') AS unit_name
            FROM coaching_sessions cs
            LEFT JOIN coaching_staff_assessments csa ON csa.session_id = cs.id
            LEFT JOIN coaching_competencies cc ON cc.id = cs.competency_id
            LEFT JOIN coaching_assignments ca ON ca.id = cs.assignment_id
            LEFT JOIN units u ON u.id = ca.unit_id
            WHERE cs.id = ? LIMIT 1";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res ? $res->fetch_assoc() : null;
    $stmt->close();
    if (!$row) exit('Data sesi tidak ditemukan.');

    $phpWord = new \PhpOffice\PhpWord\PhpWord();
    $phpWord->setDefaultFontName('Times New Roman');
    $phpWord->setDefaultFontSize(11);
    $section = $phpWord->addSection(['marginTop'=>900,'marginBottom'=>900,'marginLeft'=>1000,'marginRight'=>900]);
    $section->addText('LAPORAN COACHING STAF BARU', ['bold'=>true,'size'=>14], ['align'=>'center']);
    $section->addText('RS BaliMed Denpasar', ['size'=>11], ['align'=>'center']);
    $section->addTextBreak(1);
    $coachName = coaching_employee_name_from_db($conn, (int)$row['coach_employee_id']);
    $staffName = coaching_employee_name_from_db($conn, (int)$row['staff_employee_id']);
    $lines = [
        'Tanggal Coaching: ' . $row['coaching_date'],
        'Unit: ' . $row['unit_name'],
        'Coach: ' . $coachName,
        'Staff Baru: ' . $staffName,
        'Topik: ' . $row['topic_title'],
        'Kompetensi: ' . $row['competency_name'],
        '',
        'Pre-Briefing: ' . $row['pre_briefing_notes'],
        '',
        'Observation: ' . $row['observation_notes'],
        '',
        'Reflective Feedback: ' . $row['reflective_feedback_notes'],
        '',
        'Action Plan: ' . $row['action_plan_notes'],
        '',
        'Skor Klinis: ' . $row['score_clinical'],
        'Skor Soft Skill: ' . $row['score_softskill'],
        'Skor Dokumentasi: ' . $row['score_documentation'],
        'Weighted Score: ' . $row['weighted_score'],
        'Status Kompetensi: ' . str_replace('_',' ', (string)$row['competency_status']),
        '',
        'Catatan Observasi: ' . $row['observation_note'],
        '',
        'Kekuatan: ' . $row['strengths_note'],
        '',
        'Area Perbaikan: ' . $row['improvement_note'],
    ];
    foreach ($lines as $line) $section->addText($line);
    $tempFile = tempnam(sys_get_temp_dir(), 'coach_docx_');
    $writer = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
    $writer->save($tempFile);
    $filename = 'Coaching_Session_' . $id . '.docx';
    while (ob_get_level()) ob_end_clean();
    header('Content-Description: File Transfer');
    header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: ' . filesize($tempFile));
    readfile($tempFile);
    @unlink($tempFile);
    exit;
}

$where = ["DATE_FORMAT(cs.coaching_date, '%Y-%m') = '" . $conn->real_escape_string($month) . "'"];
$unitFilter = (int)($_GET['unit_filter'] ?? 0);
$coachFilter = (int)($_GET['coach_filter'] ?? 0);
if ($unitFilter > 0) $where[] = 'ca.unit_id = ' . $unitFilter;
if ($coachFilter > 0) $where[] = 'cs.coach_employee_id = ' . $coachFilter;

$sql = "SELECT cs.coaching_date, cs.topic_title, cc.competency_name, COALESCE(u.name,'-') AS unit_name,
        cs.coach_employee_id, cs.staff_employee_id, csa.weighted_score, csa.competency_status
        FROM coaching_sessions cs
        LEFT JOIN coaching_staff_assessments csa ON csa.session_id = cs.id
        LEFT JOIN coaching_competencies cc ON cc.id = cs.competency_id
        LEFT JOIN coaching_assignments ca ON ca.id = cs.assignment_id
        LEFT JOIN units u ON u.id = ca.unit_id
        WHERE " . implode(' AND ', $where) . "
        ORDER BY cs.coaching_date DESC, cs.id DESC";
$res = $conn->query($sql);

$phpWord = new \PhpOffice\PhpWord\PhpWord();
$phpWord->setDefaultFontName('Times New Roman');
$phpWord->setDefaultFontSize(11);
$section = $phpWord->addSection(['marginTop'=>900,'marginBottom'=>900,'marginLeft'=>1000,'marginRight'=>900]);
$section->addText('REKAP COACHING STAF BARU', ['bold'=>true,'size'=>14], ['align'=>'center']);
$section->addText('Periode ' . $month, ['size'=>11], ['align'=>'center']);
$section->addTextBreak(1);
$table = $section->addTable(['borderSize'=>6,'borderColor'=>'777777','cellMargin'=>60]);
$table->addRow();
foreach (['Tanggal','Coach','Staff Baru','Topik','Kompetensi','Unit','Score','Status'] as $head) {
    $table->addCell(1600)->addText($head, ['bold'=>true]);
}
while ($res && $row = $res->fetch_assoc()) {
    $table->addRow();
    $table->addCell(1600)->addText((string)$row['coaching_date']);
    $table->addCell(1600)->addText(coaching_employee_name_from_db($conn, (int)$row['coach_employee_id']));
    $table->addCell(1600)->addText(coaching_employee_name_from_db($conn, (int)$row['staff_employee_id']));
    $table->addCell(1600)->addText((string)$row['topic_title']);
    $table->addCell(1600)->addText((string)$row['competency_name']);
    $table->addCell(1600)->addText((string)$row['unit_name']);
    $table->addCell(1600)->addText((string)$row['weighted_score']);
    $table->addCell(1600)->addText(str_replace('_',' ', (string)$row['competency_status']));
}
$tempFile = tempnam(sys_get_temp_dir(), 'coach_rekap_');
$writer = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$writer->save($tempFile);
$filename = 'Rekap_Coaching_' . preg_replace('/[^0-9\-]/', '', $month) . '.docx';
while (ob_get_level()) ob_end_clean();
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . filesize($tempFile));
readfile($tempFile);
@unlink($tempFile);
exit;
