<?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'])) {
    require 'config.php';

    // Sanitize input
    function check_input($par) {
        return htmlspecialchars(stripslashes(trim($par)));
    }

    $auth = check_input($_POST['auth']);
    $user_id = check_input($_POST['user_id']);

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

    // Check if the user exists
    $sql_user = "SELECT * FROM users WHERE user_id = '$user_id' AND auth = '$auth'";
    $result_user = $con->query($sql_user);

    if ($result_user && $result_user->num_rows === 1) {
        $user_row = $result_user->fetch_assoc();
        $phone = $user_row['phone'];
        $email = $user_row['email'];
        $firstname = $user_row['firstname'];
        $lastname = $user_row['lastname'];

        // Check if the student exists
        $sql_student = "SELECT * FROM company WHERE user_id = '$user_id' AND auth = '$auth'";
        $result_student = $con->query($sql_student);

        if ($result_student && $result_student->num_rows === 1) {
            // Process the image
            $img = $_POST['img'];
            $fileX = $user_id . '.png';
            $img = str_replace('data:image/png;base64,', '', $img);
            $img = str_replace(' ', '+', $img);
            $data = base64_decode($img);
            $file = "../reg_certs/$fileX";

            if (file_put_contents($file, $data)) {
                $img_url = $p_url . "/reg_certs/" . $fileX;

                // Update user and student records
               // $sql_update_user = $con->query("UPDATE users SET id_doc = '$img_url' WHERE user_id = '$user_id' AND auth = '$auth'");
                $sql_update_student = $con->query("UPDATE company SET reg_cert = '$img_url' WHERE user_id = '$user_id' AND auth = '$auth'");

                if ($sql_update_user && $sql_update_student) {
                    $suc = "Successful";
                    $status = true;
                } else {
                    $suc = "Update failed: " . $con->error;
                    $status = false;
                }
            } else {
                $suc = "Failed to save the image file.";
                $status = false;
            }
        } else {
            $suc = "Company record does not exist.";
            $status = false;
        }
    } else {
        $suc = "User does not exist.";
        $status = false;
    }

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