<?php
// api/update_enrollment_status.php
// This API endpoint handles updating the status of a course enrollment.
// When approved, it now moves the initial payment as the first record
// into the 'monthly_payments' table, supporting a flexible payment model.

header('Content-Type: application/json');

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

// Ensure user is logged in AND is an admin/instructor.
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'instructor')) {
    echo json_encode(['success' => false, 'message' => 'Authentication required or not authorized.']);
    exit();
}

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

$input = json_decode(file_get_contents('php://input'), true);
$enrollment_id = filter_var($input['enrollment_id'] ?? null, FILTER_VALIDATE_INT);
$new_status = trim($input['new_status'] ?? '');

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

$current_user_id = $_SESSION['user_id'];
$current_user_role = $_SESSION['user_role'];

// --- 1. Basic Input Validation ---
if (!$enrollment_id || !in_array($new_status, ['enrolled', 'rejected'])) {
    $response['message'] = "Invalid enrollment ID or status provided.";
    echo json_encode($response);
    exit();
}

try {
    // Start a transaction for atomicity to ensure all related database operations succeed or fail together.
    $pdo->beginTransaction();

    // --- 2. Fetch current enrollment details and related batch/initial payment data ---
    // UPDATED: Joining with 'batches' table instead of 'courses'
    $stmt = $pdo->prepare("
        SELECT ce.id, ce.status, ce.enrollment_date, ce.student_id,
               b.id AS batch_id, b.instructor_id, b.fees, b.duration,
               p.id AS initial_payment_id, p.bank_name, p.branch_code, p.slip_number,
               p.payment_date AS initial_payment_date, p.payment_amount AS initial_paid_amount,
               p.slip_path AS initial_slip_path, p.upload_date AS initial_upload_date
        FROM course_enrollments ce
        JOIN batches b ON ce.batch_id = b.id
        LEFT JOIN payments p ON ce.id = p.enrollment_id -- LEFT JOIN to get initial payment if exists
        WHERE ce.id = ? LIMIT 1
    ");
    $stmt->execute([$enrollment_id]);
    $enrollment = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$enrollment) {
        throw new Exception("Enrollment record not found.");
    }

    // Authorization check: Instructor can only manage enrollments for their own batches.
    // UPDATED: Checking against the instructor_id from the 'batches' table.
    if ($current_user_role === 'instructor' && $enrollment['instructor_id'] != $current_user_id) {
        throw new Exception("You are not authorized to manage this enrollment. It belongs to a different batch.");
    }

    // Prevent updating if already in final status
    if ($enrollment['status'] === 'enrolled' || $enrollment['status'] === 'rejected') {
        throw new Exception("Enrollment is already in a final state (" . htmlspecialchars($enrollment['status']) . "). Cannot update.");
    }

    // Specific check: If approving, an initial payment should exist for first record in monthly payments
    if ($new_status === 'enrolled' && $enrollment['initial_paid_amount'] === null) {
        throw new Exception("Initial payment details missing for this enrollment. Cannot approve without a first payment record.");
    }

    // --- 3. Update Enrollment Status ---
    $stmt_update_enrollment = $pdo->prepare("UPDATE course_enrollments SET status = ? WHERE id = ?");
    if (!$stmt_update_enrollment->execute([$new_status, $enrollment_id])) {
        throw new Exception("Failed to update enrollment status.");
    }

    // --- 4. Process Initial Payment as First Monthly Payment Record if Status is 'enrolled' ---
    if ($new_status === 'enrolled') {
        // Check if an initial payment for this enrollment has already been recorded in monthly_payments
        // The check for amount_due IS NULL is based on your old code logic. We'll keep it.
        $stmt_check_monthly_initial = $pdo->prepare("SELECT COUNT(*) FROM monthly_payments WHERE enrollment_id = ? AND amount_due IS NULL");
        $stmt_check_monthly_initial->execute([$enrollment_id]);

        // If no initial monthly payment record exists, create one
        if ($stmt_check_monthly_initial->fetchColumn() == 0) {
            $stmt_insert_initial_monthly = $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, verified_by_user_id, verified_at, admin_notes)
                VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");

            // For the first payment, status is 'verified', amount_due is NULL (flexible model)
            $payment_status = 'verified';
            $paid_amount = $enrollment['initial_paid_amount'];
            $bank_name = $enrollment['bank_name'];
            $branch_code = $enrollment['branch_code'];
            $slip_number = $enrollment['slip_number'];
            $payment_date = $enrollment['initial_payment_date'];
            $slip_path = $enrollment['initial_slip_path'];
            $uploaded_at = $enrollment['initial_upload_date'];
            $verified_by_user_id = $current_user_id; // Admin/Instructor who approved
            $verified_at = date('Y-m-d H:i:s');
            $admin_notes = "Initial enrollment payment, automatically verified upon course approval.";

            // Use the first day of the batch's start month as a conceptual 'month_due_date'
            // UPDATED: Using the batch's start_date now.
            $first_month_date = (new DateTime($enrollment['batch_start_date']))->format('Y-m-01');

            if (!$stmt_insert_initial_monthly->execute([
                $enrollment_id, $first_month_date, $payment_status, $paid_amount, $bank_name,
                $branch_code, $slip_number, $payment_date, $slip_path, $uploaded_at,
                $verified_by_user_id, $verified_at, $admin_notes
            ])) {
                throw new Exception("Failed to record initial payment as first monthly payment.");
            }

            // --- 5. Delete the original payment record from the 'payments' table ---
            // It's now migrated to the 'monthly_payments' table as the first payment record.
            $stmt_delete_initial_payment = $pdo->prepare("DELETE FROM payments WHERE id = ?");
            if (!$stmt_delete_initial_payment->execute([$enrollment['initial_payment_id']])) {
                // Log this, but don't halt the whole transaction if the payment table entry
                // is already gone (e.g. from a prior failed attempt)
                error_log("Failed to delete initial payment record (ID: {$enrollment['initial_payment_id']}) after migration. It might have been deleted already.");
            }
        } else {
            error_log("Enrollment ID {$enrollment_id}: Initial payment already recorded as a monthly payment. Skipping re-creation.");
        }
    }

    $pdo->commit(); // Commit the transaction
    $response['success'] = true;
    $response['message'] = "Enrollment status updated to " . ucwords($new_status) . " successfully! " . ($new_status === 'enrolled' ? "Initial payment recorded." : "");

} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack(); // Rollback if something went wrong during the transaction
    }
    $response['message'] = "Server error: " . $e->getMessage();
    error_log("Update Enrollment Status API Error: " . $e->getMessage());
}

echo json_encode($response);
exit();