<?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';
require_once __DIR__ . '/../includes/push_service.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);
$action = strtolower(trim((string) ($payload['action'] ?? '')));
$note = trim((string) ($payload['note'] ?? ''));

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

if (!in_array($action, ['approve', 'lulus', 'sahkan', 'sign', 'request_revision', 'pindaan', 'revision', 'reject', 'tolak'], true)) {
    respond(422, [
        'success' => false,
        'message' => 'Tindakan tidak sah.',
    ]);
}

$user_stmt = mysqli_prepare($conn, 'SELECT id, fullname, position, department, signature_path 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);
$current_user = $user_result ? mysqli_fetch_assoc($user_result) : null;

if (!$current_user) {
    respond(403, [
        'success' => false,
        'message' => 'Akaun tidak dibenarkan.',
    ]);
}

$signature_path = trim((string) ($current_user['signature_path'] ?? ''));
if ($signature_path === '') {
    $possible_sig1 = 'uploads/signatures/signature_user_' . $user_id . '.png';
    $possible_sig2 = 'uploads/signatures/user_' . $user_id . '.png';
    if (is_file(__DIR__ . '/../' . $possible_sig1)) {
        $signature_path = $possible_sig1;
    } elseif (is_file(__DIR__ . '/../' . $possible_sig2)) {
        $signature_path = $possible_sig2;
    }
}

if (in_array($action, ['approve', 'lulus', 'sahkan', 'sign'], true) && $signature_path === '') {
    respond(400, [
        'success' => false,
        'message' => 'Tandatangan anda belum didaftarkan dalam sistem. Sila simpan atau lukis tandatangan di profil dahulu.',
    ]);
}

$draft_stmt = mysqli_prepare($conn, 'SELECT * FROM letter_drafts WHERE id = ? AND deleted_at IS NULL LIMIT 1 FOR UPDATE');
if (!$draft_stmt) {
    respond(500, [
        'success' => false,
        'message' => 'Ralat sistem membaca surat.',
    ]);
}

mysqli_begin_transaction($conn);
mysqli_stmt_bind_param($draft_stmt, 'i', $draft_id);
mysqli_stmt_execute($draft_stmt);
$draft_result = mysqli_stmt_get_result($draft_stmt);
$draft = $draft_result ? mysqli_fetch_assoc($draft_result) : null;

if (!$draft) {
    mysqli_rollback($conn);
    respond(404, [
        'success' => false,
        'message' => 'Surat tidak dijumpai.',
    ]);
}

$check_rec_stmt = mysqli_prepare($conn, 'SELECT status FROM letter_approval_recipients WHERE draft_id = ? AND user_id = ? LIMIT 1');
$check_rec = null;
if ($check_rec_stmt) {
    mysqli_stmt_bind_param($check_rec_stmt, 'ii', $draft_id, $user_id);
    mysqli_stmt_execute($check_rec_stmt);
    $check_rec_res = mysqli_stmt_get_result($check_rec_stmt);
    $check_rec = $check_rec_res ? mysqli_fetch_assoc($check_rec_res) : null;
}

if ($check_rec) {
    $rec_status = strtolower((string) ($check_rec['status'] ?? ''));
    if (in_array($rec_status, ['lulus', 'ditolak'], true)) {
        mysqli_rollback($conn);
        respond(400, [
            'success' => false,
            'message' => 'Keputusan anda untuk surat ini telah muktamad dan tidak boleh diubah lagi.',
        ]);
    }
} else {
    $draft_approval_status = strtolower((string) ($draft['approval_status'] ?? ''));
    if (in_array($draft_approval_status, ['lulus', 'ditolak'], true)) {
        mysqli_rollback($conn);
        respond(400, [
            'success' => false,
            'message' => 'Keputusan surat ini telah muktamad dan tidak boleh diubah lagi.',
        ]);
    }
}

$user_fullname = (string) ($current_user['fullname'] ?? '');
$user_position = (string) ($current_user['position'] ?? '');
$user_department = (string) ($current_user['department'] ?? '');
$creator_id = (int) ($draft['created_by'] ?? 0);
$subject_title = (string) ($draft['subject'] ?? 'Draf Surat');
$ref_no = (string) ($draft['ref_no'] ?? '');

$is_revision_action = in_array($action, ['request_revision', 'pindaan', 'revision'], true);
$is_approve_action = in_array($action, ['approve', 'lulus', 'sahkan', 'sign'], true);

if ($is_revision_action) {
    if (trim($note) === '') {
        mysqli_rollback($conn);
        respond(422, [
            'success' => false,
            'message' => 'Sila masukkan catatan pindaan untuk penyedia surat.',
        ]);
    }

    $preparer_user_id = (int) ($draft['created_by'] ?? 0);
    $preparer_name = null;
    $preparer_email = null;
    if ($preparer_user_id > 0) {
        $p_stmt = mysqli_prepare($conn, "SELECT fullname, email FROM users WHERE id = ? LIMIT 1");
        if ($p_stmt) {
            mysqli_stmt_bind_param($p_stmt, "i", $preparer_user_id);
            mysqli_stmt_execute($p_stmt);
            $p_res = mysqli_stmt_get_result($p_stmt);
            $p_row = $p_res ? mysqli_fetch_assoc($p_res) : null;
            if ($p_row) {
                $preparer_name = $p_row['fullname'];
                $preparer_email = $p_row['email'];
            }
        }
    }

    $next_status = 'perlu_pindaan_penyedia';
    $update_stmt = mysqli_prepare($conn, "UPDATE letter_drafts
        SET approval_status = ?,
            approval_stage = 1,
            department_officer_status = 'menunggu',
            department_officer_decision = 'belum_diputuskan',
            department_officer_note = ?,
            department_officer_approved_at = NULL,
            department_officer_signature_path = NULL,
            department_officer_responded_at = NOW(),
            support_status = 'perlu_pindaan_penyedia',
            support_note = ?,
            support_responded_at = NOW(),
            support_user_id = ?,
            support_name = ?,
            support_email = ?,
            updated_by = ?,
            updated_at = CURRENT_TIMESTAMP
        WHERE id = ? AND deleted_at IS NULL");

    if ($update_stmt) {
        mysqli_stmt_bind_param($update_stmt, "sssissii", $next_status, $note, $note, $preparer_user_id, $preparer_name, $preparer_email, $user_id, $draft_id);
        mysqli_stmt_execute($update_stmt);
    }

    mysqli_commit($conn);

    if ($preparer_user_id > 0) {
        $push_title = '📝 Pindaan Surat Diperlukan';
        $push_body = "Surat/Memo \"{$subject_title}\" memerlukan pindaan oleh anda. Catatan: {$note}";

        $notif_stmt = mysqli_prepare($conn, "
            INSERT INTO push_notifications
            (user_id, title, body, payload_json, notification_type, is_read, created_at)
            VALUES (?, ?, ?, ?, 'letter_revision_requested', 0, NOW())
        ");
        if ($notif_stmt) {
            $payload_json = json_encode([
                'draft_id' => $draft_id,
                'type' => 'letter_revision_requested',
                'status' => 'perlu_pindaan_penyedia',
                'actor_name' => $user_fullname,
                'note' => $note,
            ], JSON_UNESCAPED_UNICODE);
            mysqli_stmt_bind_param($notif_stmt, 'isss', $preparer_user_id, $push_title, $push_body, $payload_json);
            mysqli_stmt_execute($notif_stmt);
        }

        if (function_exists('sendMainppPush')) {
            @sendMainppPush($conn, $preparer_user_id, $push_title, $push_body, [
                'draft_id' => (string) $draft_id,
                'type' => 'letter_revision_requested',
                'status' => 'perlu_pindaan_penyedia',
            ]);
        }
    }

    respond(200, [
        'success' => true,
        'message' => 'Permohonan pindaan telah dihantar kepada penyedia surat.',
        'status' => 'Perlu Pindaan',
    ]);
} else if ($is_approve_action) {
    $raw_doc_type = strtolower(trim((string) ($draft['doc_type'] ?? '')));
    $is_memo = ($raw_doc_type === 'memo' || strpos($raw_doc_type, 'memo') !== false);
    $is_surat_rasmi = ($raw_doc_type === 'surat rasmi' || strpos($raw_doc_type, 'surat') !== false);

    if ($is_memo || $is_surat_rasmi) {
        // Mark all delivery recipients delivered
        $deliv_stmt = mysqli_prepare($conn, "
            UPDATE letter_approval_recipients
            SET status = 'lulus',
                decision = 'lulus',
                note = IF(note = '' OR note IS NULL, ?, note),
                signature_path = IF(signature_path = '' OR signature_path IS NULL, ?, signature_path),
                requested_at = IF(requested_at IS NULL, NOW(), requested_at),
                approved_at = IF(approved_at IS NULL, NOW(), approved_at),
                responded_at = IF(responded_at IS NULL, NOW(), responded_at)
            WHERE draft_id = ?
        ");
        if ($deliv_stmt) {
            mysqli_stmt_bind_param($deliv_stmt, 'ssi', $note, $signature_path, $draft_id);
            mysqli_stmt_execute($deliv_stmt);
        }

        $is_fully_approved = true;
    } else {
        // 1. Update recipient row for this user
        $update_recipients = mysqli_prepare($conn, "
            UPDATE letter_approval_recipients
            SET status = 'lulus',
                decision = 'lulus',
                note = ?,
                approved_at = NOW(),
                signature_path = ?,
                responded_at = NOW()
            WHERE draft_id = ? AND (user_id = ? OR user_id IS NULL OR user_id = 0)
        ");

        if ($update_recipients) {
            mysqli_stmt_bind_param($update_recipients, 'ssii', $note, $signature_path, $draft_id, $user_id);
            mysqli_stmt_execute($update_recipients);
            if (mysqli_stmt_affected_rows($update_recipients) === 0) {
                $insert_rec = mysqli_prepare($conn, "
                    INSERT INTO letter_approval_recipients
                    (draft_id, user_id, position_label, source_type, status, decision, note, signature_path, approved_at, responded_at)
                    VALUES (?, ?, ?, 'tambahan', 'lulus', 'lulus', ?, ?, NOW(), NOW())
                ");
                if ($insert_rec) {
                    mysqli_stmt_bind_param($insert_rec, 'iisss', $draft_id, $user_id, $user_position, $note, $signature_path);
                    mysqli_stmt_execute($insert_rec);
                }
            }
        }

        // 2. Check remaining recipients status for this draft
        $rec_summary_stmt = mysqli_prepare($conn, "
            SELECT 
                COUNT(*) AS total_count,
                SUM(IF(status = 'lulus', 1, 0)) AS approved_count,
                SUM(IF(status = 'ditolak', 1, 0)) AS rejected_count,
                SUM(IF(status IN ('belum_mula', 'menunggu', 'menunggu_tandatangan'), 1, 0)) AS pending_count
            FROM letter_approval_recipients
            WHERE draft_id = ?
        ");

        $total_recipients = 0;
        $approved_recipients = 0;
        $rejected_recipients = 0;
        $pending_recipients = 0;

        if ($rec_summary_stmt) {
            mysqli_stmt_bind_param($rec_summary_stmt, 'i', $draft_id);
            mysqli_stmt_execute($rec_summary_stmt);
            $summary_res = mysqli_stmt_get_result($rec_summary_stmt);
            $summary = $summary_res ? mysqli_fetch_assoc($summary_res) : null;
            if ($summary) {
                $total_recipients = (int) ($summary['total_count'] ?? 0);
                $approved_recipients = (int) ($summary['approved_count'] ?? 0);
                $rejected_recipients = (int) ($summary['rejected_count'] ?? 0);
                $pending_recipients = (int) ($summary['pending_count'] ?? 0);
            }
        }

        // Activate next recipient in queue if any pending 'belum_mula'
        if ($pending_recipients > 0 && $rejected_recipients === 0) {
            $order_stmt = mysqli_prepare($conn, "
                SELECT MIN(route_order) AS next_order
                FROM letter_approval_recipients
                WHERE draft_id = ? AND status = 'belum_mula'
            ");
            if ($order_stmt) {
                mysqli_stmt_bind_param($order_stmt, 'i', $draft_id);
                mysqli_stmt_execute($order_stmt);
                $order_res = mysqli_stmt_get_result($order_stmt);
                $next_order = (int) (mysqli_fetch_assoc($order_res)['next_order'] ?? 0);
                if ($next_order > 0) {
                    $act_stmt = mysqli_prepare($conn, "
                        UPDATE letter_approval_recipients
                        SET status = 'menunggu', requested_at = NOW(), responded_at = NULL
                        WHERE draft_id = ? AND route_order = ? AND status = 'belum_mula'
                    ");
                    if ($act_stmt) {
                        mysqli_stmt_bind_param($act_stmt, 'ii', $draft_id, $next_order);
                        mysqli_stmt_execute($act_stmt);
                    }
                }
            }
        }

        $is_fully_approved = ($pending_recipients === 0 && $rejected_recipients === 0);
    }

    if ($is_fully_approved) {
        // ALL signers / Memo approved -> update draft status to 'lulus' & 'siap'
        $update_draft = mysqli_prepare($conn, "
            UPDATE letter_drafts
            SET approval_status = 'lulus',
                status = 'siap',
                approval_stage = 0,
                support_status = 'disokong',
                support_user_id = 0,
                support_name = NULL,
                support_email = NULL,
                support_note = ?,
                support_responded_at = NOW(),
                signatory_signature_path = ?,
                signatory_name = ?,
                signatory_position = ?,
                signatory_department = ?,
                preparer_signed_at = IF(preparer_signed_at IS NULL, NOW(), preparer_signed_at),
                department_officer_user_id = ?,
                department_officer_name = ?,
                department_officer_status = 'lulus',
                department_officer_decision = 'lulus',
                department_officer_signature_path = ?,
                department_officer_note = ?,
                department_officer_approved_at = NOW(),
                department_officer_responded_at = NOW(),
                updated_by = ?,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = ? AND deleted_at IS NULL
        ");

        if ($update_draft) {
            mysqli_stmt_bind_param(
                $update_draft,
                'sssssisssii',
                $note,
                $signature_path,
                $user_fullname,
                $user_position,
                $user_department,
                $user_id,
                $user_fullname,
                $signature_path,
                $note,
                $user_id,
                $draft_id
            );
            mysqli_stmt_execute($update_draft);
        }

        mysqli_commit($conn);

        // Notify Creator (Penyedia) that ALL signers have approved
        if ($creator_id > 0) {
            $push_title = '✅ Surat / Memo Diluluskan';
            $push_body = "Surat/Memo \"{$subject_title}\" (" . ($ref_no !== '' ? "No. Ruj: {$ref_no}" : "ID: {$draft_id}") . ") telah diluluskan dan ditandatangani sepenuhnya.";

            $notif_stmt = mysqli_prepare($conn, "
                INSERT INTO push_notifications
                (user_id, title, body, payload_json, notification_type, is_read, created_at)
                VALUES (?, ?, ?, ?, 'letter_approved', 0, NOW())
            ");
            if ($notif_stmt) {
                $payload_json = json_encode([
                    'draft_id' => $draft_id,
                    'type' => 'letter_approved',
                    'status' => 'lulus',
                    'actor_name' => $user_fullname,
                ], JSON_UNESCAPED_UNICODE);
                mysqli_stmt_bind_param($notif_stmt, 'isss', $creator_id, $push_title, $push_body, $payload_json);
                mysqli_stmt_execute($notif_stmt);
            }

            if (function_exists('sendMainppPush')) {
                @sendMainppPush($conn, $creator_id, $push_title, $push_body, [
                    'draft_id' => (string) $draft_id,
                    'type' => 'letter_approved',
                    'status' => 'lulus',
                ]);
            }
        }

        // Notify distribution staff (Senarai Edaran)
        $dist_staff_json = trim((string) ($draft['distribution_staff_list'] ?? ''));
        $dist_staff_ids = [];
        if ($dist_staff_json !== '' && $dist_staff_json !== '[]') {
            $decoded = json_decode($dist_staff_json, true);
            if (is_array($decoded)) {
                foreach ($decoded as $s_id) {
                    $s_int = (int) (is_array($s_id) ? ($s_id['id'] ?? 0) : $s_id);
                    if ($s_int > 0 && $s_int !== $user_id && $s_int !== $creator_id) {
                        $dist_staff_ids[] = $s_int;
                    }
                }
            }
        }

        if (!empty($dist_staff_ids)) {
            $dist_title = '📬 Salinan Surat / Memo Untuk Edaran Anda';
            $dist_body = "Surat/Memo \"{$subject_title}\" (" . ($ref_no !== '' ? "No. Ruj: {$ref_no}" : "ID: {$draft_id}") . ") telah diluluskan dan diedarkan kepada anda.";
            $dist_stmt = mysqli_prepare($conn, "
                INSERT INTO push_notifications
                (user_id, title, body, payload_json, notification_type, is_read, created_at)
                VALUES (?, ?, ?, ?, 'letter_distributed', 0, NOW())
            ");
            foreach ($dist_staff_ids as $target_staff_id) {
                if ($dist_stmt) {
                    $p_json = json_encode([
                        'draft_id' => $draft_id,
                        'type' => 'letter_distributed',
                        'status' => 'lulus',
                        'actor_name' => $user_fullname,
                    ], JSON_UNESCAPED_UNICODE);
                    mysqli_stmt_bind_param($dist_stmt, 'isss', $target_staff_id, $dist_title, $dist_body, $p_json);
                    mysqli_stmt_execute($dist_stmt);
                }
                if (function_exists('sendMainppPush')) {
                    @sendMainppPush($conn, $target_staff_id, $dist_title, $dist_body, [
                        'draft_id' => (string) $draft_id,
                        'type' => 'letter_distributed',
                        'status' => 'lulus',
                    ]);
                }
            }
        }

        if (function_exists('logActivity')) {
            logActivity($conn, $user_id, 'approve_draft_letter', "Meluluskan dan menurunkan tandatangan akhir draf surat ID: {$draft_id}");
        }

        respond(200, [
            'success' => true,
            'message' => 'Surat/Memo telah diluluskan dan ditandatangani secara lengkap oleh semua penandatangan!',
            'status' => 'Diluluskan',
            'isFullyApproved' => true,
            'signatoryName' => $user_fullname,
            'signaturePath' => $signature_path,
        ]);
    } else {
        // Still pending next signers in sequence
        $update_draft = mysqli_prepare($conn, "
            UPDATE letter_drafts
            SET approval_status = 'menunggu_pelulus',
                support_status = 'menunggu',
                updated_by = ?,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = ? AND deleted_at IS NULL
        ");
        if ($update_draft) {
            mysqli_stmt_bind_param($update_draft, 'ii', $user_id, $draft_id);
            mysqli_stmt_execute($update_draft);
        }

        mysqli_commit($conn);

        // Send push notification to the NEXT active signer (status = 'menunggu')
        $next_signer_stmt = mysqli_prepare($conn, "
            SELECT lar.user_id, u.fullname
            FROM letter_approval_recipients lar
            LEFT JOIN users u ON u.id = lar.user_id
            WHERE lar.draft_id = ? AND lar.status = 'menunggu' AND lar.user_id != ?
            LIMIT 1
        ");
        if ($next_signer_stmt) {
            mysqli_stmt_bind_param($next_signer_stmt, 'ii', $draft_id, $user_id);
            mysqli_stmt_execute($next_signer_stmt);
            $next_res = mysqli_stmt_get_result($next_signer_stmt);
            $next_signer = $next_res ? mysqli_fetch_assoc($next_res) : null;
            if ($next_signer && (int) ($next_signer['user_id'] ?? 0) > 0) {
                $next_user_id = (int) $next_signer['user_id'];
                $next_title = '📝 Menunggu Tandatangan Anda';
                $next_body = "Surat/Memo \"{$subject_title}\" (" . ($ref_no !== '' ? "No. Ruj: {$ref_no}" : "ID: {$draft_id}") . ") memerlukan semakan dan tandatangan anda.";

                $notif_stmt = mysqli_prepare($conn, "
                    INSERT INTO push_notifications
                    (user_id, title, body, payload_json, notification_type, is_read, created_at)
                    VALUES (?, ?, ?, ?, 'letter_pending_signature', 0, NOW())
                ");
                if ($notif_stmt) {
                    $payload_json = json_encode([
                        'draft_id' => $draft_id,
                        'type' => 'letter_pending_signature',
                        'status' => 'menunggu',
                    ], JSON_UNESCAPED_UNICODE);
                    mysqli_stmt_bind_param($notif_stmt, 'isss', $next_user_id, $next_title, $next_body, $payload_json);
                    mysqli_stmt_execute($notif_stmt);
                }

                if (is_file(__DIR__ . '/../includes/push_service.php')) {
                    require_once __DIR__ . '/../includes/push_service.php';
                    if (function_exists('sendMainppPush')) {
                        @sendMainppPush($conn, $next_user_id, $next_title, $next_body, [
                            'draft_id' => (string) $draft_id,
                            'type' => 'letter_pending_signature',
                        ]);
                    }
                }
            }
        }

        if (function_exists('logActivity')) {
            logActivity($conn, $user_id, 'approve_draft_letter', "Menandatangani draf surat ID: {$draft_id} (Dihantar ke penandatangan seterusnya)");
        }

        respond(200, [
            'success' => true,
            'message' => 'Tandatangan anda telah disimpan. Surat/Memo dihantar kepada penandatangan seterusnya.',
            'status' => 'Dalam Proses',
            'isFullyApproved' => false,
            'signatoryName' => $user_fullname,
            'signaturePath' => $signature_path,
        ]);
    }
} else {
    // REJECTION (Tolak) Action
    $update_draft = mysqli_prepare($conn, "
        UPDATE letter_drafts
        SET approval_status = 'ditolak',
            support_status = 'ditolak',
            department_officer_user_id = IF(department_officer_user_id IS NULL OR department_officer_user_id = 0, ?, department_officer_user_id),
            department_officer_name = IF(department_officer_name = '' OR department_officer_name IS NULL, ?, department_officer_name),
            department_officer_status = 'ditolak',
            department_officer_decision = 'ditolak',
            department_officer_signature_path = ?,
            department_officer_note = ?,
            department_officer_responded_at = NOW(),
            signatory_signature_path = IF(signatory_signature_path = '' OR signatory_signature_path IS NULL, ?, signatory_signature_path),
            updated_by = ?,
            updated_at = CURRENT_TIMESTAMP
        WHERE id = ? AND deleted_at IS NULL
    ");

    if ($update_draft) {
        mysqli_stmt_bind_param($update_draft, 'issssii', $user_id, $user_fullname, $signature_path, $note, $signature_path, $user_id, $draft_id);
        mysqli_stmt_execute($update_draft);
    }

    $update_recipients = mysqli_prepare($conn, "
        UPDATE letter_approval_recipients
        SET status = 'ditolak',
            decision = 'ditolak',
            note = ?,
            signature_path = ?,
            responded_at = NOW()
        WHERE draft_id = ? AND (user_id = ? OR user_id IS NULL OR user_id = 0)
    ");

    if ($update_recipients) {
        mysqli_stmt_bind_param($update_recipients, 'ssii', $note, $signature_path, $draft_id, $user_id);
        mysqli_stmt_execute($update_recipients);
        if (mysqli_stmt_affected_rows($update_recipients) === 0) {
            $insert_rec = mysqli_prepare($conn, "
                INSERT INTO letter_approval_recipients
                (draft_id, user_id, position_label, source_type, status, decision, note, signature_path, responded_at)
                VALUES (?, ?, ?, 'tambahan', 'ditolak', 'ditolak', ?, ?, NOW())
            ");
            if ($insert_rec) {
                mysqli_stmt_bind_param($insert_rec, 'iisss', $draft_id, $user_id, $user_position, $note, $signature_path);
                mysqli_stmt_execute($insert_rec);
            }
        }
    }

    mysqli_commit($conn);

    // Notify Creator (Penyedia) that the letter was REJECTED
    if ($creator_id > 0) {
        $push_title = '❌ Surat / Memo Ditolak';
        $push_body = "Surat/Memo \"{$subject_title}\" (" . ($ref_no !== '' ? "No. Ruj: {$ref_no}" : "ID: {$draft_id}") . ") telah ditolak oleh {$user_fullname}.";
        if ($note !== '') {
            $push_body .= " Catatan: {$note}";
        }

        $notif_stmt = mysqli_prepare($conn, "
            INSERT INTO push_notifications
            (user_id, title, body, payload_json, notification_type, is_read, created_at)
            VALUES (?, ?, ?, ?, 'letter_rejected', 0, NOW())
        ");
        if ($notif_stmt) {
            $payload_json = json_encode([
                'draft_id' => $draft_id,
                'type' => 'letter_rejected',
                'status' => 'ditolak',
                'actor_name' => $user_fullname,
                'note' => $note,
            ], JSON_UNESCAPED_UNICODE);
            mysqli_stmt_bind_param($notif_stmt, 'isss', $creator_id, $push_title, $push_body, $payload_json);
            mysqli_stmt_execute($notif_stmt);
        }

        if (is_file(__DIR__ . '/../includes/push_service.php')) {
            require_once __DIR__ . '/../includes/push_service.php';
            if (function_exists('sendMainppPush')) {
                @sendMainppPush($conn, $creator_id, $push_title, $push_body, [
                    'draft_id' => (string) $draft_id,
                    'type' => 'letter_rejected',
                    'status' => 'ditolak',
                ]);
            }
        }
    }

    if (function_exists('logActivity')) {
        logActivity($conn, $user_id, 'reject_draft_letter', "Menolak draf surat ID: {$draft_id}");
    }

    respond(200, [
        'success' => true,
        'message' => 'Surat/Memo telah ditolak. Notifikasi penolakan telah dihantar kepada penyedia.',
        'status' => 'Ditolak',
        'isFullyApproved' => false,
    ]);
}
