<?php include "../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();
session_start();

$today = new DateTime();
$today->modify('+2 hours');
$current_date = $today->format('Y-m-d' . ' ' . 'H:i');

// Make sure user is logged in and file is uploaded
if (!isset($_SESSION['user_id'])) {
    echo "User not logged in.";
    exit;
}

if (!isset($_FILES['file'])) {
    echo "No file uploaded.";
    exit;
}

try {

    $user_id = $_SESSION['user_id'];

    $type = $_POST['type'];

    $ajax_type = $_POST['ajax_type'];

    if ($type == "supervisor_signature") {

        $target_file = "../capture/signatures/supervisor{$user_id}-training-{$current_date}.png";

        // Optional: Validate the file type
        if ($_FILES["file"]["type"] !== "image/png") {
            echo "Invalid file type. Only PNG allowed.";
            exit;
        }

        // Move the uploaded file
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
            echo "OK";
        } else {
            echo "Failed to move uploaded file.";
        }
    }

    if ($type == "technician_signature") {

        $visitor_no = $_POST['visitor_no'];
        $target_file = "../capture/signatures/visitor{$visitor_no}-training-{$current_date}.png";

        if (file_exists($target_file)) {
            $visitor_no++;
            $target_file = "../capture/signatures/visitor{$visitor_no}-training.png";
        } else {
            $target_file = "../capture/signatures/visitor{$visitor_no}-training.png";
        }

        // Optional: Validate the file type
        if ($_FILES["file"]["type"] !== "image/png") {
            echo "Invalid file type. Only PNG allowed.";
            exit;
        }

        // Move the uploaded file
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
            echo "OK";
        } else {
            echo "Failed to move uploaded file.";
        }
    }

    if ($ajax_type == "file_upload") {
        $target_dir = $_POST["file_save_path"];
        $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
        $uploadOk = 1;
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        // Check if image file is a actual image or fake image
        if (isset($_POST["submit"])) {
            $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
            if ($check !== false) {
                echo "File is an image - " . $check["mime"] . ".";
                $uploadOk = 1;
            } else {
                echo "File is not an image.";
                $uploadOk = 0;
            }
        }
    }

    return 1;

} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}