<?
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 = strtoupper($_POST['cluster']);
$rating = $_POST['rating'];
$instructions = strtoupper($_POST['instruction']);
$user_id = $_POST['user_id'];
$date_created = date('Y-m-d H:i', strtotime("+ 2 Hours"));
$completed = '';
$date_completed = '';
$coms = '';
$images = $_POST['image_index']; 

// echo "INSERT INTO `management`(`farm_id`, `farming_type_id`, `farming_action_id`, `cluster_ids`, `date_created`, `action_date`, `date_completed`, `completed`, `user_id_created`, `user_id_assigned`, `coms`, `instructions`, `rating`) VALUES ('$farm_id','$farming_type','$farming_action','$cluster','$date_created','$action_date','$date_completed','$completed','{$_SESSION[user_id]}','$user_id','$coms','$instructions','$rating')";

$res = $db->insert("INSERT INTO `management`(`farm_id`, `farming_type_id`, `farming_action_id`, `cluster_ids`, `date_created`, `action_date`, `date_completed`, `completed`, `user_id_created`, `user_id_assigned`, `coms`, `instructions`, `rating`,`image`) VALUES ('$farm_id','$farming_type','$farming_action','$cluster','$date_created','$action_date','$date_completed','$completed','{$_SESSION['user_id']}','$user_id','$coms','$instructions','$rating','$image')");


$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 = $file_names;

    $db->update("management", ["image"], [$update_images] , "record_id = {$res}", false);
} else {
    echo 0;
}