<?php
// /public_html/erp.jewellersbd.com/api/purchases/delete_purchase.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, 'Purchase ID দিন', null);
}

try {
    $stmt = $pdo->prepare("
        SELECT
            id,
            party_id,
            payment_method_id,
            total_amount,
            deleted_at
        FROM purchases
        WHERE id = ?
        LIMIT 1
    ");
    $stmt->execute([$id]);
    $pur = $stmt->fetch(PDO::FETCH_ASSOC);

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

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

    $pdo->beginTransaction();

    // 1) Purchase soft delete
    $delPur = $pdo->prepare("
        UPDATE purchases
        SET deleted_at = NOW()
        WHERE id = ?
        LIMIT 1
    ");
    $delPur->execute([$id]);

    // 2) CASH payment হলে related cash transaction খুঁজে delete
    if ((int)$pur['payment_method_id'] === 1) {

        $cashTxnStmt = $pdo->prepare("
            SELECT id, cash_account_id
            FROM cash_transactions
            WHERE reference_type = 'PURCHASE'
              AND reference_id = ?
              AND deleted_at IS NULL
            ORDER BY id DESC
        ");
        $cashTxnStmt->execute([$id]);
        $cashTxns = $cashTxnStmt->fetchAll(PDO::FETCH_ASSOC);

        if ($cashTxns) {
            $cashAccountIds = [];

            $delTxn = $pdo->prepare("
                UPDATE cash_transactions
                SET deleted_at = NOW()
                WHERE id = ?
                LIMIT 1
            ");

            foreach ($cashTxns as $txn) {
                $delTxn->execute([$txn['id']]);
                if (!empty($txn['cash_account_id'])) {
                    $cashAccountIds[] = (int)$txn['cash_account_id'];
                }
            }

            $cashAccountIds = array_values(array_unique($cashAccountIds));

            $recalcStmt = $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 = ?
            ");

            foreach ($cashAccountIds as $accId) {
                $recalcStmt->execute([$accId, $accId]);
            }
        }
    }

    // 3) Party balance restore
    if (!empty($pur['party_id'])) {
        $partyStmt = $pdo->prepare("
            UPDATE parties
            SET balance = balance + ?
            WHERE id = ?
            LIMIT 1
        ");
        $partyStmt->execute([
            $pur['total_amount'],
            $pur['party_id']
        ]);
    }

    $pdo->commit();

    send_response(200, true, 'Purchase সফলভাবে Delete হয়েছে', [
        'purchase_id' => $id
    ]);

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

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