<?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;
}

try { 
    $user_id = $_SESSION['user_id'];
    $record_id = $_POST['record_id'];
    $type = $_POST['type'];

    // Get jobcard number
    $get_jc_id = $db->query("jobcards", "SELECT jc_no FROM jobcards WHERE record_id = {$record_id}");
    $jobcard_data = $get_jc_id->fetch_assoc();
    $jobcard_no = $jobcard_data['jc_no'];

    if ($type == "client") {
        // Define the target filename
        $target_file = $target_dir . "../jobcards/signatures/client-jc{$jobcard_no}-{$user_id}-signature.png";
    }

    if ($type == "employee") {
        // Define the target filename
        $target_file = $target_dir . "../jobcards/signatures/employee-jc{$jobcard_no}-{$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)) {
        echo "OK";
    } else {
        echo "Failed to move uploaded file.";
    }

    return 1;

} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}