<?php
declare(strict_types=1);

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

require_login($conn);
require_permission($conn, 'queue');

ensure_order_split_deposit_columns($conn);
ensure_payment_slip_columns($conn);

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

$paymentId = (int) (filter_input(INPUT_POST, 'payment_id', FILTER_VALIDATE_INT) ?: 0);
$orderId = (int) (filter_input(INPUT_POST, 'order_id', FILTER_VALIDATE_INT) ?: 0);
$scopeRaw = trim((string) ($_POST['deposit_scope'] ?? ''));
$fallbackReturn = 'job_details.php?id=' . $orderId . '#deposit-management';
$returnPath = process_safe_return_path((string) ($_POST['return_to'] ?? ''), '../pages/' . $fallbackReturn);
$preferredLandingPath = '../pages/' . auth_preferred_landing_page($conn);

ensure_post_csrf_or_redirect('booking_deposit_manage', $returnPath);

if ($orderId <= 0) {
    redirect_with_flash('../pages/queue.php', 'error', localized_flash_message('ไม่พบบิลจอง', 'Booking was not found.'));
}

$orderStmt = db_prepare($conn, "
    SELECT
        order_id,
        bill_number,
        branch_name,
        customer_id,
        car_id,
        status,
        total_price,
        payment_status,
        deposit_amount,
        deposit_method,
        admin_deposit_amount,
        admin_deposit_method,
        branch_deposit_amount,
        branch_deposit_method
    FROM orders
    WHERE order_id = ?
    LIMIT 1
");
$orderStmt->bind_param('i', $orderId);
$orderStmt->execute();
$orderRow = $orderStmt->get_result()->fetch_assoc();
$orderStmt->close();

if (!$orderRow) {
    redirect_with_flash('../pages/queue.php', 'error', localized_flash_message('ไม่พบบิลจอง', 'Booking was not found.'));
}

if (!auth_can_access_branch($conn, (string) ($orderRow['branch_name'] ?? ''))) {
    redirect_with_flash($preferredLandingPath, 'error', localized_flash_message('คุณไม่มีสิทธิ์เข้าถึงสาขานี้', 'You do not have access to that branch.'));
}

if ((string) ($orderRow['status'] ?? '') === 'cancelled') {
    redirect_with_flash($returnPath, 'error', localized_flash_message('บิลที่ยกเลิกแล้วไม่สามารถแก้ไขมัดจำการจองได้', 'Cancelled bill cannot update booking deposits.'));
}

$paymentRow = null;
$depositScope = '';
$paymentNote = '';

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

    if (!$paymentRow) {
        redirect_with_flash($returnPath, 'error', localized_flash_message('ไม่พบรายการชำระมัดจำ', 'Deposit payment was not found.'));
    }

    $paymentNote = trim((string) ($paymentRow['note'] ?? ''));
    if ($paymentNote === 'Admin deposit at booking') {
        $depositScope = 'admin';
    } elseif ($paymentNote === 'Branch deposit at booking') {
        $depositScope = 'branch';
    }

    if ($depositScope === '') {
        redirect_with_flash($returnPath, 'error', localized_flash_message('หน้านี้ลบได้เฉพาะรายการมัดจำจากการจอง', 'Only booking deposit payments can be deleted here.'));
    }
} else {
    if (!in_array($scopeRaw, array('admin', 'branch'), true)) {
        redirect_with_flash($returnPath, 'error', localized_flash_message('ยังไม่ได้เลือกประเภทมัดจำ', 'Deposit type was not selected.'));
    }

    $depositScope = $scopeRaw;
    $paymentNote = $depositScope === 'admin' ? 'Admin deposit at booking' : 'Branch deposit at booking';

    $paymentStmt = db_prepare($conn, "
        SELECT
            payment_id,
            order_id,
            payment_method,
            amount,
            received_amount,
            change_amount,
            note,
            slip_file_path,
            slip_file_name,
            slip_mime_type,
            slip_uploaded_at
        FROM payments
        WHERE order_id = ?
            AND note = ?
        ORDER BY payment_date DESC, payment_id DESC
        LIMIT 1
    ");
    $paymentStmt->bind_param('is', $orderId, $paymentNote);
    $paymentStmt->execute();
    $paymentRow = $paymentStmt->get_result()->fetch_assoc();
    $paymentStmt->close();

    if ($paymentRow) {
        $paymentId = (int) ($paymentRow['payment_id'] ?? 0);
    }
}

$requiredPermission = $depositScope === 'admin' ? 'booking_deposit_admin_edit' : 'booking_deposit_branch_edit';
process_ensure_permission_or_redirect(
    $conn,
    $requiredPermission,
    $returnPath,
    localized_flash_message('คุณไม่มีสิทธิ์ลบรายการมัดจำนี้', 'You do not have permission to delete that deposit.')
);

$currentAdminDepositAmount = round((float) ($orderRow['admin_deposit_amount'] ?? 0), 2);
$currentBranchDepositAmount = round((float) ($orderRow['branch_deposit_amount'] ?? 0), 2);
$currentAdminDepositMethod = trim((string) ($orderRow['admin_deposit_method'] ?? ''));
$currentBranchDepositMethod = trim((string) ($orderRow['branch_deposit_method'] ?? ''));
$currentScopeAmount = $depositScope === 'admin' ? $currentAdminDepositAmount : $currentBranchDepositAmount;
$currentScopeMethod = $depositScope === 'admin' ? $currentAdminDepositMethod : $currentBranchDepositMethod;

if ($currentScopeAmount <= 0.0 && !$paymentRow) {
    redirect_with_flash($returnPath, 'error', localized_flash_message('ไม่พบรายการมัดจำ', 'Deposit record was not found.'));
}

$otherPaidStmt = db_prepare($conn, "
    SELECT COALESCE(SUM(amount), 0) AS other_paid_amount
    FROM payments
    WHERE order_id = ?
        AND payment_id <> ?
");
$otherPaidStmt->bind_param('ii', $orderId, $paymentId);
$otherPaidStmt->execute();
$otherPaidAmount = (float) ($otherPaidStmt->get_result()->fetch_assoc()['other_paid_amount'] ?? 0);
$otherPaidStmt->close();

$updatedAdminDepositAmount = $depositScope === 'admin' ? 0.0 : $currentAdminDepositAmount;
$updatedBranchDepositAmount = $depositScope === 'branch' ? 0.0 : $currentBranchDepositAmount;
$updatedAdminDepositMethod = $depositScope === 'admin' ? '' : $currentAdminDepositMethod;
$updatedBranchDepositMethod = $depositScope === 'branch' ? '' : $currentBranchDepositMethod;
$updatedDepositAmount = round($updatedAdminDepositAmount + $updatedBranchDepositAmount, 2);
$updatedPaidAmount = round($otherPaidAmount, 2);
$totalPrice = round((float) ($orderRow['total_price'] ?? 0), 2);

$updatedDepositMethod = '';
if ($updatedAdminDepositAmount > 0.0 && $updatedBranchDepositAmount > 0.0) {
    if ($updatedAdminDepositMethod !== '' && $updatedBranchDepositMethod !== '' && $updatedAdminDepositMethod !== $updatedBranchDepositMethod) {
        $updatedDepositMethod = 'mixed';
    } else {
        $updatedDepositMethod = $updatedAdminDepositMethod !== '' ? $updatedAdminDepositMethod : $updatedBranchDepositMethod;
    }
} elseif ($updatedAdminDepositAmount > 0.0) {
    $updatedDepositMethod = $updatedAdminDepositMethod;
} elseif ($updatedBranchDepositAmount > 0.0) {
    $updatedDepositMethod = $updatedBranchDepositMethod;
}

$updatedPaymentStatus = order_payment_status_from_amounts($totalPrice, $updatedPaidAmount);

$currentPaymentAmount = round((float) ($paymentRow['amount'] ?? $currentScopeAmount), 2);
$currentPaymentMethod = trim((string) ($paymentRow['payment_method'] ?? $currentScopeMethod));
$currentReceivedAmount = round((float) ($paymentRow['received_amount'] ?? $currentPaymentAmount), 2);
$currentChangeAmount = round((float) ($paymentRow['change_amount'] ?? 0), 2);
$currentSlipPath = trim((string) ($paymentRow['slip_file_path'] ?? ''));
$currentSlipName = trim((string) ($paymentRow['slip_file_name'] ?? ''));
$paidAmountBefore = round($otherPaidAmount + ($paymentRow ? $currentPaymentAmount : 0.0), 2);

$beforeSnapshot = array(
    'deposit_type' => $depositScope,
    'payment_amount' => $currentPaymentAmount,
    'payment_method' => $currentPaymentMethod,
    'received_amount' => $currentReceivedAmount,
    'change_amount' => $currentChangeAmount,
    'deposit_amount' => round((float) ($orderRow['deposit_amount'] ?? 0), 2),
    'admin_deposit_amount' => $currentAdminDepositAmount,
    'admin_deposit_method' => $currentAdminDepositMethod,
    'branch_deposit_amount' => $currentBranchDepositAmount,
    'branch_deposit_method' => $currentBranchDepositMethod,
    'deposit_method' => trim((string) ($orderRow['deposit_method'] ?? '')),
    'payment_status' => (string) ($orderRow['payment_status'] ?? ''),
    'paid_amount' => $paidAmountBefore,
    'slip_file_name' => $currentSlipName,
    'has_slip' => $currentSlipPath !== '',
);
$afterSnapshot = array(
    'deposit_type' => $depositScope,
    'payment_deleted' => true,
    'deposit_amount' => $updatedDepositAmount,
    'admin_deposit_amount' => $updatedAdminDepositAmount,
    'admin_deposit_method' => $updatedAdminDepositMethod,
    'branch_deposit_amount' => $updatedBranchDepositAmount,
    'branch_deposit_method' => $updatedBranchDepositMethod,
    'deposit_method' => $updatedDepositMethod,
    'payment_status' => $updatedPaymentStatus,
    'paid_amount' => $updatedPaidAmount,
    'has_slip' => false,
);

$conn->begin_transaction();

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

    $updateOrderStmt = db_prepare($conn, "
        UPDATE orders
        SET
            admin_deposit_amount = ?,
            admin_deposit_method = NULLIF(?, ''),
            branch_deposit_amount = ?,
            branch_deposit_method = NULLIF(?, ''),
            deposit_amount = ?,
            deposit_method = NULLIF(?, ''),
            payment_status = ?
        WHERE order_id = ?
        LIMIT 1
    ");
    $updateOrderStmt->bind_param(
        'dsdsdssi',
        $updatedAdminDepositAmount,
        $updatedAdminDepositMethod,
        $updatedBranchDepositAmount,
        $updatedBranchDepositMethod,
        $updatedDepositAmount,
        $updatedDepositMethod,
        $updatedPaymentStatus,
        $orderId
    );
    $updateOrderStmt->execute();
    $updateOrderStmt->close();

    audit_log($conn, array(
        'module_key' => 'payment',
        'action_key' => 'delete',
        'entity_type' => $paymentId > 0 ? 'payment' : 'order',
        'entity_id' => $paymentId > 0 ? $paymentId : $orderId,
        'order_id' => $orderId,
        'payment_id' => $paymentId > 0 ? $paymentId : null,
        'customer_id' => (int) ($orderRow['customer_id'] ?? 0),
        'car_id' => (int) ($orderRow['car_id'] ?? 0),
        'branch_name' => (string) ($orderRow['branch_name'] ?? ''),
        'bill_number' => (string) ($orderRow['bill_number'] ?? ''),
        'amount' => $currentPaymentAmount,
        'message' => ($depositScope === 'admin' ? 'Deposit @Admin' : 'Deposit @Branch') . ' deleted.',
        'before' => $beforeSnapshot,
        'after' => $afterSnapshot,
        'meta' => array(
            'payment_note' => $paymentNote,
            'legacy_order_only' => $paymentId <= 0,
        ),
    ));

    $conn->commit();
} catch (Throwable $exception) {
    process_handle_exception_and_redirect(
        $conn,
        $exception,
        'delete_booking_deposit',
        $returnPath,
        localized_flash_message('ลบมัดจำไม่สำเร็จ', 'Deposit was not deleted.'),
        array(
            'order_id' => $orderId,
            'payment_id' => $paymentId,
            'deposit_scope' => $depositScope,
            'payment_note' => $paymentNote,
        ),
        array(),
        true
    );
}

if ($currentSlipPath !== '') {
    delete_payment_slip_file($currentSlipPath);
}

$depositScopeLabelTh = $depositScope === 'admin' ? 'มัดจำ @Admin' : 'มัดจำ @Branch';
$depositScopeLabelEn = $depositScope === 'admin' ? 'Deposit @Admin' : 'Deposit @Branch';
redirect_with_flash(
    $returnPath,
    'success',
    localized_flash_message(
        $depositScopeLabelTh . ' ลบเรียบร้อยแล้ว',
        $depositScopeLabelEn . ' deleted successfully.'
    )
);
