<?php

session_start();
if ($_POST['section_name'] == "notes"){

    $folderPath   = $_POST['folder_path'] ?? '';
    $jobcard_no   = $_POST['jobcard_no']  ?? '';
    $section_name = $_POST['section_name'] ?? 'slip';
    $user_id      = $_SESSION['user_id']  ?? 'unknown';

    if (empty($folderPath) || empty($jobcard_no)) {
        echo "0";
        exit;
    }

    $image_parts  = explode(";base64,", $_POST['image']);
    $image_base64 = base64_decode($image_parts[1] ?? '');

    if ($image_base64 === false) {
        echo "0";
        exit;
    }

    $absoluteFolder = __DIR__ . $folderPath;

    // if (!is_dir($absoluteFolder)) {
    //     if (!mkdir($absoluteFolder, 0755, true)) {
    //         echo "0";
    //         exit;
    //     }
    // }

    $fileName = $section_name . '_image_' . uniqid() . '_' . $user_id . '_jc_' . $jobcard_no . '.png';
    $file     = $absoluteFolder . $fileName;

    $bytes = file_put_contents($file, $image_base64);

    if ($bytes === false) {
        echo "0";
        exit;
    }

    echo $fileName;

} else if (!empty($_POST['image'])) {
    $folderPath = $_POST['folder_path'];
    $jobcard_no = $_POST['jobcard_no'];
    $user_id = $_SESSION['user_id'];
    $section_name = $_POST['section_name'];

    // var_dump($_POST);

    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;

        file_put_contents($file, $image_base64);

        echo $fileName; // return file name
    } catch (Exception $e) {
        echo $e->getMessage();
    }


} else {
    echo "0";
}

?>
