<?php
header('Content-Type: application/json');
ini_set('display_errors', 0); // Keep it clean for JSON

try {
    require("../../includes/config.php");

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

    // Validate that all required fields are present
    if (!empty($data['get_student_id']) && !empty($data['fee_type_id']) && !empty($data['due_month'])) {
        
        // --- STEP 1: Check if this specific fee is already assigned for this month ---
        $checkSql = "SELECT COUNT(*) FROM fee_assign 
                     WHERE student_id = ? 
                     AND fee_type_id = ? 
                     AND due_month = ?";
        
        $checkStmt = $pdo->prepare($checkSql);
        $checkStmt->execute([
            $data['get_student_id'],
            $data['fee_type_id'],
            $data['due_month']
        ]);

        if ($checkStmt->fetchColumn() > 0) {
            // Duplicate found - stop the process
            echo json_encode([
                'status' => 'error', 
                'message' => 'Error: This fee has already been assigned to this student for the selected month.'
            ]);
            exit;
        }

        // --- STEP 2: Proceed with the Insertion ---
        $sql = "INSERT INTO fee_assign 
                (student_id, fee_type_id, amount, due_month, due_date, payment_status) 
                VALUES (?, ?, ?, ?, ?, 'unpaid')";
        
        $stmt = $pdo->prepare($sql);
        $success = $stmt->execute([
            $data['get_student_id'],
            $data['fee_type_id'],
            $data['fee_amount'],
            $data['due_month'],
            $data['due_date']
        ]);

        if ($success) {
            echo json_encode(['status' => 'success', 'message' => 'Fee assigned successfully.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Failed to assign fee.']);
        }

    } else {
        echo json_encode(['status' => 'error', 'message' => 'All fields are required.']);
    }

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => 'System Error: ' . $e->getMessage()]);
}
?>