<?php
// File: /public_html/erp.jewellersbd.com/api/cash/cash_transaction_delete.php
// Cash Module 2.0 — soft delete a MANUAL cash transaction + recalc balance
// Audit Added: cash_transactions DELETE

header("Content-Type: application/json; charset=UTF-8");

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

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

function ctd_send($ok, $msg, $data = null, $code = 200)
{
    http_response_code($code);
    echo json_encode([
        "success" => $ok,
        "message" => $msg,
        "data" => $data
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

/**
 * Safe Audit Logger
 * Audit fail হলেও cash delete বন্ধ হবে না।
 */
function ctd_safe_audit_log($pdo, $tableName, $recordId, $action, $changedBy, $note = '')
{
    try {
        if (!$pdo || !($pdo instanceof PDO)) {
            return;
        }

        $ipAddress = $_SERVER['REMOTE_ADDR'] ?? '';

        $stmt = $pdo->prepare("
            INSERT INTO audit_log
                (table_name, record_id, action, changed_by, changed_at, ip_address, note)
            VALUES
                (:table_name, :record_id, :action, :changed_by, NOW(), :ip_address, :note)
        ");

        $stmt->execute([
            ':table_name' => $tableName,
            ':record_id'  => (int)$recordId,
            ':action'     => $action,
            ':changed_by' => (int)$changedBy,
            ':ip_address' => $ipAddress,
            ':note'       => $note
        ]);

    } catch (Throwable $e) {
        return;
    }
}

if (
    (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) &&
    (!function_exists('is_logged_in') || !is_logged_in())
) {
    ctd_send(false, "লগইন প্রয়োজন", null, 401);
}

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    ctd_send(false, "Invalid method", null, 405);
}

$in = json_decode(file_get_contents('php://input'), true);

if (!is_array($in)) {
    ctd_send(false, "Invalid JSON", null, 400);
}

$id     = (int)($in['id'] ?? 0);
$reason = trim((string)($in['reason'] ?? ''));

if ($id <= 0) {
    ctd_send(false, "id দিন", null, 422);
}

$userId = (int)($_SESSION['user_id'] ?? 0);
if ($userId <= 0 && function_exists('gs_current_user_id')) {
    $userId = (int)gs_current_user_id();
}

try {
    $st = $pdo->prepare("
        SELECT 
            id,
            cash_account_id,
            direction,
            amount,
            reference_type,
            is_locked,
            is_deleted,
            voucher_no
        FROM cash_transactions 
        WHERE id = ? 
        LIMIT 1
    ");
    $st->execute([$id]);
    $txn = $st->fetch();

    if (!$txn) {
        ctd_send(false, "লেনদেন পাওয়া যায়নি", null, 404);
    }

    if ((int)$txn['is_deleted'] === 1) {
        ctd_send(false, "এটি ইতিমধ্যে মুছে ফেলা হয়েছে", null, 422);
    }

    if ((int)$txn['is_locked'] === 1) {
        ctd_send(false, "দিন বন্ধ (locked) — এই এন্ট্রি মোছা যাবে না", null, 422);
    }

    if ((string)$txn['reference_type'] !== 'MANUAL') {
        ctd_send(false, "এই এন্ট্রিটি " . $txn['reference_type'] . " এর সাথে যুক্ত — সংশ্লিষ্ট মডিউল থেকে বাতিল করুন", null, 422);
    }

    $accountId = (int)$txn['cash_account_id'];
    $deleteReason = $reason !== '' ? $reason : 'Manual delete';

    $pdo->beginTransaction();

    $upd = $pdo->prepare("
        UPDATE cash_transactions
        SET 
            is_deleted = 1,
            deleted_by = ?,
            deleted_at = NOW(),
            delete_reason = ?
        WHERE id = ?
          AND reference_type = 'MANUAL'
          AND is_locked = 0
          AND is_deleted = 0
    ");

    $upd->execute([
        $userId,
        $deleteReason,
        $id
    ]);

    if ($upd->rowCount() === 0) {
        $pdo->rollBack();
        ctd_send(false, "কোনো পরিবর্তন প্রয়োগ হয়নি", null, 422);
    }

    if (function_exists('gs_recalc_cash_account')) {
        gs_recalc_cash_account($pdo, $accountId);
    }

    $auditNote = "Manual cash transaction soft deleted"
        . " | Voucher: " . ($txn['voucher_no'] ?? '')
        . " | Direction: " . ($txn['direction'] ?? '')
        . " | Amount: " . number_format((float)$txn['amount'], 2)
        . " | Reason: " . $deleteReason;

    ctd_safe_audit_log(
        $pdo,
        'cash_transactions',
        $id,
        'DELETE',
        $userId,
        $auditNote
    );

    $pdo->commit();

    $bs = $pdo->prepare("
        SELECT account_name, current_balance 
        FROM cash_accounts 
        WHERE id = ? 
        LIMIT 1
    ");
    $bs->execute([$accountId]);
    $b = $bs->fetch() ?: [];

    ctd_send(true, "লেনদেন মুছে ফেলা হয়েছে", [
        "id"           => $id,
        "account_name" => $b['account_name'] ?? '',
        "new_balance"  => round((float)($b['current_balance'] ?? 0), 2)
    ]);

} catch (Throwable $e) {
    if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) {
        $pdo->rollBack();
    }

    ctd_send(false, "সার্ভার সমস্যা: " . $e->getMessage(), null, 500);
}
?>