<?php
require_once '../../config/db.php';
require_once '../../config/session.php';
require_once '../../config/response.php';

session_start_if_not_started();

if(!isset($_SESSION['user_id'])){
    send_response(401, false, 'অনুমতি নেই');
}

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

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

if(!$id){
    send_response(400, false, 'Purchase ID দিন');
}

try {
    $stmt = $pdo->prepare(
        "SELECT * FROM purchase_stock WHERE id=?"
    );
    $stmt->execute([$id]);
    $pur = $stmt->fetch();

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

    $bcStmt = $pdo->prepare(
        "SELECT COUNT(*) as cnt
         FROM barcode_stock
         WHERE purchase_stock_id=?
         AND status='sold'"
    );
    $bcStmt->execute([$id]);
    $sold = $bcStmt->fetch()['cnt'];

    if($sold > 0){
        send_response(400, false,
            'এই Purchase এর '.$sold.'টি item বিক্রি হয়েছে — Delete করা যাবে না!');
    }

    $pdo->beginTransaction();

    $pdo->prepare(
        "UPDATE barcode_stock
         SET deleted_at=NOW()
         WHERE purchase_stock_id=?
         AND deleted_at IS NULL"
    )->execute([$id]);

    $pdo->prepare(
        "UPDATE purchase_stock
         SET deleted_at=NOW()
         WHERE id=?"
    )->execute([$id]);

    if(!empty($pur['cash_account_id']) && $pur['payment_method_id']==1){
        $pdo->prepare(
            "UPDATE cash_transactions
             SET deleted_at=NOW()
             WHERE reference_type='NEW_PURCHASE'
             AND reference_id=?
             AND deleted_at IS NULL"
        )->execute([$id]);

        $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=?"
        )->execute([
            $pur['cash_account_id'],
            $pur['cash_account_id']
        ]);
    }

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

    $pdo->commit();

    send_response(200, true,
        'New Purchase সফলভাবে Delete হয়েছে');

} catch(Exception $e){
    $pdo->rollBack();
    send_response(500, false, 'Error: '.$e->getMessage());
}
?>