<?php
// /public_html/erp.jewellersbd.com/api/cash/add_transaction.php
// v3 — 2026-05-27: Fixed for new clean cash_transactions schema
//                  Removed: type, note columns → now uses description

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

$cash_account_id     = $data['cash_account_id'] ?? null;
$transaction_type_id = $data['transaction_type_id'] ?? 1;
$transaction_type    = strtoupper(trim((string)($data['transaction_type'] ?? '')));
$amount              = $data['amount'] ?? null;
$note                = trim((string)($data['note'] ?? ''));
$transaction_date    = $data['transaction_date'] ?? date('Y-m-d');

if (empty($cash_account_id) || empty($transaction_type) || $amount === null || $amount === '') {
    send_response(400, false, 'সব তথ্য দিন', null);
}

if (!in_array($transaction_type, ['IN', 'OUT'], true)) {
    send_response(400, false, 'লেনদেনের ধরন ভুল', null);
}

$amount = (float)$amount;
if ($amount <= 0) {
    send_response(400, false, 'টাকার পরিমাণ সঠিক নয়', null);
}

function normalize_account_name($name): string
{
    $name = trim((string)$name);
    $lower = mb_strtolower($name, 'UTF-8');

    $map = [
        'showroom cash'  => 'শোরুম ক্যাশ',
        'showroom নগদ'   => 'শোরুম ক্যাশ',
        'শোরুম নগদ'      => 'শোরুম ক্যাশ',
        'শোরুম cash'     => 'শোরুম ক্যাশ',
        'factory cash'   => 'ফ্যাক্টরি ক্যাশ',
        'factory নগদ'    => 'ফ্যাক্টরি ক্যাশ',
        'ফ্যাক্টরি নগদ'  => 'ফ্যাক্টরি ক্যাশ',
        'ফ্যাক্টরি cash' => 'ফ্যাক্টরি ক্যাশ',
        'locker cash'    => 'লকার ক্যাশ',
        'locker নগদ'     => 'লকার ক্যাশ',
        'লকার নগদ'       => 'লকার ক্যাশ',
        'লকার cash'      => 'লকার ক্যাশ',
    ];

    return $map[$lower] ?? $name;
}

function fallback_note(int $transactionTypeId, string $transactionType): string
{
    $typeMap = [
        1 => 'ওপেনিং ব্যালেন্স',
        2 => 'বিক্রয় আদায়',
        3 => 'ক্রয় পরিশোধ',
        4 => 'অফিস খরচ',
        5 => 'ব্যাংকে জমা',
        6 => 'ব্যাংক থেকে উত্তোলন',
        7 => 'অন্যান্য আয়',
        8 => 'অন্যান্য খরচ',
    ];

    if (isset($typeMap[$transactionTypeId])) {
        return $typeMap[$transactionTypeId];
    }

    return $transactionType === 'IN' ? 'ক্যাশ ইন' : 'ক্যাশ আউট';
}

// $type (cash_in/cash_out) column removed — no longer needed

if ($note === '') {
    $note = fallback_note((int)$transaction_type_id, $transaction_type);
}

try {
    $pdo->beginTransaction();

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

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

    // Balance check for OUT transactions
    if ($transaction_type === 'OUT' && (int)$transaction_type_id !== 1) {
        $current_balance = (float)($account['current_balance'] ?? 0);
        if ($amount > $current_balance + 0.001) {
            $pdo->rollBack();
            send_response(400, false,
                normalize_account_name($account['account_name']) . "-এ পর্যাপ্ত টাকা নেই। " .
                "বর্তমান ব্যালেন্স: ৳" . number_format($current_balance, 2) . ", " .
                "চাহিদা: ৳" . number_format($amount, 2),
                [
                    'current_balance'  => $current_balance,
                    'requested_amount' => $amount,
                    'short_by'         => round($amount - $current_balance, 2)
                ]
            );
        }
    }

    // ✅ FIXED: type + note columns removed, using description now
    $stmt = $pdo->prepare("
        INSERT INTO cash_transactions
        (
            transaction_date,
            cash_account_id,
            transaction_type_id,
            transaction_type,
            amount,
            description,
            reference_type,
            is_reversal
        )
        VALUES (?, ?, ?, ?, ?, ?, 'MANUAL', 0)
    ");

    $stmt->execute([
        $transaction_date,
        $cash_account_id,
        $transaction_type_id,
        $transaction_type,
        $amount,
        $note
    ]);

    $txn_id = (int)$pdo->lastInsertId();

    // Recalculate account balance
    $recalc = $pdo->prepare("
        UPDATE cash_accounts
        SET current_balance =
            opening_balance + COALESCE((
                SELECT SUM(
                    CASE
                        WHEN transaction_type = 'IN' THEN amount
                        ELSE -amount
                    END
                )
                FROM cash_transactions
                WHERE cash_account_id = ?
                  AND deleted_at IS NULL
                  AND is_reversal = 0
            ), 0)
        WHERE id = ?
    ");
    $recalc->execute([$cash_account_id, $cash_account_id]);

    $stmt2 = $pdo->prepare("
        SELECT id, account_name, current_balance
        FROM cash_accounts
        WHERE id = ?
        LIMIT 1
    ");
    $stmt2->execute([$cash_account_id]);
    $updated = $stmt2->fetch(PDO::FETCH_ASSOC);

    $pdo->commit();

    send_response(200, true, 'লেনদেন সফলভাবে সেভ হয়েছে', [
        'transaction_id'  => $txn_id,
        'cash_account_id' => (int)$cash_account_id,
        'transaction_type'=> $transaction_type,
        'amount'          => round($amount, 2),
        'note'            => $note,
        'current_balance' => round((float)($updated['current_balance'] ?? 0), 2),
        'account_name'    => normalize_account_name($updated['account_name'] ?? '')
    ]);

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

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