<?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);
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;
    }

    mysqli_stmt_bind_param($stmt, 'iii', $user_id, $user_id, $user_id);
    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
    ) 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()
    ) 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'
    ) 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.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.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 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'
    ) latest
    ORDER BY activity_date DESC
    LIMIT 100";

$latest_letters = [];
$latest_stmt = mysqli_prepare($conn, $latest_sql);
if ($latest_stmt) {
    mysqli_stmt_bind_param($latest_stmt, 'iii', $user_id, $user_id, $user_id);
    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) : '',
        ];
    }
}

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,
]);
