<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Accept');

ob_start();

function respond(int $status_code, array $payload): void
{
    while (ob_get_level() > 0) {
        ob_end_clean();
    }

    http_response_code($status_code);
    echo json_encode($payload);
    exit;
}

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
    respond(204, []);
}

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    respond(405, [
        'success' => false,
        'message' => 'Method tidak dibenarkan.',
    ]);
}

require_once __DIR__ . '/../db.php';

$raw = file_get_contents('php://input');
$payload = json_decode($raw ?: '', true);
if (!is_array($payload)) {
    $payload = $_POST;
}

$user_id = (int) ($payload['user_id'] ?? 0);
$draft_id = (int) ($payload['draft_id'] ?? 0);

if ($user_id <= 0 || $draft_id <= 0) {
    respond(422, [
        'success' => false,
        'message' => 'Maklumat user atau surat tidak sah.',
    ]);
}

$user_stmt = mysqli_prepare($conn, 'SELECT id FROM users WHERE id = ? AND status = "approved" LIMIT 1');
if (!$user_stmt) {
    respond(500, [
        'success' => false,
        'message' => 'Ralat sistem semasa membaca pengguna.',
    ]);
}

mysqli_stmt_bind_param($user_stmt, 'i', $user_id);
mysqli_stmt_execute($user_stmt);
$user_result = mysqli_stmt_get_result($user_stmt);
if (!$user_result || !mysqli_fetch_assoc($user_result)) {
    respond(403, [
        'success' => false,
        'message' => 'Akaun tidak dibenarkan.',
    ]);
}

function formatDateLabel(?string $value, bool $include_time = false): string
{
    $value = trim((string) $value);
    if ($value === '' || $value === '0000-00-00' || $value === '0000-00-00 00:00:00') {
        return '';
    }

    $timestamp = strtotime($value);
    if (!$timestamp) {
        return '';
    }

    return $include_time ? date('j M Y, g:i A', $timestamp) : date('j M Y', $timestamp);
}

function fileSizeLabel(string $path): string
{
    if ($path === '') {
        return '';
    }

    $full_path = preg_match('/^[A-Za-z]:[\\\\\\/]/', $path) ? $path : __DIR__ . '/../' . $path;
    if (!is_file($full_path)) {
        return '';
    }

    $bytes = filesize($full_path);
    if ($bytes === false || $bytes <= 0) {
        return '';
    }

    if ($bytes >= 1048576) {
        return rtrim(rtrim(number_format($bytes / 1048576, 1), '0'), '.') . ' MB';
    }

    return max(1, (int) ceil($bytes / 1024)) . ' KB';
}

function statusLabelFromValue(string $status): string
{
    return match ($status) {
        'disokong', 'lulus' => 'Diluluskan',
        'ditolak' => 'Ditolak',
        'menunggu', 'menunggu_tandatangan',
        'menunggu_pegawai_bahagian', 'menunggu_pelulus',
        'menunggu_pelulus_akhir' => 'Menunggu',
        default => 'Surat',
    };
}

function plainTextFromLetterPages(?string $letter_pages, ?string $letter_body): string
{
    return implode("\n\n", plainTextPageList($letter_pages, $letter_body));
}

function plainTextPageList(?string $letter_pages, ?string $letter_body): array
{
    $pages = decodeDraftLetterPages($letter_pages ?? '', $letter_body ?? '');
    $page_texts = [];
    foreach ($pages as $page) {
        $page_texts[] = plainTextFromHtml((string) $page);
    }

    return !empty($page_texts) ? $page_texts : [''];
}

function plainTextFromHtml(?string $html): string
{
    $html = (string) $html;
    $html = preg_replace('/<\s*br\s*\/?\s*>/i', "\n", $html);
    $html = preg_replace('/<\s*\/\s*(p|div|li|tr|h1|h2|h3|h4|h5|h6)\s*>/i', "\n", (string) $html);
    $text = html_entity_decode(strip_tags((string) $html), ENT_QUOTES | ENT_HTML5, 'UTF-8');
    $text = preg_replace('/[ \t]+/', ' ', (string) $text);
    $text = preg_replace("/\n{3,}/", "\n\n", (string) $text);
    return trim((string) $text);
}

