<?php
include "../../../root.class.php";
$db = new db_safeguard();
session_start();

if (!empty($_POST['image'])) {

    // ✅ Build the absolute path server-side — never trust posted folder_path
    $folderPath       = $_SERVER['DOCUMENT_ROOT'] . '/app/jobcards/pump/install_images/';
    $jobcard_no       = $_POST['jobcard_no'];
    $user_id          = $_SESSION['user_id'];
    $section_name     = $_POST['section_name'];
    $description      = $_POST['description'] ?? '';
    $current_date_time = date("Y-m-d H:i", strtotime("+2 Hours"));

    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;

        // ✅ Ensure the directory exists before writing
        if (!is_dir($folderPath)) {
            mkdir($folderPath, 0755, true);
        }

        $result = file_put_contents($file, $image_base64);

        if ($result === false) {
            echo '0'; // ✅ Return error code, not the server path
            exit;
        }

        $db->query("notes", "INSERT INTO notes (jobcard_id, reason, note, image, date_time)
            VALUES ('{$jobcard_no}', 'INSTALL IMAGE', '{$description}', '{$fileName}', '{$current_date_time}')");

        echo $fileName . ' _ ' . $description;

    } catch (Exception $e) {
        echo '0';
        exit;
    }

} else {
    echo '0';
}
?>