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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fee_id = $_POST['fee_id'] ?? null;
    $due_date = $_POST['due_date'] ?? null; // Base date (e.g., 2026-04-10)
    $due_months = $_POST['due_months'] ?? []; 
    $student_ids = $_POST['student_ids'] ?? [];
    $medium_id = $_POST['medium_id'] ?? null; 

    // REMOVED: stream_id capture logic

    if (!$fee_id || !$due_date || empty($student_ids) || empty($due_months)) {
        echo json_encode(['status' => 'error', 'message' => 'Missing required data.']);
        exit;
    }

    try {
        $pdo->beginTransaction();

        // 1. Get Fee Amount
        $feeQuery = $pdo->prepare("SELECT amount FROM fee_types WHERE id = ?");
        $feeQuery->execute([$fee_id]);
        $fee_data = $feeQuery->fetch();
        
        if (!$fee_data) {
            throw new Exception("Invalid Fee Type selected.");
        }
        $total_amount = $fee_data['amount'];

        // 2. Extract Base Day and Year for dynamic date generation
        $base_day = date('d', strtotime($due_date));
        $base_year = date('Y', strtotime($due_date));

        // 3. Prepare Statements (REMOVED: stream_id logic from SQL)
        $checkSql = "SELECT COUNT(*) FROM fee_assign 
                     WHERE student_id = :stu_id 
                     AND fee_type_id = :fee_id 
                     AND due_month = :d_month";
        $checkStmt = $pdo->prepare($checkSql);

        $insertSql = "INSERT INTO fee_assign (student_id, fee_type_id, due_month, due_date, total_amount, remaining_amount, payment_status) 
                      VALUES (:stu_id, :fee_id, :d_month, :d_date, :total, :remain, 'unpaid')";
        $insertStmt = $pdo->prepare($insertSql);

        $assignedCount = 0;
        $skippedCount = 0;

        // 4. NESTED LOOP: Students -> Months
        foreach ($student_ids as $stu_id) {
            foreach ($due_months as $month) {
                
                // GENERATE DYNAMIC DUE DATE
                $generated_date = date('Y-m-d', strtotime("$base_day $month $base_year"));

                // Check for duplicate
                $checkStmt->execute([
                    ':stu_id'   => $stu_id,
                    ':fee_id'   => $fee_id,
                    ':d_month'  => $month
                ]);

                if ($checkStmt->fetchColumn() == 0) {
                    $insertStmt->execute([
                        ':stu_id'    => $stu_id,
                        ':fee_id'    => $fee_id,
                        ':d_month'   => $month,
                        ':d_date'    => $generated_date,
                        ':total'     => $total_amount,
                        ':remain'    => $total_amount
                    ]);
                    $assignedCount++;
                } else {
                    $skippedCount++;
                }
            }
        }

        $pdo->commit();
        
        $response['status'] = 'success';
        $response['message'] = "Successfully created $assignedCount fee entries.";
        if ($skippedCount > 0) {
            $response['message'] .= " ($skippedCount entries skipped as they already existed).";
        }

    } catch (Exception $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        $response['message'] = 'Error: ' . $e->getMessage();
    }
} else {
    $response['message'] = 'Invalid request method.';
}

echo json_encode($response);
?>