function fetchApprovalPages(mysqli $conn, int $draft_id, ?string $route_bodies, ?string $approval_page_body, ?array $draft = null): array
{
    $route_body_map = decodeDraftApprovalRouteBodies($route_bodies ?? '');
    $stmt = mysqli_prepare($conn, "
        SELECT
            lar.user_id,
            lar.position_label,
            lar.source_type,
            lar.status,
            lar.note,
            lar.signature_path,
            lar.responded_at,
            lar.approved_at,
            lar.route_order,
            u.fullname,
            u.position
        FROM letter_approval_recipients lar
        LEFT JOIN users u ON u.id = lar.user_id
        WHERE lar.draft_id = ?
        ORDER BY lar.route_order ASC, lar.id ASC
    ");

    if (!$stmt) {
        return [];
    }

    mysqli_stmt_bind_param($stmt, 'i', $draft_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $pages = [];
    $source_labels = [
        'kepada' => 'Kelulusan Kepada',
        'melalui' => 'Kelulusan Melalui',
        'tambahan' => 'Kelulusan',
    ];

    while ($row = $result ? mysqli_fetch_assoc($result) : null) {
        $user_key = 'user:' . (int) ($row['user_id'] ?? 0);
        $position_key = 'position:' . trim((string) ($row['position_label'] ?? ''));
        $body = $route_body_map[$user_key] ?? $route_body_map[$position_key] ?? '';

        $pages[] = [
            'label' => $source_labels[$row['source_type'] ?? ''] ?? 'Kelulusan',
            'name' => (string) (($row['fullname'] ?? '') ?: ($row['position_label'] ?? '')),
            'position' => (string) (($row['position_label'] ?? '') ?: ($row['position'] ?? '')),
            'status' => statusLabelFromValue((string) ($row['status'] ?? '')),
            'rawStatus' => (string) ($row['status'] ?? ''),
            'bodyText' => plainTextFromHtml($body),
            'note' => plainTextFromHtml($row['note'] ?? ''),
            'signatureUrl' => (string) ($row['signature_path'] ?? ''),
            'dateLabel' => formatDateLabel(($row['responded_at'] ?? '') ?: ($row['approved_at'] ?? ''), true),
        ];
    }

    if (empty($pages) && $draft && (!empty($draft['department_officer_note']) || !empty($draft['department_officer_status']))) {
        $pages[] = [
            'label' => 'Ulasan Pegawai Bahagian',
            'name' => (string) (($draft['department_officer_name'] ?? '') ?: ($draft['signatory_name'] ?? '')),
            'position' => (string) (($draft['department_officer_position'] ?? '') ?: ($draft['signatory_position'] ?? '')),
            'status' => statusLabelFromValue((string) ($draft['department_officer_status'] ?? '')),
            'rawStatus' => (string) ($draft['department_officer_status'] ?? ''),
            'bodyText' => '',
            'note' => plainTextFromHtml($draft['department_officer_note'] ?? ''),
            'signatureUrl' => (string) ($draft['department_officer_signature_path'] ?? ''),
            'dateLabel' => formatDateLabel($draft['department_officer_responded_at'] ?? null, true),
        ];
    }

    $fallback_body = plainTextFromHtml($approval_page_body ?? '');
    if (empty($pages) && $fallback_body !== '') {
        $pages[] = [
            'label' => 'Halaman Kelulusan',
            'name' => '',
            'position' => '',
            'status' => 'Surat',
            'rawStatus' => '',
            'bodyText' => $fallback_body,
            'note' => '',
            'dateLabel' => '',
        ];
    }

    $total_pages = count($pages);
    for ($i = 0; $i < $total_pages; $i++) {
        $pages[$i]['isFinalApprover'] = ($i === $total_pages - 1);
    }

    return $pages;
}

$detail_sql = "
    SELECT
        ld.id,
        ld.document_id,
        ld.ref_no,
        ld.subject,
        ld.doc_type,
        ld.recipient_organization,
        ld.attention_to,
        ld.letter_body,
        ld.letter_pages,
        ld.approval_page_body,
        ld.approval_route_bodies,
        ld.signatory_name,
        ld.signatory_position,
        ld.signatory_department,
        ld.signatory_signature_path,
        creator.signature_path AS creator_signature_path,
        ld.letter_date,
        ld.department,
        ld.created_at,
        ld.updated_at,
        ld.created_by,
        ld.updated_by,
        ld.support_user_id,
        ld.support_status,
        ld.support_requested_at,
        ld.support_responded_at,
        ld.department_officer_user_id,
        ld.department_officer_status,
        ld.department_officer_requested_at,
        ld.department_officer_responded_at,
        ld.department_officer_approved_at,
        ld.approval_status,
        creator.fullname AS applicant_name,
        creator.department AS applicant_department,
        (
            SELECT lar.status
            FROM letter_approval_recipients lar
            WHERE lar.draft_id = ld.id
              AND lar.user_id = ?
            ORDER BY lar.route_order ASC, lar.id ASC
            LIMIT 1
        ) AS recipient_status,
        (
            SELECT COALESCE(lar.responded_at, lar.approved_at, lar.requested_at, lar.updated_at, lar.created_at)
            FROM letter_approval_recipients lar
            WHERE lar.draft_id = ld.id
              AND lar.user_id = ?
            ORDER BY lar.route_order ASC, lar.id ASC
            LIMIT 1
        ) AS recipient_date
    FROM letter_drafts ld
    LEFT JOIN users creator ON creator.id = ld.created_by
    WHERE ld.id = ?
      AND ld.deleted_at IS NULL
      AND (
          ld.created_by = ?
          OR ld.updated_by = ?
          OR ld.support_user_id = ?
          OR ld.department_officer_user_id = ?
          OR EXISTS (
              SELECT 1
              FROM letter_approval_recipients access_lar
              WHERE access_lar.draft_id = ld.id
                AND access_lar.user_id = ?
          )
      )
    LIMIT 1";

$detail_stmt = mysqli_prepare($conn, $detail_sql);
if (!$detail_stmt) {
    respond(500, [
        'success' => false,
        'message' => 'Ralat sistem semasa membaca detail surat.',
    ]);
}

mysqli_stmt_bind_param(
    $detail_stmt,
    'iiiiiiii',
    $user_id,
    $user_id,
    $draft_id,
    $user_id,
    $user_id,
    $user_id,
    $user_id,
    $user_id
);
mysqli_stmt_execute($detail_stmt);
$detail_result = mysqli_stmt_get_result($detail_stmt);
$detail = $detail_result ? mysqli_fetch_assoc($detail_result) : null;

if (!$detail) {
    respond(404, [
        'success' => false,
        'message' => 'Surat tidak dijumpai atau tiada akses.',
    ]);
}

$current_status = '';
$activity_date = $detail['updated_at'] ?? '';

if ((int) ($detail['support_user_id'] ?? 0) === $user_id) {
    $current_status = (string) ($detail['support_status'] ?? '');
    $activity_date = $detail['support_responded_at'] ?: ($detail['support_requested_at'] ?: $activity_date);
}

if ((int) ($detail['department_officer_user_id'] ?? 0) === $user_id) {
    $current_status = (string) ($detail['department_officer_status'] ?? '');
    $activity_date = $detail['department_officer_responded_at']
        ?: ($detail['department_officer_approved_at'] ?: ($detail['department_officer_requested_at'] ?: $activity_date));
}

if (!empty($detail['recipient_status'])) {
    $current_status = (string) $detail['recipient_status'];
    $activity_date = $detail['recipient_date'] ?: $activity_date;
}

if ($current_status === '') {
    $current_status = (string) ($detail['approval_status'] ?? '');
}

$user_action_status = strtolower(trim((string) $current_status));
$overall_approval_status = strtolower(trim((string) ($detail['approval_status'] ?? '')));

$is_user_pending = in_array($user_action_status, ['menunggu', 'menunggu_tandatangan'], true);
$is_overall_pending = in_array($overall_approval_status, ['menunggu_pegawai_bahagian', 'menunggu_pelulus', 'menunggu_pelulus_akhir'], true);
$is_finalized = in_array($user_action_status, ['lulus', 'disokong', 'ditolak'], true) || in_array($overall_approval_status, ['lulus', 'ditolak', 'siap'], true);

$can_approve = ($is_user_pending || ($user_action_status === '' && $is_overall_pending)) && !$is_finalized;

$attachments = [];
$attachment_stmt = mysqli_prepare($conn, "
    SELECT id, file_path, original_name, created_at
    FROM document_attachments
    WHERE document_id = ?
    ORDER BY id ASC
");

if ($attachment_stmt) {
    $document_id = (int) ($detail['document_id'] ?? 0);
    mysqli_stmt_bind_param($attachment_stmt, 'i', $document_id);
    mysqli_stmt_execute($attachment_stmt);
    $attachment_result = mysqli_stmt_get_result($attachment_stmt);

    while ($row = $attachment_result ? mysqli_fetch_assoc($attachment_result) : null) {
        $file_path = (string) ($row['file_path'] ?? '');
        $original_name = (string) ($row['original_name'] ?? '');
        $file_name = $original_name !== '' ? $original_name : basename($file_path);
        $extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        $attachments[] = [
            'id' => (int) ($row['id'] ?? 0),
            'fileName' => $file_name,
            'fileType' => $extension,
            'sizeLabel' => fileSizeLabel($file_path),
            'dateLabel' => formatDateLabel($row['created_at'] ?? null),
            'viewUrl' => '/api/mobile_file.php?action=attachment&user_id=' . $user_id . '&draft_id=' . $draft_id . '&attachment_id=' . (int) ($row['id'] ?? 0),
            'downloadUrl' => '/api/mobile_file.php?action=attachment&download=1&user_id=' . $user_id . '&draft_id=' . $draft_id . '&attachment_id=' . (int) ($row['id'] ?? 0),
        ];
    }
}

respond(200, [
    'success' => true,
    'detail' => [
        'draftId' => (int) ($detail['id'] ?? 0),
        'referenceNo' => (string) ($detail['ref_no'] ?? ''),
        'title' => (string) ($detail['subject'] ?? ''),
        'documentType' => (string) ($detail['doc_type'] ?? ''),
        'status' => statusLabelFromValue($current_status),
        'canApprove' => (bool) $can_approve,
        'userStatus' => statusLabelFromValue($user_action_status),
        'rawUserStatus' => $user_action_status,
        'letterDate' => formatDateLabel($detail['letter_date'] ?? null),
        'applicant' => (string) ($detail['applicant_name'] ?? ''),
        'department' => (string) (($detail['department'] ?? '') ?: ($detail['applicant_department'] ?? '')),
        'receivedAt' => formatDateLabel($activity_date, true),
        'letterPdfUrl' => '/api/mobile_file.php?action=letter_pdf&user_id=' . $user_id . '&draft_id=' . $draft_id,
        'letterDownloadUrl' => '/api/mobile_file.php?action=letter_pdf&download=1&user_id=' . $user_id . '&draft_id=' . $draft_id,
        'recipientOrganization' => (string) ($detail['recipient_organization'] ?? ''),
        'attentionTo' => (string) ($detail['attention_to'] ?? ''),
        'signatoryName' => (string) ($detail['signatory_name'] ?? ''),
        'signatoryPosition' => (string) ($detail['signatory_position'] ?? ''),
        'signatoryDepartment' => (string) ($detail['signatory_department'] ?? ''),
        'signatorySignatureUrl' => (string) (($detail['signatory_signature_path'] ?? '') ?: ($detail['creator_signature_path'] ?? '')),
        'bodyText' => plainTextFromLetterPages($detail['letter_pages'] ?? '', $detail['letter_body'] ?? ''),
        'bodyPages' => plainTextPageList($detail['letter_pages'] ?? '', $detail['letter_body'] ?? ''),
        'approvalPages' => fetchApprovalPages($conn, $draft_id, $detail['approval_route_bodies'] ?? '', $detail['approval_page_body'] ?? '', $detail),
        'attachments' => $attachments,
    ],
]);
