<?php
// DB connection settings — update with your credentials
$host = 'localhost';
$db = 'xrgconos_register';
$user = 'xrgconos_registerjdtutoring';
$pass = 'Emmanuelg1@';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8mb4", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("DB Connection failed: " . $e->getMessage());
}

// Upload function for files
function uploadFile($fileInputName, $uploadDir = 'uploads/') {
    if (!isset($_FILES[$fileInputName]) || $_FILES[$fileInputName]['error'] !== UPLOAD_ERR_OK) {
        return null;
    }

    $fileTmpPath = $_FILES[$fileInputName]['tmp_name'];
    $fileName = basename($_FILES[$fileInputName]['name']);
    $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    
    $allowedExtensions = ['pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx'];
    if (!in_array($fileExtension, $allowedExtensions)) {
        die("Error: Invalid file type for $fileInputName.");
    }

    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $newFileName = uniqid() . '.' . $fileExtension;
    $destPath = $uploadDir . $newFileName;

    if (move_uploaded_file($fileTmpPath, $destPath)) {
        return $newFileName;
    } else {
        die("Error uploading file for $fileInputName.");
    }
}

function getPost($key) {
    return isset($_POST[$key]) ? trim($_POST[$key]) : null;
}

// Generate unique registration code
function generateRegistrationCode($pdo) {
    $prefix = 'REG' . date('Ymd') . '-';
    do {
        $code = $prefix . str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM students WHERE registration_code = ?");
        $stmt->execute([$code]);
        $count = $stmt->fetchColumn();
    } while ($count > 0);
    return $code;
}

// Retrieve referral source, prefer 'referralOther' if 'Other' selected
function getReferralSource() {
    $referral = isset($_POST['referralSource']) ? trim($_POST['referralSource']) : '';
    $referralOther = isset($_POST['referralOther']) ? trim($_POST['referralOther']) : '';

    if ($referral === 'Other' && $referralOther !== '') {
        return $referralOther;
    }
    return $referral;
}

$latestResultsFile = uploadFile('latestResults');
$idDocumentFile = uploadFile('idDocument');
$subjectsArray = isset($_POST['subjects']) ? $_POST['subjects'] : [];
$subjectsString = implode(',', array_map('trim', $subjectsArray));
$registrationCode = generateRegistrationCode($pdo);

$stmt = $pdo->prepare("
    INSERT INTO students 
    (registration_code, student_name, student_surname, gender, dob, phone, email, physical_address, home_language, latest_results, id_document,
     program, grade, curriculum, learning_mode, subjects, school_name,
     nextkin1_name, nextkin1_surname, nextkin1_personal_contact, nextkin1_work_contact, nextkin1_email, nextkin1_physical_address,
     nextkin1_relation_to_student, nextkin1_occupation, nextkin1_home_language,
     nextkin2_name, nextkin2_surname, nextkin2_personal_contact, nextkin2_work_contact, nextkin2_email, nextkin2_physical_address,
     nextkin2_relation_to_student, nextkin2_occupation, nextkin2_home_language,
     referral_source,
     additional_notes)
    VALUES 
    (:registration_code, :student_name, :student_surname, :gender, :dob, :phone, :email, :physical_address, :home_language, :latest_results, :id_document,
     :program, :grade, :curriculum, :learning_mode, :subjects, :school_name,
     :nextkin1_name, :nextkin1_surname, :nextkin1_personal_contact, :nextkin1_work_contact, :nextkin1_email, :nextkin1_physical_address,
     :nextkin1_relation_to_student, :nextkin1_occupation, :nextkin1_home_language,
     :nextkin2_name, :nextkin2_surname, :nextkin2_personal_contact, :nextkin2_work_contact, :nextkin2_email, :nextkin2_physical_address,
     :nextkin2_relation_to_student, :nextkin2_occupation, :nextkin2_home_language,
     :referral_source,
     :additional_notes)
");

try {
    $stmt->execute([
        ':registration_code' => $registrationCode,
        ':student_name' => getPost('studentName'),
        ':student_surname' => getPost('studentSurname'),
        ':gender' => getPost('gender'),
        ':dob' => getPost('dob'),
        ':phone' => getPost('phone'),
        ':email' => getPost('email'),
        ':physical_address' => getPost('physicalAddress'),
        ':home_language' => getPost('homeLanguage'),
        ':latest_results' => $latestResultsFile,
        ':id_document' => $idDocumentFile,
        ':program' => getPost('program'),
        ':grade' => getPost('grade'),
        ':curriculum' => getPost('curriculum'),
        ':learning_mode' => getPost('learningMode'),
        ':subjects' => $subjectsString,
        ':school_name' => getPost('schoolName'),

        ':nextkin1_name' => getPost('nextKin1Name'),
        ':nextkin1_surname' => getPost('nextKin1Surname'),
        ':nextkin1_personal_contact' => getPost('nextKin1PersonalContact'),
        ':nextkin1_work_contact' => getPost('nextKin1WorkContact'),
        ':nextkin1_email' => getPost('nextKin1Email'),
        ':nextkin1_physical_address' => getPost('nextKin1PhysicalAddress'),
        ':nextkin1_relation_to_student' => getPost('nextKin1RelationToStudent'),
        ':nextkin1_occupation' => getPost('nextKin1Occupation'),
        ':nextkin1_home_language' => getPost('nextKin1HomeLanguage'),

        ':nextkin2_name' => getPost('nextKin2Name'),
        ':nextkin2_surname' => getPost('nextKin2Surname'),
        ':nextkin2_personal_contact' => getPost('nextKin2PersonalContact'),
        ':nextkin2_work_contact' => getPost('nextKin2WorkContact'),
        ':nextkin2_email' => getPost('nextKin2Email'),
        ':nextkin2_physical_address' => getPost('nextKin2PhysicalAddress'),
        ':nextkin2_relation_to_student' => getPost('nextKin2RelationToStudent'),
        ':nextkin2_occupation' => getPost('nextKin2Occupation'),
        ':nextkin2_home_language' => getPost('nextKin2HomeLanguage'),

        ':referral_source' => getReferralSource(),

        ':additional_notes' => getPost('additionalNotes'),
    ]);

    echo "<h2>Registration Successful!</h2>";
    echo "<p>Your registration code is: <strong>" . htmlspecialchars($registrationCode) . "</strong></p>";
    echo "<p>Please save this code for your records.</p>";
    echo "<p><a href='student-registration.html'>Register another student</a></p>";
} catch (PDOException $e) {
    echo "Error saving registration: " . $e->getMessage();
}
