<?php

session_start();
if (!empty($_POST['image'])) {
    $jobcard_no = $_POST['jobcard_no'];
    $user_id = $_SESSION['user_id'];
    $section_name = $_POST['section_name'];

    // Use real server path, ignore posted folder_path
    $folderPath = __DIR__ . '/' . $section_name . '/';

    try {
        $image_parts = explode(";base64,", $_POST['image']);
        $image_type_aux = explode("image/", $image_parts[0]);
        $image_type = $image_type_aux[1];
        $image_base64 = base64_decode($image_parts[1]);
        $fileName = $section_name . '_image_' . uniqid() . '_' . $user_id . '_jc_' . $jobcard_no . '.png';

        $file = $folderPath . $fileName;

        // Create folder if it doesn't exist
        if (!is_dir($folderPath)) {
            mkdir($folderPath, 0755, true);
        }

        file_put_contents($file, $image_base64);

        echo $fileName;
    } catch (Exception $e) {
        echo $e->getMessage();
    }

} else {
    echo "0";
}