<?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', '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'], 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.',
    ]);
}

$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.',
    ]);
}

if ((int) ($draft['department_officer_user_id'] ?? 0) === $user_id) {
    $dept_status = strtolower((string) ($draft['department_officer_status'] ?? ''));
    if (in_array($dept_status, ['lulus', 'ditolak'], true)) {
        mysqli_rollback($conn);
        respond(400, [
            'success' => false,
            'message' => 'Keputusan anda untuk surat ini telah muktamad dan tidak boleh diubah lagi.',
        ]);
    }
}

$check_rec_stmt = mysqli_prepare($conn, 'SELECT status FROM letter_approval_recipients WHERE draft_id = ? AND user_id = ? LIMIT 1');
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.',
            ]);
        }
    }
}

$user_fullname = (string) ($current_user['fullname'] ?? '');
$user_position = (string) ($current_user['position'] ?? '');
$user_department = (string) ($current_user['department'] ?? '');

$is_approve_action = in_array($action, ['approve', 'lulus'], true);

if ($is_approve_action) {
    $update_draft = mysqli_prepare($conn, "
        UPDATE letter_drafts
        SET approval_status = 'lulus',
            status = 'siap',
            support_status = 'disokong',
            signatory_signature_path = ?,
            signatory_name = IF(signatory_name = '' OR signatory_name IS NULL, ?, signatory_name),
            signatory_position = IF(signatory_position = '' OR signatory_position IS NULL, ?, signatory_position),
            signatory_department = IF(signatory_department = '' OR signatory_department IS NULL, ?, signatory_department),
            preparer_signed_at = IF(preparer_signed_at IS NULL, NOW(), preparer_signed_at),
            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 = '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,
            'ssssisssii',
            $signature_path,
            $user_fullname,
            $user_position,
            $user_department,
            $user_id,
            $user_fullname,
            $signature_path,
            $note,
            $user_id,
            $draft_id
        );
        mysqli_stmt_execute($update_draft);
    }

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

    mysqli_commit($conn);

    $creator_id = (int) ($draft['created_by'] ?? 0);
    if ($creator_id > 0 && $creator_id !== $user_id) {
        $subject_title = (string) ($draft['subject'] ?? 'Draf Surat');
        $ref_no = (string) ($draft['ref_no'] ?? '');
        $push_title = '✅ Surat Diluluskan';
        $push_body = "Surat \"{$subject_title}\" (" . ($ref_no !== '' ? "No. Ruj: {$ref_no}" : "ID: {$draft_id}") . ") telah diluluskan dan ditandatangani oleh {$user_fullname}.";

        $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 (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_approved',
                    'status' => 'lulus',
                ]);
            }
        }
    }

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

    respond(200, [
        'success' => true,
        'message' => 'Surat berjaya diluluskan dan ditandatangani!',
        'status' => 'Diluluskan',
        'signatoryName' => $user_fullname,
        'signaturePath' => $signature_path,
    ]);
} else {
    $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);

    $creator_id = (int) ($draft['created_by'] ?? 0);
    if ($creator_id > 0 && $creator_id !== $user_id) {
        $subject_title = (string) ($draft['subject'] ?? 'Draf Surat');
        $ref_no = (string) ($draft['ref_no'] ?? '');
        $push_title = '❌ Surat Ditolak';
        $push_body = "Surat \"{$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 telah ditolak.',
        'status' => 'Ditolak',
    ]);
}
