<?php include "../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();
session_start();

$current_date_time = date("Y-m-d");

// 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;
}

//count the number of files at /sorting/signatures
$target_dir = "../sorting/signatures/";
$files = glob($target_dir . "*");
$files = array_filter($files, 'is_file');

$count = count($files);

// echo "Total files: " . $count;

try {
    $user_id = $_SESSION['user_id'];
    $type = $_POST['type'];

    if ($type == "sorting_signature") {
        // Define the target filename
        $target_file = $target_dir . "../sorting/signatures/sorting_jc_signature{$count}-{$user_id}-signature.png";
    }

    if ($type == "production_supervisor_signature") {
        // Define the target filename
        $target_file = $target_dir . "../sorting/signatures/production_supervisor_signature-j-{$user_id}-signature.png";
    }

    if ($type == "quality_control_signature") {
        // Define the target filename
        $target_file = $target_dir . "../sorting/signatures/quality_control_signature-j-{$user_id}-signature.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)) {
        return "OK";
    } else {
        echo "Failed to move uploaded file.";
    }

    return 1;

} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}