<?php
// api/submit_payment.php
// Handles the submission of payment details and slip uploads for an enrollment.

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

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') {
    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'];

// 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'] ?? '');
$payment_amount = filter_var($_POST['payment_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) || $payment_amount === false || $payment_amount <= 0 || !$payment_slip_file || $payment_slip_file['error'] !== UPLOAD_ERR_OK) {
    $response['message'] = "Missing or invalid payment details or file upload error.";
    if ($payment_slip_file && $payment_slip_file['error'] !== UPLOAD_ERR_OK) {
        $response['message'] .= " File upload error code: " . $payment_slip_file['error'];
    }
    echo json_encode($response);
    exit();
}

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

    if (!$enrollment) {
        $response['message'] = "Enrollment record not found or you don't have permission.";
        echo json_encode($response);
        exit();
    }

    if ($enrollment['status'] !== 'pending') {
        $response['message'] = "Payment cannot be submitted for an enrollment with status: " . htmlspecialchars($enrollment['status']) . ".";
        echo json_encode($response);
        exit();
    }

    // --- 3. Handle File Upload ---
    $upload_dir = '../public/uploads/slips/'; // Make sure this directory exists and is writable!
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true); // Create directory if it doesn't exist
    }

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

    if (!move_uploaded_file($payment_slip_file['tmp_name'], $target_file)) {
        $response['message'] = "Failed to upload payment slip. Please check file permissions.";
        echo json_encode($response);
        exit();
    }

    // --- 4. Insert Payment Details into `payments` table ---
    $pdo->beginTransaction(); // Start a transaction for atomicity

    $stmt = $pdo->prepare("INSERT INTO payments (enrollment_id, bank_name, branch_code, slip_number, payment_date, payment_amount, slip_path) VALUES (?, ?, ?, ?, ?, ?, ?)");
    if (!$stmt->execute([$enrollment_id, $bank_name, $branch_code, $slip_number, $payment_date, $payment_amount, $relative_slip_path])) {
        throw new Exception("Failed to save payment details.");
    }

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

    $pdo->commit(); // Commit the transaction
    $response['success'] = true;
    $response['message'] = "Payment details submitted successfully! Your enrollment is now pending verification.";

} catch (Exception $e) {
    // Catch any exceptions (including PDO exceptions thrown above)
    if ($pdo->inTransaction()) {
        $pdo->rollBack(); // Rollback if something went wrong during transaction
    }
    // Delete the uploaded file if database insertion failed
    if (isset($target_file) && file_exists($target_file)) {
        unlink($target_file);
    }
    $response['message'] = "Server error: " . $e->getMessage();
    error_log("Submit Payment API Error: " . $e->getMessage());
}

echo json_encode($response);
exit();
