<?php
// /public_html/erp.jewellersbd.com/api/cash/delete_transaction.php

require_once __DIR__ . '/../../config/session.php';
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../../config/response.php';

if (!is_logged_in()) {
    send_response(401, false, 'লগইন প্রয়োজন', null);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    send_response(405, false, 'শুধু POST অনুরোধ গ্রহণযোগ্য', null);
}

$data = json_decode(file_get_contents('php://input'), true);
$id = (int)($data['id'] ?? 0);

if ($id <= 0) {
    send_response(400, false, 'Transaction ID দিন', null);
}

function table_has_column(PDO $pdo, string $table, string $column): bool
{
    $stmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = ?
          AND COLUMN_NAME = ?
    ");
    $stmt->execute([$table, $column]);
    return (int)$stmt->fetchColumn() > 0;
}

try {
    $hasDeletedAt = table_has_column($pdo, 'cash_transactions', 'deleted_at');
    $hasIsReversal = table_has_column($pdo, 'cash_transactions', 'is_reversal');

    $selectSql = "
        SELECT
            id,
            cash_account_id,
            transaction_type,
            amount" .
            ($hasDeletedAt ? ", deleted_at" : "") .
            ($hasIsReversal ? ", is_reversal" : "") . "
        FROM cash_transactions
        WHERE id = ?
        LIMIT 1
    ";

    $stmt = $pdo->prepare($selectSql);
    $stmt->execute([$id]);
    $txn = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$txn) {
        send_response(404, false, 'Transaction পাওয়া যায়নি', null);
    }

    if ($hasDeletedAt && !empty($txn['deleted_at'])) {
        send_response(400, false, 'Transaction আগেই Delete করা হয়েছে', null);
    }

    if ($hasIsReversal && (int)($txn['is_reversal'] ?? 0) === 1) {
        send_response(400, false, 'Reversal transaction Delete করা যাবে না', null);
    }

    if (empty($txn['cash_account_id'])) {
        send_response(400, false, 'Cash account পাওয়া যায়নি', null);
    }

    $cashAccountId = (int)$txn['cash_account_id'];

    $accStmt = $pdo->prepare("
        SELECT id, opening_balance
        FROM cash_accounts
        WHERE id = ?
        LIMIT 1
    ");
    $accStmt->execute([$cashAccountId]);
    $account = $accStmt->fetch(PDO::FETCH_ASSOC);

    if (!$account) {
        send_response(404, false, 'Cash account পাওয়া যায়নি', null);
    }

    $pdo->beginTransaction();

    if ($hasDeletedAt) {
        $delStmt = $pdo->prepare("
            UPDATE cash_transactions
            SET deleted_at = NOW()
            WHERE id = ?
            LIMIT 1
        ");
        $delStmt->execute([$id]);
    } else {
        $delStmt = $pdo->prepare("
            DELETE FROM cash_transactions
            WHERE id = ?
            LIMIT 1
        ");
        $delStmt->execute([$id]);
    }

    $sumWhere = "cash_account_id = ?";
    if ($hasDeletedAt) {
        $sumWhere .= " AND deleted_at IS NULL";
    }
    if ($hasIsReversal) {
        $sumWhere .= " AND is_reversal = 0";
    }

    $sumStmt = $pdo->prepare("
        SELECT COALESCE(SUM(
            CASE
                WHEN amount < 0 THEN amount
                WHEN UPPER(COALESCE(transaction_type, '')) = 'IN' THEN amount
                ELSE -amount
            END
        ), 0) AS net_amount
        FROM cash_transactions
        WHERE $sumWhere
    ");
    $sumStmt->execute([$cashAccountId]);
    $netAmount = (float)($sumStmt->fetchColumn() ?? 0);

    $newBalance = (float)($account['opening_balance'] ?? 0) + $netAmount;

    $balStmt = $pdo->prepare("
        UPDATE cash_accounts
        SET current_balance = ?
        WHERE id = ?
        LIMIT 1
    ");
    $balStmt->execute([$newBalance, $cashAccountId]);

    $pdo->commit();

    send_response(200, true, 'Transaction সফলভাবে Delete হয়েছে', [
        'transaction_id' => $id,
        'cash_account_id' => $cashAccountId,
        'current_balance' => round($newBalance, 2)
    ]);

} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    send_response(500, false, 'সার্ভার সমস্যা', [
        'error' => $e->getMessage()
    ]);
}
?>