<?php
header('Content-Type: application/json');
require("../../includes/config.php");

// Get raw input
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// 1. Basic Validation
if (!isset($data['id']) || empty($data['id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid or missing ID.']);
    exit;
}

$id = (int)$data['id'];

try {
    // 2. FETCH STATUS & EXISTENCE CHECK
    // We use a specific table name 'fee_assign' (cleaned up double spaces)
    $stmt = $pdo->prepare("SELECT payment_status FROM fee_assign WHERE id = ?");
    $stmt->execute([$id]);
    $currentStatus = $stmt->fetchColumn();

    // If no record is found at all
    if ($currentStatus === false) {
        echo json_encode(['status' => 'error', 'message' => 'Record not found.']);
        exit;
    }

    // 3. SAFETY LOCK: Block deletion if status is anything other than 'unpaid'
    // Using strtolower to handle 'Unpaid', 'UNPAID', or 'unpaid' correctly
    if (strtolower(trim($currentStatus)) !== 'unpaid') {
        echo json_encode([
            'status' => 'error', 
            'message' => 'Safety Lock: This record has payment history and cannot be deleted.'
        ]);
        exit;
    }

    // 4. PROCEED WITH DELETE
    $delete = $pdo->prepare("DELETE FROM fee_assign WHERE id = ?");
    $result = $delete->execute([$id]);

    if ($result) {
        echo json_encode(['status' => 'success', 'message' => 'Fee assignment deleted successfully.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Failed to delete record.']);
    }

} catch (PDOException $e) {
    // Log error to server log and show a clean message to user
    error_log("Delete Assignment Error: " . $e->getMessage());
    echo json_encode(['status' => 'error', 'message' => 'Database error occurred.']);
}?>