<?php include "../../root.class.php";
$db = new db_safeguard();

if (isset($_POST['type']) && $_POST['type'] === "file_upload") {

    try {
        $file_save_path = $_POST['file_save_path'];

        $target_dir = $file_save_path;

        $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "OK";
        } else {
            echo "Upload failed";
        }

    } catch (Exception $e) {
        echo $e->getMessage();
    }
}

if (isset($_POST['ajax_type']) && $_POST['ajax_type'] === "lead_payment_slip") {

    $section_name = $_POST['section_name'];
    $jobcard_no = $_POST['jobcard_no'];

    try {
        if (!isset($_FILES['file'])) {
            echo "No file received";
            exit;
        } else if(!isset($jobcard_no)) {
            echo "Jobcard number missing";
            exit;
        }

        $file_save_path = $_POST['file_save_path'];

        // Ensure directory exists
        if (!is_dir($file_save_path)) {
            mkdir($file_save_path, 0777, true);
        }

        $file_name = $section_name . "_image_jc_" . $jobcard_no . "_" . basename($_FILES["file"]["name"]);

        $target_file = $file_save_path . $file_name;

        if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
            echo "OK | $file_name ";
        } else {
            echo "Upload failed: " . $_FILES["file"]["tmp_name"] . " => " . $target_file;
        }

    } catch (Exception $e) {
        echo $e->getMessage();
    }
}