<?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']) && isset($_POST['auth']) && isset($_POST['img'])) {
    require 'config.php';

    // Function to sanitize input
    function sanitize_input($input) {
        return htmlspecialchars(stripslashes(trim($input)));
    }

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

    // Validate input length
    if (strlen($user_id) > 50 || strlen($auth) > 100) {
        echo json_encode(['status' => false, 'success' => 'Invalid input length.']);
        exit;
    }

    // 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;

    // Prepared statement to validate user
    $sql_user = "SELECT * FROM users WHERE user_id = ? AND auth = ?";
    $stmt = $con->prepare($sql_user);
    $stmt->bind_param("ss", $user_id, $auth);
    $stmt->execute();
    $result_user = $stmt->get_result();

    if ($result_user && $result_user->num_rows === 1) {
        // Save the image to the server
        if (file_put_contents($file_path, $data)) {
            // Update user record
            $sql_update = "UPDATE users SET passport = ? WHERE user_id = ? AND auth = ?";
            $stmt_update = $con->prepare($sql_update);
            $stmt_update->bind_param("sss", $img_url, $user_id, $auth);

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

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