<?php
// /public_html/erp.jewellersbd.com/api/parties/delete_party.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, 'পার্টি ID দিন', null);
}

try {
    $stmt = $pdo->prepare("
        SELECT id, name, deleted_at
        FROM parties
        WHERE id = ?
        LIMIT 1
    ");
    $stmt->execute([$id]);
    $party = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$party) {
        send_response(404, false, 'পার্টি পাওয়া যায়নি', null);
    }

    if (!empty($party['deleted_at'])) {
        send_response(400, false, 'পার্টি আগেই ডিলিট করা হয়েছে', null);
    }

    $purStmt = $pdo->prepare("
        SELECT COUNT(*) AS cnt
        FROM purchases
        WHERE party_id = ?
          AND deleted_at IS NULL
    ");
    $purStmt->execute([$id]);
    $purCount = (int)($purStmt->fetch(PDO::FETCH_ASSOC)['cnt'] ?? 0);

    if ($purCount > 0) {
        send_response(400, false, 'এই পার্টির '.$purCount.'টি Purchase আছে — ডিলিট করা যাবে না', null);
    }

    $newPurStmt = $pdo->prepare("
        SELECT COUNT(*) AS cnt
        FROM purchase_stock
        WHERE party_id = ?
          AND deleted_at IS NULL
    ");
    $newPurStmt->execute([$id]);
    $newPurCount = (int)($newPurStmt->fetch(PDO::FETCH_ASSOC)['cnt'] ?? 0);

    if ($newPurCount > 0) {
        send_response(400, false, 'এই পার্টির '.$newPurCount.'টি New Purchase আছে — ডিলিট করা যাবে না', null);
    }

    $pledgeStmt = $pdo->prepare("
        SELECT COUNT(*) AS cnt
        FROM pawn_pledges
        WHERE party_id = ?
    ");
    $pledgeStmt->execute([$id]);
    $pledgeCount = (int)($pledgeStmt->fetch(PDO::FETCH_ASSOC)['cnt'] ?? 0);

    if ($pledgeCount > 0) {
        send_response(400, false, 'এই পার্টির '.$pledgeCount.'টি বন্ধক এন্ট্রি আছে — ডিলিট করা যাবে না', null);
    }

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

    send_response(200, true, 'পার্টি সফলভাবে ডিলিট হয়েছে', [
        'party_id' => $id,
        'name' => $party['name']
    ]);

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