<?php
// student_registration_step1_action.php
session_start();
require_once 'db.php';
header('Content-Type: application/json');

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

// Collect and sanitize input
$fullName        = trim($_POST['fullName'] ?? '');
$admissionNumber = trim($_POST['admissionNumber'] ?? '');
$dob             = $_POST['dob'] ?? '';
$gender          = $_POST['gender'] ?? '';
$bloodGroup      = trim($_POST['bloodGroup'] ?? '');
$religion        = $_POST['religion'] ?? '';
$category        = $_POST['category'] ?? '';
$aadharNumber    = trim($_POST['aadharNumber'] ?? '');
$school          = $_POST['school'] ?? '';
$classGrade      = $_POST['classGrade'] ?? '';
$section         = trim($_POST['section'] ?? '');
$stationary      = trim($_POST['stationary'] ?? '');

// New fields
$preferredLanguage = $_POST['preferredLanguage'] ?? '';
$hobbies           = trim($_POST['hobbies'] ?? '');
$achievementType   = $_POST['achievementType'] ?? '';
$siblings          = $_POST['siblings'] ?? '';
$siblingDetails    = trim($_POST['siblingDetails'] ?? '');
$reference    = trim($_POST['reference'] ?? '');

// Validation
if ($fullName === '' || $admissionNumber === '' || $dob === '' || $gender === '' || $category === '' || $school === '' || $classGrade === '') {
    echo json_encode(['status' => 'error', 'message' => 'Required fields are missing.']);
    exit;
}

// Generate unique registration number
$uniqueReg = 'REG' . time() . rand(100, 999);

// Insert into students table
$stmt = $conn->prepare("INSERT INTO students 
    (unique_reg_number, full_name, admission_number, dob, gender, blood_group, religion, category, 
     aadhar_number, school, class_grade, section, stationary, 
     preferred_language, hobbies, achievement_type, siblings, sibling_details, reference) 
    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

if (!$stmt) {
    echo json_encode(['status' => 'error', 'message' => $conn->error]);
    exit;
}

$stmt->bind_param(
    "sssssssssssssssssss",
    $uniqueReg,
    $fullName,
    $admissionNumber,
    $dob,
    $gender,
    $bloodGroup,
    $religion,
    $category,
    $aadharNumber,
    $school,
    $classGrade,
    $section,
    $stationary,
    $preferredLanguage,
    $hobbies,
    $achievementType,
    $siblings,
    $siblingDetails,
    $reference
);

if ($stmt->execute()) {
    echo json_encode(['status' => 'success', 'uniqueId' => $uniqueReg]);
} else {
    echo json_encode(['status' => 'error', 'message' => $stmt->error]);
}

$stmt->close();
$conn->close();
