<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/aaaerror.txt'); // Ensure correct path

// Function to log errors
function logError($message) {
    $logFile = __DIR__ . '/aaaerror.txt';
    $timestamp = date("Y-m-d H:i:s");
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}

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

// Database connection
$servername = "localhost";
$username = "appshett_ibill";
$password = "appshett_ibill";
$dbname = "appshett_ibill";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    logError("Database connection failed: " . $conn->connect_error);
    die(json_encode(["success" => false, "message" => "Database connection failed"]));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check if all required fields are set
    $requiredFields = ['enrollmentType', 'firstName', 'lastName', 'dob', 'stateOrigin', 'lgaOrigin', 'areaResidence', 'phoneNumber', 'gender', 'middle', 'height'];
    foreach ($requiredFields as $field) {
        if (!isset($_POST[$field]) || empty(trim($_POST[$field]))) {
            logError("Missing required field: $field");
            echo json_encode(["success" => false, "message" => "Missing required field: $field"]);
            exit;
        }
    }

    // Sanitize input data
    $enrollmentType = htmlspecialchars(trim($_POST['enrollmentType']));
    $firstName = htmlspecialchars(trim($_POST['firstName']));
    $middleName = htmlspecialchars(trim($_POST['middle']));
    $lastName = htmlspecialchars(trim($_POST['lastName']));
    $dob = htmlspecialchars(trim($_POST['dob']));
    $stateOrigin = htmlspecialchars(trim($_POST['stateOrigin']));
    $lgaOrigin = htmlspecialchars(trim($_POST['lgaOrigin']));
    $areaResidence = htmlspecialchars(trim($_POST['areaResidence']));
    $phoneNumber = htmlspecialchars(trim($_POST['phoneNumber']));
    $gender = htmlspecialchars(trim($_POST['gender']));
    $height = htmlspecialchars(trim($_POST['height']));

    // Process image upload
    if (isset($_FILES['picture']) && $_FILES['picture']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = __DIR__ . '/uploads/'; // Absolute path to 'uploads/' inside 'ajax/'

        // Ensure the uploads directory exists and is writable
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true); // Create uploads directory if not exists
        }

        // Generate a unique filename to prevent overwriting
        $fileTmpPath = $_FILES['picture']['tmp_name'];
        $fileName = time() . '_' . basename($_FILES['picture']['name']);
        $fileDest = $uploadDir . $fileName;

        // Move the uploaded file
        if (!move_uploaded_file($fileTmpPath, $fileDest)) {
            logError("Error uploading picture");
            echo json_encode(["success" => false, "message" => "Error uploading picture"]);
            exit;
        }

        // Store only the relative path in the database
        $filePath = 'uploads/' . $fileName;
    } else {
        logError("Picture is required");
        echo json_encode(["success" => false, "message" => "Picture is required"]);
        exit;
    }

    // Insert data into the database
    $stmt = $conn->prepare("INSERT INTO enrollments (enrollment_type, first_name, middle_name, last_name, dob, state_origin, lga_origin, area_residence, phone_number, gender, height, picture) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    if (!$stmt) {
        logError("Prepare statement failed: " . $conn->error);
        echo json_encode(["success" => false, "message" => "Database error"]);
        exit;
    }

    $stmt->bind_param("ssssssssssss", $enrollmentType, $firstName, $middleName, $lastName, $dob, $stateOrigin, $lgaOrigin, $areaResidence, $phoneNumber, $gender, $height, $filePath);

    if ($stmt->execute()) {
        echo json_encode(["success" => true, "message" => "Enrollment successful"]);
    } else {
        logError("Database Insert Error: " . $stmt->error);
        echo json_encode(["success" => false, "message" => "Error: " . $stmt->error]);
    }

    $stmt->close();
    $conn->close();
} else {
    echo json_encode(["success" => false, "message" => "Invalid request method"]);
}
?>
