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

$response = ['status' => 'error', 'message' => ''];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 1. Capture Data
    $id = $_POST['edit_fee_id'] ?? null;
    $fee_title = trim($_POST['edit_fee_title'] ?? '');
    $description = trim($_POST['edit_description'] ?? '');
    $amount = trim($_POST['edit_amount'] ?? '');
    $class_id = $_POST['edit_class_id'] ?? null;
    $academic_year_id = $_POST['edit_academic_year_id'] ?? null;
    
    // Captured medium_id (Removed stream logic)
    $medium_id = $_POST['edit_medium_id'] ?? ''; 
    $medium_val = ($medium_id !== '') ? $medium_id : null;

    // Receive km_range from JS
    $km_range = trim($_POST['edit_km_range'] ?? 0);

    if ($fee_title !== 'Transport Fee') {
        $km_range = 0;
    } else {
        $km_range = (int) $km_range;
    }

    // 2. Validation
    if (!$id || empty($fee_title) || empty($amount) || !$class_id || !$academic_year_id || empty($medium_id)) {
        $response['message'] = 'All fields (Title, Class, Medium, Year, and Amount) are required.';
        echo json_encode($response);
        exit;
    }

    try {
        // 3. Duplicate Check (Removed stream_id conditions)
        $checkSql = "SELECT COUNT(*) FROM fee_types 
                     WHERE fee_title = :fee_title 
                     AND class_id = :class_id 
                     AND academic_year_id = :academic_year_id
                     AND km_range = :km_range
                     AND medium_id = :medium_id
                     AND id != :id";

        $checkStmt = $pdo->prepare($checkSql);
        $checkStmt->execute([
            ':fee_title' => $fee_title,
            ':class_id' => $class_id,
            ':academic_year_id' => $academic_year_id,
            ':km_range' => $km_range,
            ':medium_id' => $medium_val,
            ':id' => $id
        ]);

        if ($checkStmt->fetchColumn() > 0) {
            $response['message'] = "This fee already exists for this Class, Medium, and KM range.";
        } else {
            // 4. Update (Removed stream_id column)
            $sql = "UPDATE fee_types 
                    SET fee_title = :fee_title, 
                        description = :description, 
                        amount = :amount, 
                        class_id = :class_id,
                        medium_id = :medium_id,
                        academic_year_id = :academic_year_id,
                        km_range = :km_range 
                    WHERE id = :id";

            $stmt = $pdo->prepare($sql);
            $result = $stmt->execute([
                ':fee_title' => $fee_title,
                ':description' => $description,
                ':amount' => $amount,
                ':class_id' => $class_id,
                ':medium_id' => $medium_val,
                ':academic_year_id' => $academic_year_id,
                ':km_range' => $km_range,
                ':id' => $id
            ]);

            if ($result) {
                $response['status'] = 'success';
                $response['message'] = 'Fee type updated successfully.';
            } else {
                $response['status'] = 'error';
                $response['message'] = 'Failed to update database.';
            }
        }
    } catch (PDOException $e) {
        $response['message'] = 'Database Error: ' . $e->getMessage();
    }
} else {
    $response['message'] = 'Invalid request method: ' . $_SERVER['REQUEST_METHOD'];
}

echo json_encode($response);
?>