<?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, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    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);
if ($user_id <= 0) {
    respond(422, [
        'success' => false,
        'message' => 'User 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 fetchCount(mysqli $conn, string $sql, int $user_id): int
{
    $stmt = mysqli_prepare($conn, $sql);
    if (!$stmt) {
        return 0;
    }

    $count = substr_count($sql, '?');
    if ($count > 0) {
        $types = str_repeat('i', $count);
        $params = array_fill(0, $count, $user_id);
        mysqli_stmt_bind_param($stmt, $types, ...$params);
    }

    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $row = $result ? mysqli_fetch_assoc($result) : null;
    return (int) ($row['total'] ?? 0);
}

$pending_sql = "
    SELECT COUNT(DISTINCT id) AS total FROM (
        SELECT ld.id, 'support' AS source
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.support_user_id = ?
          AND ld.support_status = 'menunggu'
        UNION ALL
        SELECT ld.id, 'department_officer' AS source
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.department_officer_user_id = ?
          AND ld.department_officer_status IN ('menunggu','menunggu_tandatangan')
        UNION ALL
        SELECT lar.draft_id AS id, CONCAT('recipient-', lar.id) AS source
        FROM letter_approval_recipients lar
        INNER JOIN letter_drafts ld ON ld.id = lar.draft_id
        WHERE ld.deleted_at IS NULL
          AND lar.user_id = ?
          AND lar.status IN ('menunggu','menunggu_tandatangan')
    ) pending_actions";

$completed_sql = "
    SELECT COUNT(DISTINCT id) AS total FROM (
        SELECT ld.id, 'support' AS source
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.support_user_id = ?
          AND ld.support_status IN ('disokong','ditolak')
          AND ld.support_responded_at IS NOT NULL
        UNION ALL
        SELECT ld.id, 'department_officer' AS source
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.department_officer_user_id = ?
          AND ld.department_officer_status IN ('lulus','ditolak')
          AND ld.department_officer_responded_at IS NOT NULL
        UNION ALL
        SELECT lar.draft_id AS id, CONCAT('recipient-', lar.id) AS source
        FROM letter_approval_recipients lar
        INNER JOIN letter_drafts ld ON ld.id = lar.draft_id
        WHERE ld.deleted_at IS NULL
          AND lar.user_id = ?
          AND lar.status IN ('lulus','ditolak')
          AND lar.responded_at IS NOT NULL
        UNION ALL
        SELECT ld.id, 'creator' AS source
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.created_by = ?
          AND ld.approval_status IN ('lulus','ditolak')
    ) completed_actions";

$signature_sql = "
    SELECT COUNT(DISTINCT id) AS total FROM (
        SELECT ld.id, 'department_officer' AS source
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.department_officer_user_id = ?
          AND ld.department_officer_status = 'menunggu_tandatangan'
        UNION ALL
        SELECT ld.id, 'unused' AS source
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.support_user_id = ?
          AND 1 = 0
        UNION ALL
        SELECT lar.draft_id AS id, CONCAT('recipient-', lar.id) AS source
        FROM letter_approval_recipients lar
        INNER JOIN letter_drafts ld ON ld.id = lar.draft_id
        WHERE ld.deleted_at IS NULL
          AND lar.user_id = ?
          AND lar.status = 'menunggu_tandatangan'
    ) signature_actions";

$pending_count = fetchCount($conn, $pending_sql, $user_id);
$completed_count = fetchCount($conn, $completed_sql, $user_id);
$signature_count = fetchCount($conn, $signature_sql, $user_id);

$approval_sql = "
    SELECT COUNT(DISTINCT id) AS total FROM (
        SELECT ld.id, 'department_officer' AS source
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.department_officer_user_id = ?
          AND ld.department_officer_status = 'menunggu'
        UNION ALL
        SELECT lar.draft_id AS id, CONCAT('recipient-', lar.id) AS source
        FROM letter_approval_recipients lar
        INNER JOIN letter_drafts ld ON ld.id = lar.draft_id
        WHERE ld.deleted_at IS NULL
          AND lar.user_id = ?
          AND lar.status = 'menunggu'
        UNION ALL
        SELECT ld.id, 'support' AS source
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.support_user_id = ?
          AND ld.support_status = 'menunggu'
    ) approval_actions";

$approved_today_sql = "
    SELECT COUNT(DISTINCT id) AS total FROM (
        SELECT ld.id, 'support' AS source
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.support_user_id = ?
          AND ld.support_status = 'disokong'
          AND DATE(ld.support_responded_at) = CURDATE()
        UNION ALL
        SELECT ld.id, 'department_officer' AS source
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.department_officer_user_id = ?
          AND ld.department_officer_status = 'lulus'
          AND DATE(COALESCE(ld.department_officer_responded_at, ld.department_officer_approved_at)) = CURDATE()
        UNION ALL
        SELECT lar.draft_id AS id, CONCAT('recipient-', lar.id) AS source
        FROM letter_approval_recipients lar
        INNER JOIN letter_drafts ld ON ld.id = lar.draft_id
        WHERE ld.deleted_at IS NULL
          AND lar.user_id = ?
          AND lar.status = 'lulus'
          AND DATE(COALESCE(lar.responded_at, lar.approved_at)) = CURDATE()
        UNION ALL
        SELECT ld.id, 'creator' AS source
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.created_by = ?
          AND ld.approval_status = 'lulus'
          AND DATE(ld.updated_at) = CURDATE()
    ) approved_today";

$rejected_sql = "
    SELECT COUNT(DISTINCT id) AS total FROM (
        SELECT ld.id, 'support' AS source
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.support_user_id = ?
          AND ld.support_status = 'ditolak'
        UNION ALL
        SELECT ld.id, 'department_officer' AS source
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.department_officer_user_id = ?
          AND ld.department_officer_status = 'ditolak'
        UNION ALL
        SELECT lar.draft_id AS id, CONCAT('recipient-', lar.id) AS source
        FROM letter_approval_recipients lar
        INNER JOIN letter_drafts ld ON ld.id = lar.draft_id
        WHERE ld.deleted_at IS NULL
          AND lar.user_id = ?
          AND lar.status = 'ditolak'
        UNION ALL
        SELECT ld.id, 'creator' AS source
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.created_by = ?
          AND ld.approval_status = 'ditolak'
    ) rejected_actions";

$approval_count = fetchCount($conn, $approval_sql, $user_id);
$approved_today_count = fetchCount($conn, $approved_today_sql, $user_id);
$rejected_count = fetchCount($conn, $rejected_sql, $user_id);

$task_sql = "
    SELECT * FROM (
        SELECT
            ld.id AS draft_id,
            ld.ref_no,
            ld.subject,
            ld.doc_type,
            'Sokongan diperlukan' AS status_label,
            'support' AS action_type,
            'review' AS icon_type,
            3 AS priority,
            COALESCE(ld.support_requested_at, ld.updated_at, ld.created_at) AS action_date
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.support_user_id = ?
          AND ld.support_status = 'menunggu'
        UNION ALL
        SELECT
            ld.id AS draft_id,
            ld.ref_no,
            ld.subject,
            ld.doc_type,
            CASE
                WHEN ld.department_officer_status = 'menunggu_tandatangan' THEN 'Menunggu tandatangan'
                ELSE 'Semakan pegawai bahagian'
            END AS status_label,
            'department_officer' AS action_type,
            CASE
                WHEN ld.department_officer_status = 'menunggu_tandatangan' THEN 'signature'
                ELSE 'review'
            END AS icon_type,
            CASE
                WHEN ld.department_officer_status = 'menunggu_tandatangan' THEN 1
                ELSE 2
            END AS priority,
            COALESCE(ld.department_officer_requested_at, ld.updated_at, ld.created_at) AS action_date
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.department_officer_user_id = ?
          AND ld.department_officer_status IN ('menunggu','menunggu_tandatangan')
        UNION ALL
        SELECT
            ld.id AS draft_id,
            ld.ref_no,
            ld.subject,
            ld.doc_type,
            CASE
                WHEN lar.status = 'menunggu_tandatangan' THEN 'Menunggu tandatangan'
                ELSE 'Kelulusan diperlukan'
            END AS status_label,
            'recipient' AS action_type,
            CASE
                WHEN lar.status = 'menunggu_tandatangan' THEN 'signature'
                ELSE 'approval'
            END AS icon_type,
            CASE
                WHEN lar.status = 'menunggu_tandatangan' THEN 1
                ELSE 2
            END AS priority,
            COALESCE(lar.requested_at, lar.updated_at, lar.created_at) AS action_date
        FROM letter_approval_recipients lar
        INNER JOIN letter_drafts ld ON ld.id = lar.draft_id
        WHERE ld.deleted_at IS NULL
          AND lar.user_id = ?
          AND lar.status IN ('menunggu','menunggu_tandatangan')
    ) tasks
    ORDER BY priority ASC, action_date DESC
    LIMIT 10";

$tasks = [];
$task_stmt = mysqli_prepare($conn, $task_sql);
if ($task_stmt) {
    mysqli_stmt_bind_param($task_stmt, 'iii', $user_id, $user_id, $user_id);
    mysqli_stmt_execute($task_stmt);
    $task_result = mysqli_stmt_get_result($task_stmt);
    $seen_drafts = [];
    while ($row = $task_result ? mysqli_fetch_assoc($task_result) : null) {
        $draft_id = (int) ($row['draft_id'] ?? 0);
        if ($draft_id > 0 && isset($seen_drafts[$draft_id])) {
            continue;
        }
        if ($draft_id > 0) {
            $seen_drafts[$draft_id] = true;
        }

        $tasks[] = [
            'draftId' => $draft_id,
            'referenceNo' => (string) ($row['ref_no'] ?? ''),
            'title' => (string) ($row['subject'] ?? ''),
            'documentType' => (string) ($row['doc_type'] ?? ''),
            'status' => (string) ($row['status_label'] ?? ''),
            'actionType' => (string) ($row['action_type'] ?? ''),
            'iconType' => (string) ($row['icon_type'] ?? ''),
        ];
    }
}

$latest_sql = "
    SELECT * FROM (
        SELECT
            ld.id AS draft_id,
            ld.ref_no,
            ld.subject,
            ld.doc_type,
            CASE
                WHEN ld.approval_status = 'perlu_pindaan_penyedia' OR ld.support_status = 'perlu_pindaan_penyedia' THEN 'Pindaan'
                WHEN ld.support_status = 'menunggu' THEN 'Menunggu'
                WHEN ld.support_status = 'disokong' THEN 'Diluluskan'
                WHEN ld.support_status = 'ditolak' THEN 'Ditolak'
                ELSE 'Surat'
            END AS status_label,
            COALESCE(ld.support_responded_at, ld.support_requested_at, ld.updated_at, ld.created_at) AS activity_date
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.support_user_id = ?
          AND ld.support_status <> 'tidak_perlu'
        UNION ALL
        SELECT
            ld.id AS draft_id,
            ld.ref_no,
            ld.subject,
            ld.doc_type,
            CASE
                WHEN ld.approval_status = 'perlu_pindaan_penyedia' OR ld.department_officer_status = 'perlu_pindaan_penyedia' THEN 'Pindaan'
                WHEN ld.department_officer_status IN ('menunggu','menunggu_tandatangan') THEN 'Menunggu'
                WHEN ld.department_officer_status = 'lulus' THEN 'Diluluskan'
                WHEN ld.department_officer_status = 'ditolak' THEN 'Ditolak'
                ELSE 'Surat'
            END AS status_label,
            COALESCE(ld.department_officer_responded_at, ld.department_officer_approved_at, ld.department_officer_requested_at, ld.updated_at, ld.created_at) AS activity_date
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.department_officer_user_id = ?
          AND ld.department_officer_status <> 'tidak_perlu'
        UNION ALL
        SELECT
            ld.id AS draft_id,
            ld.ref_no,
            ld.subject,
            ld.doc_type,
            CASE
                WHEN ld.approval_status = 'perlu_pindaan_penyedia' THEN 'Pindaan'
                WHEN lar.status IN ('menunggu','menunggu_tandatangan') THEN 'Menunggu'
                WHEN lar.status = 'lulus' THEN 'Diluluskan'
                WHEN lar.status = 'ditolak' THEN 'Ditolak'
                ELSE 'Surat'
            END AS status_label,
            COALESCE(lar.responded_at, lar.approved_at, lar.requested_at, lar.updated_at, lar.created_at) AS activity_date
        FROM letter_approval_recipients lar
        INNER JOIN letter_drafts ld ON ld.id = lar.draft_id
        WHERE ld.deleted_at IS NULL
          AND lar.user_id = ?
          AND lar.status <> 'belum_mula'
        UNION ALL
        SELECT
            ld.id AS draft_id,
            ld.ref_no,
            ld.subject,
            ld.doc_type,
            CASE
                WHEN ld.approval_status = 'lulus' THEN 'Diluluskan'
                WHEN ld.approval_status = 'ditolak' THEN 'Ditolak'
                WHEN ld.approval_status = 'perlu_pindaan_penyedia' THEN 'Pindaan'
                ELSE 'Edaran'
            END AS status_label,
            COALESCE(ld.updated_at, ld.created_at) AS activity_date
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.distribution_staff_list IS NOT NULL
          AND ld.distribution_staff_list != ''
          AND ld.distribution_staff_list != '[]'
          AND (
              ld.distribution_staff_list LIKE CONCAT('%\"', ?, '\"%')
              OR ld.distribution_staff_list LIKE CONCAT('%[', ?, ',%')
              OR ld.distribution_staff_list LIKE CONCAT('%,', ?, ',%')
              OR ld.distribution_staff_list LIKE CONCAT('%,', ?, ']%')
              OR ld.distribution_staff_list LIKE CONCAT('%[', ?, ']%')
          )
        UNION ALL
        SELECT
            ld.id AS draft_id,
            ld.ref_no,
            ld.subject,
            ld.doc_type,
            CASE
                WHEN ld.approval_status = 'lulus' THEN 'Diluluskan'
                WHEN ld.approval_status = 'ditolak' THEN 'Ditolak'
                WHEN ld.approval_status = 'perlu_pindaan_penyedia' THEN 'Pindaan'
                WHEN ld.approval_status IN ('menunggu_pelulus','menunggu_pegawai_bahagian','menunggu_pelulus_akhir','menunggu','dalam_proses') THEN 'Menunggu'
                ELSE 'Surat'
            END AS status_label,
            COALESCE(ld.updated_at, ld.created_at) AS activity_date
        FROM letter_drafts ld
        WHERE ld.deleted_at IS NULL
          AND ld.created_by = ?
    ) latest
    ORDER BY activity_date DESC
    LIMIT 100";

$latest_letters = [];
$latest_stmt = mysqli_prepare($conn, $latest_sql);
if ($latest_stmt) {
    $latest_count = substr_count($latest_sql, '?');
    $latest_types = str_repeat('i', $latest_count);
    $latest_params = array_fill(0, $latest_count, $user_id);
    mysqli_stmt_bind_param($latest_stmt, $latest_types, ...$latest_params);
    mysqli_stmt_execute($latest_stmt);
    $latest_result = mysqli_stmt_get_result($latest_stmt);
    $seen_latest = [];
    while ($row = $latest_result ? mysqli_fetch_assoc($latest_result) : null) {
        $draft_id = (int) ($row['draft_id'] ?? 0);
        if ($draft_id > 0 && isset($seen_latest[$draft_id])) {
            continue;
        }
        if ($draft_id > 0) {
            $seen_latest[$draft_id] = true;
        }

        $activity_date = (string) ($row['activity_date'] ?? '');
        $timestamp = $activity_date !== '' ? strtotime($activity_date) : false;

        $latest_letters[] = [
            'draftId' => $draft_id,
            'referenceNo' => (string) ($row['ref_no'] ?? ''),
            'title' => (string) ($row['subject'] ?? ''),
            'documentType' => (string) ($row['doc_type'] ?? ''),
            'status' => (string) ($row['status_label'] ?? 'Surat'),
            'dateLabel' => $timestamp ? date('j M Y', $timestamp) : '',
            'activityDate' => $activity_date,
        ];
    }
}

function formatDashboardDateLabel(?string $date_str): string {
    if (!$date_str) return '';
    $ts = strtotime($date_str);
    if (!$ts) return '';
    return date('j M Y, g:i a', $ts);
}

$notifications = [];
$notif_query = mysqli_prepare($conn, "
    SELECT id, title, body, notification_type, payload_json, is_read, created_at
    FROM push_notifications
    WHERE user_id = ?
    ORDER BY id DESC
    LIMIT 60
");
if ($notif_query) {
    mysqli_stmt_bind_param($notif_query, 'i', $user_id);
    mysqli_stmt_execute($notif_query);
    $notif_res = mysqli_stmt_get_result($notif_query);
    while ($nrow = $notif_res ? mysqli_fetch_assoc($notif_res) : null) {
        $p_data = json_decode($nrow['payload_json'] ?? '', true);
        $d_id = (int) ($p_data['draft_id'] ?? 0);
        $notifications[] = [
            'id' => 'push-' . $nrow['id'],
            'notificationId' => (int) $nrow['id'],
            'title' => (string) ($nrow['title'] ?? ''),
            'body' => (string) ($nrow['body'] ?? ''),
            'type' => (string) ($nrow['notification_type'] ?? 'general'),
            'draftId' => $d_id,
            'isRead' => (int) ($nrow['is_read'] ?? 0) === 1,
            'createdAt' => (string) ($nrow['created_at'] ?? ''),
            'dateLabel' => formatDashboardDateLabel($nrow['created_at'] ?? null),
        ];
    }
}

respond(200, [
    'success' => true,
    'summary' => [
        'pending' => $pending_count,
        'completed' => $completed_count,
        'signature' => $signature_count,
        'approval' => $approval_count,
        'approvedToday' => $approved_today_count,
        'rejected' => $rejected_count,
    ],
    'tasks' => $tasks,
    'latestLetters' => $latest_letters,
    'notifications' => $notifications,
]);
