<?php
require_once __DIR__ . '/../_core.php';
header('Content-Type: application/json; charset=utf-8');

try {
    $input = json_decode(file_get_contents('php://input'), true);
    if (!$input) $input = $_POST;

    $id = intval($input['id'] ?? $_GET['id'] ?? 0);
    if ($id <= 0) throw new Exception('লকার ID দরকার');

    // Check if locker has pledges
    $chk = $pdo->prepare("SELECT COUNT(*) AS cnt FROM pawn_pledges WHERE locker_id = ?");
    $chk->execute([$id]);
    $count = (int)($chk->fetch(PDO::FETCH_ASSOC)['cnt'] ?? 0);

    if ($count > 0) {
        // Soft delete - mark inactive
        $stmt = $pdo->prepare("UPDATE lockers SET status='inactive' WHERE id=?");
        $stmt->execute([$id]);
        echo json_encode([
            'success' => true,
            'message' => "লকার Inactive করা হয়েছে ($count টি bondhok এই লকারে আছে, তাই মুছে ফেলা হয়নি)"
        ]);
    } else {
        // Hard delete - no pledges
        $stmt = $pdo->prepare("DELETE FROM lockers WHERE id=?");
        $stmt->execute([$id]);
        echo json_encode(['success' => true, 'message' => 'লকার মুছে ফেলা হয়েছে ✅']);
    }
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}