<?php

error_reporting(0);
ini_set('display_errors', 0);

session_start();

include "../../../root.class.php";
$db = new db_safeguard();

if (!empty($_POST['image'])) {
    $folderPath = __DIR__ . "/install_images/";
    $jobcard_no = $_POST['jobcard_no'];
    $user_id = $_SESSION['user_id'];
    $section_name = $_POST['section_name'];
    $description = $_POST['description'] ?? '';
    $record_id = $_POST['record_id'] ?? '';
    $date_time = date("Y-m-d H:i:s");

    try {
        $image_parts = explode(";base64,", $_POST['image']);
        $image_base64 = base64_decode($image_parts[1]);
        $fileName = $section_name . '_image_' . uniqid() . '_' . $user_id . '_jc_' . $jobcard_no . '.png';
        $file = $folderPath . $fileName;

        if (!is_dir($folderPath)) {
            mkdir($folderPath, 0755, true);
        }

        $result = @file_put_contents($file, $image_base64);

        if ($result === false) {
            echo '0';
            exit;
        }

        $db->query("notes", "INSERT INTO notes (jobcard_id, reason, note, image, date_time) 
            VALUES ('{$jobcard_no}', 'INSTALL IMAGE', '{$description}', '{$fileName}', '{$date_time}')");

        echo $fileName;

    } catch (Exception $e) {
        echo '0';
        exit;
    }

} else {
    echo "0";
}
?>