<?php
// api/submit_monthly_payment.php
// Handles the submission of monthly payment details and slip uploads for a flexible payment model.
// Payments are now recorded against the overall enrollment, not fixed installments.

// --- START TEMPORARY AGGRESSIVE DEBUGGING ---
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// --- END TEMPORARY AGGRESSIVE DEBUGGING ---

header('Content-Type: application/json'); // Crucial: tell browser to expect JSON response

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Ensure user is logged in and is a student
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || $_SESSION['user_role'] !== 'student') {
    error_log("SUBMIT_MONTHLY_PAYMENT_API: Unauthorized access attempt. Session: " . print_r($_SESSION, true));
    echo json_encode(['success' => false, 'message' => 'Authentication required or not authorized.']);
    exit();
}

require_once '../config/database.php'; // Path to database connection

$response = ['success' => false, 'message' => ''];
$student_id = $_SESSION['user_id'];

error_log("SUBMIT_MONTHLY_PAYMENT_API: Request received. Student ID: " . $student_id);
error_log("SUBMIT_MONTHLY_PAYMENT_API: POST data: " . print_r($_POST, true));
error_log("SUBMIT_MONTHLY_PAYMENT_API: FILES data: " . print_r($_FILES, true));


// Get data from POST request (FormData sends as $_POST and $_FILES)
$enrollment_id = filter_var($_POST['enrollment_id'] ?? null, FILTER_VALIDATE_INT);
$bank_name = trim($_POST['bank_name'] ?? '');
$branch_code = trim($_POST['branch_code'] ?? '');
$slip_number = trim($_POST['slip_number'] ?? '');
$payment_date = trim($_POST['payment_date'] ?? '');
$paid_amount = filter_var($_POST['paid_amount'] ?? null, FILTER_VALIDATE_FLOAT);

$payment_slip_file = $_FILES['payment_slip'] ?? null;

// --- 1. Basic Input Validation ---
if (!$enrollment_id || empty($bank_name) || empty($slip_number) || empty($payment_date) || $paid_amount === false || $paid_amount <= 0 || !$payment_slip_file || $payment_slip_file['error'] !== UPLOAD_ERR_OK) {
    $error_details = [
        'enrollment_id_valid' => ($enrollment_id !== false && $enrollment_id !== null),
        'bank_name_empty' => empty($bank_name),
        'slip_number_empty' => empty($slip_number),
        'payment_date_empty' => empty($payment_date),
        'paid_amount_valid' => ($paid_amount !== false && $paid_amount > 0),
        'file_exists' => ($payment_slip_file !== null),
        'file_error_code' => ($payment_slip_file ? $payment_slip_file['error'] : 'N/A')
    ];
    $response['message'] = "Missing or invalid payment details or file upload error. " . json_encode($error_details);
    error_log("SUBMIT_MONTHLY_PAYMENT_API: Input validation failed: " . json_encode($error_details));
    echo json_encode($response);
    exit();
}

try {
    // --- 2. Verify Enrollment and Student Ownership ---
    $stmt = $pdo->prepare("
        SELECT id, student_id
        FROM course_enrollments
        WHERE id = ? AND student_id = ? LIMIT 1
    ");
    $stmt->execute([$enrollment_id, $student_id]);
    $enrollment_info = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$enrollment_info) {
        $response['message'] = "Enrollment not found or you don't have permission to make payments for it.";
        error_log("SUBMIT_MONTHLY_PAYMENT_API: Enrollment ID " . $enrollment_id . " not found for student " . $student_id . ".");
        echo json_encode($response);
        exit();
    }

    // --- 3. Handle File Upload ---
    $upload_dir = '../public/uploads/monthly_slips/'; // Make sure this directory exists and is writable!
    error_log("SUBMIT_MONTHLY_PAYMENT_API: Upload directory: " . $upload_dir);
    if (!is_dir($upload_dir)) {
        if (!mkdir($upload_dir, 0777, true)) { // Create directory if it doesn't exist, recursive
            throw new Exception("Failed to create upload directory: " . $upload_dir);
        }
        error_log("SUBMIT_MONTHLY_PAYMENT_API: Upload directory created: " . $upload_dir);
    } elseif (!is_writable($upload_dir)) {
        throw new Exception("Upload directory is not writable: " . $upload_dir);
    }


    $file_extension = pathinfo($payment_slip_file['name'], PATHINFO_EXTENSION);
    $new_file_name = uniqid('monthly_slip_') . '.' . $file_extension;
    $target_file = $upload_dir . $new_file_name;
    $relative_slip_path = 'public/uploads/monthly_slips/' . $new_file_name; // Path to store in DB

    error_log("SUBMIT_MONTHLY_PAYMENT_API: Attempting to move file from " . $payment_slip_file['tmp_name'] . " to " . $target_file);
    if (!move_uploaded_file($payment_slip_file['tmp_name'], $target_file)) {
        throw new Exception("Failed to move uploaded payment slip file. Check permissions.");
    }
    error_log("SUBMIT_MONTHLY_PAYMENT_API: File successfully moved to: " . $target_file);

    // Start a transaction for atomicity
    $pdo->beginTransaction();

    // --- 4. Insert New Monthly Payment Record ---
    // Note: amount_due is NULL as per flexible payment model. month_due_date represents the payment date conceptually.
    $stmt = $pdo->prepare("
        INSERT INTO monthly_payments
        (enrollment_id, month_due_date, amount_due, status, paid_amount, bank_name,
        branch_code, slip_number, payment_date, slip_path, uploaded_at)
        VALUES (?, ?, NULL, 'uploaded', ?, ?, ?, ?, ?, ?, NOW())
    ");
    // Use the actual payment_date provided by the user for month_due_date (as a general "payment for this month" date)
    // Convert payment_date to YYYY-MM-01 format for month_due_date consistency
    $payment_month_date = (new DateTime($payment_date))->format('Y-m-01');

    error_log("SUBMIT_MONTHLY_PAYMENT_API: Inserting into monthly_payments with values: " .
              "Enrollment ID: " . $enrollment_id . ", Month Due Date: " . $payment_month_date .
              ", Paid Amount: " . $paid_amount . ", Bank Name: " . $bank_name .
              ", Branch Code: " . $branch_code . ", Slip Number: " . $slip_number .
              ", Payment Date: " . $payment_date . ", Slip Path: " . $relative_slip_path);

    if (!$stmt->execute([
        $enrollment_id, $payment_month_date, $paid_amount, $bank_name,
        $branch_code, $slip_number, $payment_date, $relative_slip_path
    ])) {
        $error_info = $stmt->errorInfo();
        throw new Exception("Failed to record new monthly payment details. DB Error: " . ($error_info[2] ?? 'Unknown'));
    }

    $pdo->commit(); // Commit the transaction
    $response['success'] = true;
    $response['message'] = "Your payment of $" . number_format($paid_amount, 2) . " has been submitted successfully! Pending admin verification.";
    error_log("SUBMIT_MONTHLY_PAYMENT_API: Payment submitted successfully for enrollment " . $enrollment_id);

} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack(); // Rollback if something went wrong during transaction
    }
    // Delete the uploaded file if database insertion failed or any other error occurred
    if (isset($target_file) && file_exists($target_file)) {
        unlink($target_file);
        error_log("SUBMIT_MONTHLY_PAYMENT_API: Uploaded file " . $target_file . " deleted due to error.");
    }
    $response['message'] = "Server error: " . $e->getMessage();
    error_log("SUBMIT_MONTHLY_PAYMENT_API FATAL ERROR: " . $e->getMessage());
}

echo json_encode($response);
exit();
