<?php include "../../root.class.php";
$db = new db_safeguard();

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();
    }
}

if (isset($_POST['ajax_type']) && $_POST['ajax_type'] === "note_section") {

    $section_name = $_POST['section_name'] ?? 'notes';
    $jobcard_no   = $_POST['jobcard_no']   ?? '';

    if (empty($jobcard_no)) {
        echo "Jobcard number missing";
        exit;
    }

    if (!isset($_FILES['file'])) {
        echo "No file received";
        exit;
    }

    // FIX: validate file type — only allow images and PDFs
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
    $file_mime     = mime_content_type($_FILES['file']['tmp_name']);
    if (!in_array($file_mime, $allowed_types)) {
        echo "Invalid file type. Only JPG, PNG, GIF and PDF are allowed.";
        exit;
    }

    // FIX: enforce a size limit (e.g. 5MB)
    // $max_size = 5 * 1024 * 1024;
    // if ($_FILES['file']['size'] > $max_size) {
    //     echo "File too large. Maximum size is 5MB.";
    //     exit;
    // }

    try {
        $file_save_path = $_POST['file_save_path'];

        if (!is_dir($file_save_path)) {
            mkdir($file_save_path, 0755, 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 {
            error_log("Upload failed: " . $_FILES["file"]["tmp_name"] . " => " . $target_file);
            echo "Upload failed";
        }

    } catch (Exception $e) {
        error_log("Upload error: " . $e->getMessage());
        echo "Upload error";
    }
}