<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

include_once 'db_connect.php';

$method = $_SERVER['REQUEST_METHOD'];

// 1. GET: Fetch all fee data
if ($method == 'GET') {
    $tuition = [];
    $mandatory = [];

    $res1 = $conn->query("SELECT * FROM tuition_fees ORDER BY display_order ASC");
    while($row = $res1->fetch_assoc()) $tuition[] = $row;

    $res2 = $conn->query("SELECT * FROM mandatory_fees ORDER BY id ASC");
    while($row = $res2->fetch_assoc()) $mandatory[] = $row;

    echo json_encode([
        "success" => true, 
        "tuition" => $tuition, 
        "mandatory" => $mandatory
    ]);
}

// 2. POST: Save Fee Item (Create or Update)
if ($method == 'POST') {
    $data = json_decode(file_get_contents("php://input"));
    $type = $data->type; // 'tuition' or 'mandatory'

    if ($type === 'tuition') {
        $level = mysqli_real_escape_string($conn, $data->level);
        $amount = mysqli_real_escape_string($conn, $data->amount);
        $order = intval($data->display_order);

        if (isset($data->id) && $data->id > 0) {
            $id = intval($data->id);
            $query = "UPDATE tuition_fees SET level='$level', amount='$amount', display_order=$order WHERE id=$id";
        } else {
            $query = "INSERT INTO tuition_fees (level, amount, display_order) VALUES ('$level', '$amount', $order)";
        }
    } else {
        $item = mysqli_real_escape_string($conn, $data->item);
        $amount = mysqli_real_escape_string($conn, $data->amount);
        $notes = mysqli_real_escape_string($conn, $data->notes);

        if (isset($data->id) && $data->id > 0) {
            $id = intval($data->id);
            $query = "UPDATE mandatory_fees SET item='$item', amount='$amount', notes='$notes' WHERE id=$id";
        } else {
            $query = "INSERT INTO mandatory_fees (item, amount, notes) VALUES ('$item', '$amount', '$notes')";
        }
    }

    if ($conn->query($query)) {
        echo json_encode(["success" => true, "message" => "Fee record saved."]);
    } else {
        http_response_code(500);
        echo json_encode(["success" => false, "message" => "Save failed: " . $conn->error]);
    }
}

// 3. DELETE: Remove Fee Item
if ($method == 'DELETE') {
    $id = intval($_GET['id']);
    $table = ($_GET['type'] === 'tuition') ? 'tuition_fees' : 'mandatory_fees';
    
    if ($id > 0) {
        $query = "DELETE FROM $table WHERE id = $id";
        if ($conn->query($query)) {
            echo json_encode(["success" => true, "message" => "Record deleted."]);
        }
    }
}

$conn->close();
?>