<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

checkAuth();
$conn = getConnection();

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

$module = 'generator_surat';
$action = $_GET['action'] ?? 'list';
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$autoPrint = isset($_GET['autoprint']) && $_GET['autoprint'] === '1';

/**
 * Ambil user_id valid dari session yang benar-benar ada di tabel users
 */
if (!function_exists('getValidSessionUserId')) {
    function getValidSessionUserId(mysqli $conn): ?int
    {
        $candidateUserId = 0;

        if (!empty($_SESSION['user_id'])) {
            $candidateUserId = (int) $_SESSION['user_id'];
        } elseif (!empty($_SESSION['user']['id'])) {
            $candidateUserId = (int) $_SESSION['user']['id'];
        } elseif (!empty($_SESSION['id'])) {
            $candidateUserId = (int) $_SESSION['id'];
        }

        if ($candidateUserId <= 0) {
            return null;
        }

        $check = $conn->prepare("SELECT id FROM users WHERE id = ? LIMIT 1");
        if (!$check) {
            return null;
        }

        $check->bind_param("i", $candidateUserId);
        $check->execute();
        $res = $check->get_result();

        $valid = ($res && $res->fetch_assoc()) ? $candidateUserId : null;
        $check->close();

        return $valid;
    }
}

// Handle form submit
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'generate') {
    $perihal = trim($_POST['perihal'] ?? '');
    $tujuan = trim($_POST['tujuan'] ?? '');
    $lampiran = trim($_POST['lampiran'] ?? '') ?: '-';
    $isi_surat = trim($_POST['isi_surat'] ?? '');
    $kajian = trim($_POST['kajian'] ?? '');
    $pengirim = trim($_POST['pengirim'] ?? '') ?: ($_SESSION['full_name'] ?? '');
    $jabatan_pengirim = trim($_POST['jabatan_pengirim'] ?? '') ?: 'Kadiv Keperawatan';

    if ($perihal === '' || $tujuan === '' || $isi_surat === '') {
        echo "<script>alert('Perihal, tujuan, dan isi surat wajib diisi.');</script>";
    } else {
        $nomor_surat = function_exists('generateNomorSurat')
            ? generateNomorSurat()
            : ('SURAT-' . date('YmdHis'));

        $stmt = $conn->prepare("
            INSERT INTO surat_db
            (
                nomor_surat, tanggal_surat, lampiran, perihal, tujuan,
                isi_surat, kajian, pengirim, jabatan_pengirim,
                dibuat_oleh_username, dibuat_oleh_nama
            )
            VALUES (?, CURDATE(), ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        if (!$stmt) {
            echo "<script>alert('Prepare gagal: " . addslashes($conn->error) . "');</script>";
        } else {
            $username = (string) ($_SESSION['username'] ?? '');
            $full_name = (string) ($_SESSION['full_name'] ?? '');

            $stmt->bind_param(
                "ssssssssss",
                $nomor_surat,
                $lampiran,
                $perihal,
                $tujuan,
                $isi_surat,
                $kajian,
                $pengirim,
                $jabatan_pengirim,
                $username,
                $full_name
            );

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

                // Pakai logActivity dari includes/functions.php
                if (function_exists('logActivity')) {
                    logActivity('create', 'generator_surat', $new_id, "Membuat surat baru: {$nomor_surat}");
                }

                // Simpan juga ke tabel letters
                $attachment_count = $lampiran !== '-' ? $lampiran : '0';
                $created_by = getValidSessionUserId($conn);

                if ($created_by !== null) {
                    $stmt2 = $conn->prepare("
                        INSERT INTO letters
                        (
                            letter_no, letter_date, subject, recipient_name, recipient_address,
                            attachment_count, body_text, signer_name, signer_position, status, created_by
                        )
                        VALUES (?, CURDATE(), ?, ?, ?, ?, ?, ?, ?, 'draft', ?)
                    ");

                    if ($stmt2) {
                        $stmt2->bind_param(
                            "ssssssssi",
                            $nomor_surat,
                            $perihal,
                            $tujuan,
                            $tujuan,
                            $attachment_count,
                            $isi_surat,
                            $pengirim,
                            $jabatan_pengirim,
                            $created_by
                        );

                        if (!$stmt2->execute()) {
                            echo "<script>alert('Gagal menyimpan ke letters: " . addslashes($stmt2->error) . "');</script>";
                        }

                        $stmt2->close();
                    }
                } else {
                    $stmt2 = $conn->prepare("
                        INSERT INTO letters
                        (
                            letter_no, letter_date, subject, recipient_name, recipient_address,
                            attachment_count, body_text, signer_name, signer_position, status, created_by
                        )
                        VALUES (?, CURDATE(), ?, ?, ?, ?, ?, ?, ?, 'draft', NULL)
                    ");

                    if ($stmt2) {
                        $stmt2->bind_param(
                            "ssssssss",
                            $nomor_surat,
                            $perihal,
                            $tujuan,
                            $tujuan,
                            $attachment_count,
                            $isi_surat,
                            $pengirim,
                            $jabatan_pengirim
                        );

                        if (!$stmt2->execute()) {
                            echo "<script>alert('Gagal menyimpan ke letters: " . addslashes($stmt2->error) . "');</script>";
                        }

                        $stmt2->close();
                    }
                }

                $stmt->close();

                echo "<script>alert('Surat berhasil dibuat dengan nomor: " . addslashes($nomor_surat) . "'); window.location.href='?module={$module}&action=view&id={$new_id}';</script>";
                exit;
            } else {
                echo "<script>alert('Gagal menyimpan surat: " . addslashes($stmt->error) . "');</script>";
            }

            $stmt->close();
        }
    }
}

// Get surat untuk view
$surat = null;
if ($action === 'view' && $id > 0) {
    $stmtView = $conn->prepare("SELECT * FROM surat_db WHERE id = ? LIMIT 1");
    if ($stmtView) {
        $stmtView->bind_param("i", $id);
        $stmtView->execute();
        $resultView = $stmtView->get_result();
        if ($resultView) {
            $surat = $resultView->fetch_assoc();
        }
        $stmtView->close();
    }

    if ($surat) {
        $stmtPrint = $conn->prepare("UPDATE letters SET status = 'printed', printed_at = NOW() WHERE letter_no = ?");
        if ($stmtPrint) {
            $stmtPrint->bind_param("s", $surat['nomor_surat']);
            $stmtPrint->execute();
            $stmtPrint->close();
        }

        if (function_exists('logActivity')) {
            logActivity('print', 'generator_surat', $id, "Membuka / mencetak surat: {$surat['nomor_surat']}");
        }
    }
}

// Get all surat
$surats = [];
$result = $conn->query("SELECT * FROM surat_db ORDER BY created_at DESC LIMIT 20");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $surats[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generator Surat</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;
            color: #111827;
        }

        #suratContainer {
            background: #fff;
            color: #000;
        }

        .surat-header h2 {
            font-size: 30px;
            font-weight: 700;
            line-height: 1.25;
            margin-bottom: 6px;
        }

        .surat-header p {
            margin: 2px 0;
            font-size: 15px;
            line-height: 1.5;
        }

        .surat-meta td {
            padding: 2px 0;
            vertical-align: top;
            font-size: 18px;
            line-height: 1.6;
        }

        .surat-body,
        .surat-body p,
        .surat-body div {
            font-size: 18px;
            line-height: 1.8;
        }

        .kajian-box {
            background: #f3f4f6;
            border-radius: 12px;
            padding: 16px 18px;
            margin: 18px 0;
        }

        .ttd-box {
            margin-top: 70px;
            text-align: right;
        }

        .ttd-box p {
            margin: 4px 0;
        }

        @media print {
            @page {
                size: A4;
                margin: 22mm 20mm 22mm 20mm;
            }

            html, body {
                margin: 0 !important;
                padding: 0 !important;
                background: #fff !important;
                color: #000 !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }

            .no-print {
                display: none !important;
            }

            #suratContainer {
                width: 100% !important;
                max-width: 100% !important;
                margin: 0 !important;
                padding: 0 !important;
                box-shadow: none !important;
                border-radius: 0 !important;
                background: #fff !important;
            }

            .surat-header h2 {
                font-size: 15pt !important;
                margin-bottom: 4px !important;
            }

            .surat-header p {
                font-size: 11pt !important;
                line-height: 1.4 !important;
                margin: 1px 0 !important;
            }

            .surat-meta td,
            .surat-body,
            .surat-body p,
            .surat-body div {
                font-size: 12pt !important;
                line-height: 1.7 !important;
            }

            hr {
                border: 0 !important;
                border-top: 2px solid #000 !important;
                margin: 14px 0 24px 0 !important;
            }

            .kajian-box {
                background: #f3f4f6 !important;
                border-radius: 10px !important;
                padding: 12px 14px !important;
                page-break-inside: avoid !important;
            }

            .ttd-box {
                margin-top: 56px !important;
                page-break-inside: avoid !important;
            }

            table {
                width: 100% !important;
                border-collapse: collapse !important;
            }

            td {
                vertical-align: top !important;
            }
        }
    </style>
</head>
<body class="p-6">
    <div class="mb-6 flex justify-between items-center no-print">
        <h1 class="text-2xl font-bold text-gray-800">Generator Surat</h1>
        <div class="space-x-2">
            <button onclick="showForm()" class="bg-gradient-to-r from-blue-600 to-indigo-600 text-white px-4 py-2 rounded-lg hover:from-blue-700 hover:to-indigo-700 transition-all">
                <i class="fas fa-plus mr-2"></i> Buat Surat Baru
            </button>
            <?php if ($action === 'view' && $surat): ?>
            <button onclick="printSurat()" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-all">
                <i class="fas fa-print mr-2"></i> Cetak
            </button>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($action === 'generate'): ?>
    <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
        <h2 class="text-lg font-semibold mb-4">Form Pembuatan Surat</h2>
        <form method="POST" action="?module=<?= e($module) ?>&action=generate" 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">Perihal *</label>
                    <input type="text" name="perihal" required 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">Tujuan *</label>
                    <input type="text" name="tujuan" required 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">Lampiran</label>
                    <input type="text" name="lampiran" placeholder="Contoh: 1 lembar" 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">Pengirim</label>
                    <input type="text" name="pengirim" value="<?= e($_SESSION['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">Jabatan Pengirim</label>
                    <input type="text" name="jabatan_pengirim" value="Kadiv Keperawatan" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                </div>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Isi Surat *</label>
                <textarea name="isi_surat" rows="8" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"></textarea>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Kajian (opsional)</label>
                <textarea name="kajian" rows="4" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500" placeholder="Masukkan analisis, data pendukung, perhitungan, dll..."></textarea>
            </div>

            <div class="flex justify-end space-x-2">
                <a href="?module=<?= e($module) ?>" 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-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-lg hover:from-blue-700 hover:to-indigo-700">
                    Generate Surat
                </button>
            </div>
        </form>
    </div>

    <?php elseif ($action === 'view' && $surat): ?>
    <div class="bg-white rounded-xl shadow-lg p-8 max-w-4xl mx-auto" id="suratContainer">
        <div class="text-center mb-8 surat-header">
            <h2>RUMAH SAKIT BALIMÉD DENPASAR</h2>
            <p>Jl. Mahendradatta No. 57, Denpasar - Bali</p>
            <p>Telp. (0361) 484748 | Email: info@balimedhospital.co.id</p>
            <hr class="my-4 border-t-2 border-black">
        </div>

        <div class="mb-8 surat-meta">
            <table class="w-full">
                <tr>
                    <td width="120">Nomor</td>
                    <td width="20">:</td>
                    <td class="font-bold"><?= e($surat['nomor_surat']) ?></td>
                </tr>
                <tr>
                    <td>Lampiran</td>
                    <td>:</td>
                    <td><?= e($surat['lampiran']) ?></td>
                </tr>
                <tr>
                    <td>Perihal</td>
                    <td>:</td>
                    <td class="font-semibold"><?= e($surat['perihal']) ?></td>
                </tr>
                <tr>
                    <td>Tanggal</td>
                    <td>:</td>
                    <td><?= function_exists('formatTanggal') ? formatTanggal($surat['tanggal_surat']) : e($surat['tanggal_surat']) ?></td>
                </tr>
            </table>
        </div>

        <div class="surat-body">
            <div class="mb-8">
                <p>Kepada Yth.</p>
                <p><?= nl2br(e($surat['tujuan'])) ?></p>
            </div>

            <div class="mb-8">
                <p>Dengan hormat,</p>
                <p class="mt-3"><?= nl2br(e($surat['isi_surat'])) ?></p>
            </div>

            <?php if (!empty($surat['kajian'])): ?>
            <div class="kajian-box">
                <p class="font-semibold mb-2">Kajian:</p>
                <p><?= nl2br(e($surat['kajian'])) ?></p>
            </div>
            <?php endif; ?>

            <div class="mb-6">
                <p>Demikian surat ini kami sampaikan. Atas perhatian dan kerja samanya, kami ucapkan terima kasih.</p>
            </div>

            <div class="ttd-box">
                <p>Denpasar, <?= function_exists('formatTanggal') ? formatTanggal($surat['tanggal_surat']) : e($surat['tanggal_surat']) ?></p>
                <div style="height:80px;"></div>
                <p class="font-semibold"><?= e($surat['pengirim']) ?></p>
                <p><?= e($surat['jabatan_pengirim']) ?></p>
            </div>
        </div>
    </div>

    <?php else: ?>
    <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 tracking-wider">No. Surat</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Perihal</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tujuan</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Pembuat</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200">
                    <?php foreach ($surats as $s): ?>
                    <tr class="hover:bg-gray-50">
                        <td class="px-6 py-4 text-sm font-medium text-gray-900"><?= e($s['nomor_surat']) ?></td>
                        <td class="px-6 py-4 text-sm text-gray-600"><?= function_exists('formatTanggal') ? formatTanggal($s['tanggal_surat']) : e($s['tanggal_surat']) ?></td>
                        <td class="px-6 py-4 text-sm text-gray-900"><?= e($s['perihal']) ?></td>
                        <td class="px-6 py-4 text-sm text-gray-600"><?= e(mb_substr($s['tujuan'], 0, 30)) ?>...</td>
                        <td class="px-6 py-4 text-sm text-gray-600"><?= e($s['dibuat_oleh_nama']) ?></td>
                        <td class="px-6 py-4 text-sm space-x-2">
                            <a href="?module=<?= e($module) ?>&action=view&id=<?= (int)$s['id'] ?>" class="text-blue-600 hover:text-blue-800">
                                <i class="fas fa-eye"></i>
                            </a>
                            <a href="#" onclick="printSuratPreview(<?= (int)$s['id'] ?>); return false;" class="text-green-600 hover:text-green-800">
                                <i class="fas fa-print"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>

                    <?php if (empty($surats)): ?>
                    <tr>
                        <td colspan="6" class="px-6 py-8 text-center text-gray-500">Belum ada surat.</td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <script>
        function showForm() {
            window.location.href = '?module=<?= e($module) ?>&action=generate';
        }

        function printSurat() {
            const content = document.getElementById('suratContainer').innerHTML;
            const win = window.open('', '_blank', 'width=900,height=700');

            win.document.write(`
                <html>
                <head>
                    <title>Cetak Surat</title>
                    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
                    <style>
                        @page {
                            size: A4;
                            margin: 22mm 20mm 22mm 20mm;
                        }

                        html, body {
                            margin: 0;
                            padding: 0;
                            background: #fff;
                            color: #000;
                            font-family: 'Poppins', sans-serif;
                            -webkit-print-color-adjust: exact;
                            print-color-adjust: exact;
                        }

                        body {
                            width: 100%;
                        }

                        .print-wrap {
                            width: 100%;
                        }

                        .surat-header h2, h2 {
                            font-size: 15pt;
                            text-align: center;
                            font-weight: 700;
                            line-height: 1.25;
                            margin: 0 0 4px 0;
                        }

                        .surat-header p {
                            text-align: center;
                            font-size: 11pt;
                            line-height: 1.4;
                            margin: 1px 0;
                        }

                        p, td, div {
                            font-size: 12pt;
                            line-height: 1.7;
                            color: #000;
                        }

                        hr {
                            border: 0;
                            border-top: 2px solid #000;
                            margin: 14px 0 24px 0;
                        }

                        table {
                            width: 100%;
                            border-collapse: collapse;
                        }

                        td {
                            vertical-align: top;
                            padding: 2px 0;
                        }

                        .surat-meta {
                            margin-bottom: 28px;
                        }

                        .surat-body {
                            width: 100%;
                        }

                        .kajian-box {
                            background: #f3f4f6;
                            border-radius: 10px;
                            padding: 12px 14px;
                            margin: 18px 0;
                            page-break-inside: avoid;
                        }

                        .ttd-box {
                            margin-top: 56px;
                            text-align: right;
                            page-break-inside: avoid;
                        }

                        .ttd-box p {
                            margin: 4px 0;
                        }
                    </style>
                </head>
                <body>
                    <div class="print-wrap">${content}</div>
                </body>
                </html>
            `);

            win.document.close();

            setTimeout(function () {
                win.focus();
                win.print();
            }, 500);
        }

        function printSuratPreview(id) {
            window.location.href = '?module=<?= e($module) ?>&action=view&id=' + id + '&autoprint=1';
        }
    </script>

    <?php if ($autoPrint && $action === 'view' && $surat): ?>
    <script>
        window.addEventListener('load', function () {
            setTimeout(function () {
                printSurat();
            }, 400);
        });
    </script>
    <?php endif; ?>
</body>
</html>