<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/bootstrap.php';

require_permission($conn, 'quick_service');

process_post_only_or_redirect('../pages/quick_service.php');

ensure_order_source_column($conn);
ensure_payment_tender_columns($conn);
ensure_payment_slip_columns($conn);

$orderId = (int) (filter_input(INPUT_POST, 'order_id', FILTER_VALIDATE_INT) ?: 0);
$paymentId = (int) (filter_input(INPUT_POST, 'payment_id', FILTER_VALIDATE_INT) ?: 0);
$returnPath = process_safe_return_path((string) ($_POST['return_to'] ?? ''), '../pages/quick_service.php');

ensure_post_csrf_or_redirect('quick_service_payment_delete', $returnPath);

if ($orderId <= 0 || $paymentId <= 0) {
    redirect_with_flash($returnPath, 'error', localized_flash_message('ไม่พบรายการชำระเงิน', 'Payment record was not found.'));
}

process_ensure_permission_or_redirect(
    $conn,
    'quick_service_payment',
    $returnPath,
    localized_flash_message('คุณไม่มีสิทธิ์จัดการการชำระเงิน Quick Service', 'You do not have permission to manage Quick Service payment.')
);

$order = process_load_order_context_or_redirect(
    $conn,
    $orderId,
    $returnPath,
    localized_flash_message('ไม่พบบิลที่พักไว้', 'Held bill was not found.'),
    array(
        'extra_columns' => array('o.order_source'),
        'check_branch_access' => false,
    )
);

process_ensure_branch_access_or_redirect(
    $conn,
    (string) ($order['branch_name'] ?? ''),
    $returnPath,
    localized_flash_message('คุณไม่มีสิทธิ์เข้าถึงสาขานี้', 'You do not have access to that branch.')
);

if ((string) ($order['order_source'] ?? 'booking') !== 'quick_service') {
    redirect_with_flash(
        $returnPath,
        'error',
        localized_flash_message('ลบรายการชำระเงินได้เฉพาะบิล Quick Service เท่านั้น', 'Payment can only be deleted from Quick Service bills.')
    );
}

if ((string) ($order['status'] ?? '') === 'cancelled') {
    redirect_with_flash($returnPath, 'error', localized_flash_message('บิลที่ยกเลิกแล้วไม่สามารถแก้ไขได้', 'Cancelled bill cannot be updated.'));
}

if ((string) ($order['payment_status'] ?? '') === 'paid' || (string) ($order['status'] ?? '') === 'done') {
    redirect_with_flash(
        $returnPath,
        'error',
        localized_flash_message('บิลที่ชำระครบแล้วไม่สามารถลบรายการชำระเงินจากหน้านี้ได้', 'Paid bills cannot remove recorded payments from this screen.')
    );
}

$conn->begin_transaction();

try {
    $paymentStmt = db_prepare($conn, "
        SELECT payment_id, payment_method, amount, received_amount, change_amount, note, slip_file_path, slip_file_name
        FROM payments
        WHERE payment_id = ?
            AND order_id = ?
        LIMIT 1
    ");
    $paymentStmt->bind_param('ii', $paymentId, $orderId);
    $paymentStmt->execute();
    $payment = $paymentStmt->get_result()->fetch_assoc();
    $paymentStmt->close();

    if (!$payment) {
        throw new RuntimeException(localized_flash_message_string('ไม่พบรายการชำระเงินในบิลนี้', 'Payment record was not found on this bill.'));
    }

    $deleteStmt = db_prepare($conn, "
        DELETE FROM payments
        WHERE payment_id = ?
            AND order_id = ?
        LIMIT 1
    ");
    $deleteStmt->bind_param('ii', $paymentId, $orderId);
    $deleteStmt->execute();
    $deleteStmt->close();

    $paidAmount = order_paid_amount($conn, $orderId);
    $totalPrice = (float) ($order['total_price'] ?? 0);
    $quickServiceState = quick_service_order_state_from_amounts($totalPrice, $paidAmount);
    $paymentStatus = (string) ($quickServiceState['payment_status'] ?? 'unpaid');
    $status = (string) ($quickServiceState['status'] ?? 'waiting');
    $finishedAt = $quickServiceState['finished_at'] !== null ? (string) $quickServiceState['finished_at'] : null;
    $balanceAmount = (float) ($quickServiceState['balance_amount'] ?? order_balance_amount($totalPrice, $paidAmount));

    $updateOrderStmt = db_prepare($conn, "
        UPDATE orders
        SET payment_status = ?,
            status = ?,
            finished_at = ?
        WHERE order_id = ?
    ");
    $updateOrderStmt->bind_param('sssi', $paymentStatus, $status, $finishedAt, $orderId);
    $updateOrderStmt->execute();
    $updateOrderStmt->close();

    audit_log($conn, array(
        'module_key' => 'payment',
        'action_key' => 'delete',
        'entity_type' => 'payment',
        'entity_id' => $paymentId,
        'order_id' => $orderId,
        'payment_id' => $paymentId,
        'customer_id' => (int) ($order['customer_id'] ?? 0),
        'car_id' => (int) ($order['car_id'] ?? 0),
        'branch_name' => (string) ($order['branch_name'] ?? ''),
        'bill_number' => (string) ($order['bill_number'] ?? ''),
        'amount' => (float) ($payment['amount'] ?? 0),
        'message' => 'Quick Service payment record deleted.',
        'before' => array(
            'payment_method' => (string) ($payment['payment_method'] ?? ''),
            'recognized_amount' => (float) ($payment['amount'] ?? 0),
            'received_amount' => (float) ($payment['received_amount'] ?? 0),
            'change_amount' => (float) ($payment['change_amount'] ?? 0),
            'note' => (string) ($payment['note'] ?? ''),
            'slip_file_name' => (string) ($payment['slip_file_name'] ?? ''),
            'payment_status' => (string) ($order['payment_status'] ?? ''),
        ),
        'after' => array(
            'order_status' => $status,
            'payment_status' => $paymentStatus,
            'paid_amount' => $paidAmount,
            'balance_amount' => $balanceAmount,
        ),
        'meta' => array(
            'order_source' => 'quick_service',
        ),
    ));

    $conn->commit();
    delete_payment_slip_file((string) ($payment['slip_file_path'] ?? ''));

    redirect_with_flash(
        $returnPath,
        'success',
        localized_flash_message('ลบรายการชำระเงินออกจากบิลที่พักไว้เรียบร้อยแล้ว', 'Payment record deleted from the held bill.')
    );
} catch (Throwable $exception) {
    process_handle_exception_and_redirect(
        $conn,
        $exception,
        'delete_quick_service_payment',
        $returnPath,
        localized_flash_message('ลบรายการชำระเงินออกจากบิลไม่สำเร็จ', 'Payment record was not deleted.'),
        array(
            'order_id' => $orderId,
            'payment_id' => $paymentId,
            'order_status' => (string) ($order['status'] ?? ''),
            'payment_status' => (string) ($order['payment_status'] ?? ''),
        ),
        array(),
        true
    );
}
