<?
session_start();

include "../classes/db.class.php";

// var_dump($_POST);

$db = new db();

$farming_action = $_POST['farming_action'];
$farming_type = $_POST['farming_type'];
$farm_id = $_POST['farm_id'];
$action_date = $_POST['action_date'];
$cluster_ids = strtoupper($_POST['cluster']);
$rating = $_POST['rating'];
$instructions = strtoupper($_POST['instruction']);
$user_id = $_POST['user_id'];
$completed = '';
$coms = '';
$date_created = date('Y-m-d H:i', strtotime("+ 2 Hours"));
$date_completed = '';
$images = $_POST['image_index']; 
$errand_img = $_POST['errand_img'];

$res = $db->Update('management', ['farm_id', 'farming_type_id', 'farming_action_id', 'cluster_ids', 'action_date', 'date_created', 'date_completed', 'completed', 'user_id_created', 'user_id_assigned', 'coms', 'instructions', 'rating'], [$farm_id, $farming_type, $farming_action, $cluster_ids, $action_date, $date_created, $date_completed, $completed, $_SESSION['user_id'], $user_id, $coms, $instructions, $rating], "record_id = {$_POST['errand_id']}");

$index = 0;
$file_names = "";
if ($res) {
    while ($index <= $images - 1) {
        // echo $_FILES["image_$index"]['tmp_name'];
        if (!empty($_FILES["image_$index"]['tmp_name'])) {
            $target_dir = "../taskimages/";
            $target_file = $target_dir . basename($_FILES["image_$index"]["name"]);
            $uploadOk = 1;
            $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
            $check = getimagesize($_FILES["image_$index"]["tmp_name"]);
            if ($check !== false) {
                $uploadOk = 1;
            } else {
                $uploadOk = 0;
            }
            if ($uploadOk == 0) {
                echo 0;
            } else {
                $file_names .= basename($_FILES["image_$index"]["name"]) . ",";

                if (move_uploaded_file($_FILES["image_$index"]["tmp_name"], $target_file)) {
                    echo 1;
                } else {
                    echo 0;
                }
            }
        } else {
            echo 1;
        }
        $index++;
    }

    $update_images = $errand_img . $file_names;

    $db->update("management", ["image"], [$update_images] , "record_id = {$_POST['errand_id']}", false);
    

} else {

    echo "Update('management', ['farm_id', 'farming_type', 'farming_action', 'cluster_ids', 'action_date', 'date_created', 'date_completed', 'completed', 'user_id_created', 'user_id_assigned', 'coms', 'instructions', 'rating'], [$farm_id, $farming_type, $farming_action, $cluster_ids, $action_date, $date_created, $date_completed, $completed, {$_SESSION['user_id']}, $user_id, $coms, $instructions, $rating]";

    // echo 'Werk nie my seun'; website cover photo (19).jpg,website cover photo (21).jpg,

}