<?php
session_start();

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json; charset=utf-8');

if (isset($_POST['user_id'], $_POST['auth'], $_POST['student_id'], $_POST['img'])) {
    require 'config.php';

    // Sanitize input
    function sanitize_input($input) {
        return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
    }

    $user_id = sanitize_input($_POST['user_id']);
    $auth = sanitize_input($_POST['auth']);
    $student_id = sanitize_input($_POST['student_id']);
    $img = $_POST['img']; // Base64-encoded image

    // Validate base64 image format
    if (!preg_match('/^data:image\/(png|jpeg);base64,/', $img)) {
        echo json_encode(['status' => false, 'success' => 'Invalid image format.']);
        exit;
    }

    // Remove metadata and decode the image
    $img = preg_replace('/^data:image\/\w+;base64,/', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);

    if (!$data) {
        echo json_encode(['status' => false, 'success' => 'Invalid image data.']);
        exit;
    }

    // Generate unique file name
    $file_name = $user_id . '_' . time() . '.png';
    $file_path = "../passport/$file_name";
    $img_url = $p_url . "/passport/" . $file_name;

    // Check if user exists
    $sql_user = "SELECT * FROM users WHERE user_id = ? AND auth = ?";
    $stmt_user = $con->prepare($sql_user);
    $stmt_user->bind_param("ss", $user_id, $auth);
    $stmt_user->execute();
    $result_user = $stmt_user->get_result();

    if ($result_user && $result_user->num_rows === 1) {
        // Check if student exists
        $sql_student = "SELECT * FROM students WHERE user_id = ? AND student_id = ?";
        $stmt_student = $con->prepare($sql_student);
        $stmt_student->bind_param("ss", $user_id, $student_id);
        $stmt_student->execute();
        $result_student = $stmt_student->get_result();

        if ($result_student && $result_student->num_rows === 1) {
            // Save the image
            if (file_put_contents($file_path, $data)) {
                // Update student record
                $sql_update = "UPDATE students SET passport = ? WHERE user_id = ? AND student_id = ?";
                $stmt_update = $con->prepare($sql_update);
                $stmt_update->bind_param("sss", $img_url, $user_id, $student_id);

                if ($stmt_update->execute()) {
                    echo json_encode(['status' => true, 'success' => 'Image uploaded and student record updated successfully.']);
                } else {
                    echo json_encode(['status' => false, 'success' => 'Failed to update the student record.']);
                }
            } else {
                echo json_encode(['status' => false, 'success' => 'Failed to save the image file.']);
            }
        } else {
            echo json_encode(['status' => false, 'success' => 'Student record does not exist.']);
        }
    } else {
        echo json_encode(['status' => false, 'success' => 'User does not exist or authentication failed.']);
    }

    // Close connections
    $stmt_user->close();
    $stmt_student->close();
    $con->close();
} else {
    echo json_encode(['status' => false, 'success' => 'Invalid request.']);
}
?>
