<?php
header("Content-Type: application/json");
require("../../includes/config.php");
// Include the Image Helper for auto-cropping
require("../../includes/image_helper.php");

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(["status" => false, "msg" => "Invalid request method"]);
        exit;
    }

    if (empty($_POST)) {
        echo json_encode(["status" => false, "msg" => "Form data is empty"]);
        exit;
    }

    /* =========================
        REQUIRED FIELDS CHECK
    ========================== */
    $required = ['student_name', 'father_name', 'class_id', 'medium_id', 'roll_no', 'gender', 'parent_phone', 'address', 'dob', 'admission_date'];
    $missing = [];
    foreach ($required as $field) {
        if (!isset($_POST[$field]) || trim($_POST[$field]) === '') {
            $missing[] = $field;
        }
    }

    if (!empty($missing)) {
        echo json_encode(["status" => false, "msg" => "Missing fields: " . implode(", ", $missing)]);
        exit;
    }

    $dob = $_POST['dob'];
    if (strtotime($dob) > time()) {
        echo json_encode(["status" => false, "msg" => "Date of birth cannot be in the future"]);
        exit;
    }

    /* =========================
        CLASS & YEAR VALIDATION
    ========================== */
    $class_id = intval($_POST['class_id']);
    $classCheck = $pdo->prepare("SELECT id FROM classes WHERE id = :id");
    $classCheck->execute([":id" => $class_id]);
    if ($classCheck->rowCount() === 0) {
        echo json_encode(["status" => false, "msg" => "Selected class does not exist"]);
        exit;
    }

    /* =========================
        MEDIUM VALIDATION
    ========================== */
    $medium_id = intval($_POST['medium_id']);
    $mediumCheck = $pdo->prepare("SELECT id FROM mediums WHERE id = :id");
    $mediumCheck->execute([":id" => $medium_id]);
    if ($mediumCheck->rowCount() === 0) {
        echo json_encode(["status" => false, "msg" => "Selected instruction medium does not exist"]);
        exit;
    }

    if (!defined('APP_YEAR_ID') || APP_YEAR_ID == 0) {
        echo json_encode(["status" => false, "msg" => "No active academic year found."]);
        exit;
    }

    /* =========================
        ROLL NUMBER VALIDATION
    ========================== */
    $roll_no = intval($_POST['roll_no']);
    $section_id = (!empty($_POST['section_id'])) ? intval($_POST['section_id']) : null;
    
    // REMOVED: stream_id capture

    $check = $pdo->prepare("SELECT id FROM enrollments WHERE class_id = :class_id AND roll_no = :roll_no AND academic_year_id = :year_id");
    $check->execute([
        ":class_id" => $class_id,
        ":roll_no" => $roll_no,
        ":year_id" => APP_YEAR_ID
    ]);

    if ($check->rowCount() > 0) {
        echo json_encode(["status" => false, "msg" => "Roll number already exists in this class for the current session"]);
        exit;
    }

    /* ========================= 
    PHONE VALIDATION
      ========================== */
    $phone = preg_replace('/[\s\-()]/', '', trim($_POST['parent_phone']));

    if (!preg_match('/^(\+91\d{10}|\d{10})$/', $phone)) {
        echo json_encode([
            "status" => false,
            "msg" => "Invalid phone number! Please enter 10 digits or +91 followed by 10 digits."
        ]);
        exit;
    }

    $photoFileName = null;
    if (isset($_FILES['student_photo']) && $_FILES['student_photo']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = "../../uploads/students/";
        if (!is_dir($uploadDir))
            mkdir($uploadDir, 0777, true);

        $newFileName = "STD_" . time() . "_" . rand(100, 999) . ".jpg";
        $targetPath = $uploadDir . $newFileName;

        if (cropStudentPhoto($_FILES['student_photo']['tmp_name'], $targetPath, 400, 500)) {
            $photoFileName = $newFileName; 
        } else {
            throw new Exception("Failed to process student photo crop.");
        }
    }

    /* =========================
        DATABASE TRANSACTION
    ========================== */
    $pdo->beginTransaction();

    // 1. Insert into students table
    $sql = "INSERT INTO students
        (student_name, father_name, mother_name, gender, parent_phone, address, student_photo, dob, admission_date)
        VALUES
        (:student_name, :father_name, :mother_name, :gender, :parent_phone, :address, :student_photo, :dob, :admission_date)";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ":student_name" => trim($_POST['student_name']),
        ":father_name" => trim($_POST['father_name']),
        ":mother_name" => trim($_POST['mother_name'] ?? ''),
        ":gender" => trim($_POST['gender']),
        ":parent_phone" => $phone,
        ":address" => trim($_POST['address'] ?? ''),
        ":student_photo" => $photoFileName,
        ":dob" => $dob,
        ":admission_date" => $_POST['admission_date']
    ]);

    $student_id = $pdo->lastInsertId();

    // 2. Insert into enrollments table
    // REMOVED: stream_id column and placeholder
    $enrollSql = "INSERT INTO enrollments (student_id, class_id, section_id, medium_id, academic_year_id, roll_no) 
                  VALUES (:student_id, :class_id, :section_id, :medium_id, :year_id, :roll_no)";

    $enrollStmt = $pdo->prepare($enrollSql);
    
    $enrollStmt->execute([
        ":student_id" => $student_id,
        ":class_id" => $class_id,
        ":section_id" => $section_id, 
        ":medium_id" => $medium_id,
        ":year_id" => APP_YEAR_ID,
        ":roll_no" => $roll_no
    ]);

    $pdo->commit();

    echo json_encode([
        "status" => true,
        "msg" => "Student registered and enrolled successfully"
    ]);

} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    echo json_encode([
        "status" => false,
        "msg" => "Error: " . $e->getMessage()
    ]);
}
?>