<?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 'db/config.php';

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

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

    // Validate user input
    if (empty($user_id)  || empty($auth)) {
        echo json_encode(['status' => false, 'success' => 'Missing Parameters']);
        exit;
    }

    $auth = mysqli_real_escape_string($con, $auth);
    $user_id = mysqli_real_escape_string($con, $user_id);

    // 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 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 = "../profiles/$file_name";
    $img_url = $p_url . "/profiles/" . $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
            // Save the image to the file system
            if (file_put_contents($file_path, $data)) {
                // Update user and student records
               
               $stat = "Completed";
                $sql_update_student = "UPDATE users SET img7 = ? WHERE user_id = ? AND auth = ?";
$stmt_update_student = $con->prepare($sql_update_student);
$stmt_update_student->bind_param("sss", $img_url, $user_id, $auth);

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

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