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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $id = intval($_POST['id'] ?? 0);
        if ($id <= 0)
            throw new Exception("Invalid Student ID.");

        // 1. Validation Logic
        // REMOVED: 'stream_id' from logic
        $required = ['student_name', 'father_name', 'roll', 'phone', 'gender', 'class_id', 'medium_id', 'dob', 'admission_date', 'academic_year'];
        foreach ($required as $field) {
            if (empty($_POST[$field]))
                throw new Exception("Field '$field' is required.");
        }

        $phone = preg_replace('/[^0-9]/', '', $_POST['phone'] ?? '');
        if (strlen($phone) !== 10 || !preg_match('/^[6-9][0-9]{9}$/', $phone)) {
            throw new Exception("Validation Error: Please provide a valid 10-digit mobile number.");
        }

        if (strtotime($_POST['dob']) > time()) {
            throw new Exception("Date of Birth cannot be in the future.");
        }

        // Capture section_id and medium_id (Stream ID removed)
        $section_id = (!empty($_POST['section_id'])) ? intval($_POST['section_id']) : null;
        $medium_id = (!empty($_POST['medium_id'])) ? intval($_POST['medium_id']) : null;

        // Begin Transaction
        $pdo->beginTransaction();

        // 2. Fetch current photo to handle deletion of old file
        $stmt = $pdo->prepare("SELECT student_photo FROM students WHERE id = ?");
        $stmt->execute([$id]);
        $current = $stmt->fetch();
        $photoFileName = $current['student_photo'] ?? null;

        // 3. Photo Upload & Auto-Crop Logic
        if (isset($_FILES['student_photo']) && $_FILES['student_photo']['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES['student_photo'];
            
            $allowedExtensions = ['jpg', 'jpeg', 'png'];
            $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            if (!in_array($fileExtension, $allowedExtensions))
                throw new Exception("Invalid file type. Only JPG, JPEG, and PNG are allowed.");

            $uploadDir = "../../uploads/students/";
            if (!is_dir($uploadDir))
                mkdir($uploadDir, 0777, true);

            $newFileName = "STD_" . time() . "_" . uniqid() . ".jpg";
            $targetPath = $uploadDir . $newFileName;

            if (cropStudentPhoto($file['tmp_name'], $targetPath, 400, 500)) {
                if (!empty($photoFileName) && file_exists($uploadDir . $photoFileName)) {
                    unlink($uploadDir . $photoFileName);
                }
                $photoFileName = $newFileName;
            } else {
                throw new Exception("Failed to process and crop the student photo.");
            }
        }

        // 4. Update Students Table (Personal Info)
        $stmtStu = $pdo->prepare("UPDATE students SET 
            student_name = :name, father_name = :f_name, mother_name = :m_name,
            parent_phone = :phone, gender = :gender, address = :addr, 
            student_photo = :photo, dob = :dob, admission_date = :adm_date 
            WHERE id = :id");

        $stmtStu->execute([
            ":name" => $_POST['student_name'],
            ":f_name" => $_POST['father_name'],
            ":m_name" => $_POST['mother_name'] ?? '',
            ":phone" => $phone,
            ":gender" => $_POST['gender'],
            ":addr" => $_POST['address'],
            ":photo" => $photoFileName,
            ":dob" => $_POST['dob'],
            ":adm_date" => $_POST['admission_date'],
            ":id" => $id
        ]);

        // 5. Update Enrollments Table (Academic Info)
        // REMOVED: stream_id from the update query
        $stmtEnr = $pdo->prepare("UPDATE enrollments SET 
            class_id = :class_id, 
            roll_no = :roll, 
            section_id = :section,
            medium_id = :medium
            WHERE student_id = :id AND academic_year_id = :a_year");

        $stmtEnr->execute([
            ":class_id" => $_POST['class_id'],
            ":roll" => $_POST['roll'],
            ":section" => $section_id,
            ":medium" => $medium_id,
            ":id" => $id,
            ":a_year" => $_POST['academic_year']
        ]);

        $pdo->commit();
        echo json_encode(["success" => true, "message" => "Student updated successfully"]);

    } catch (Exception $e) {
        if ($pdo->inTransaction())
            $pdo->rollBack();
        echo json_encode(["success" => false, "message" => $e->getMessage()]);
    }
}
?>