<?php
session_start();
include "../../includes/config.php";
require_once "../../includes/dbcontroller.php";
$db_handle = new DBController();
if (isset($_POST["action"])) {
    if ($_POST["action"] == "fetch") {
        $deliveryid = $_POST["delivery_id"];
        $fetch_image_query = "SELECT * FROM images where DeliveryID ='$deliveryid' ORDER BY Imageid DESC";
        $fetch_image_result_count = $db_handle->numRows($fetch_image_query);
        $output = "";
        if ($fetch_image_result_count > 0) {
            $output = '
		   <table class="table table-bordered table-striped">  
			<tr>
			 <th width="10%">ID</th>
			 <th width="40%">Image</th>
			 <th width="20%">Image Description</th>
			 <th width="20%">Other Description</th>
			 <th width="10%">Remove</th>
			</tr>
		  ';
            $fetch_image_result = $db_handle->runQuery($fetch_image_query);
            foreach ($fetch_image_result as $k => $v) {
                $output .=
                    '

				<tr>
				 <td>' .
                    $fetch_image_result[$k]["Imageid"] .
                    '</td>
				 <td>
				<a href="' .
                    $fetch_image_result[$k]["ImagePath"] .
                    '" target="_blank">
				  <img src="' .
                    $fetch_image_result[$k]["ImagePath"] .
                    '" height="150" width="150" class="img-thumbnail" />
				  </a>
				 </td>
				 <td>' .
                    $fetch_image_result[$k]["ImageDescription"] .
                    '</td>
				 <td>' .
                    $fetch_image_result[$k]["OtherDescription"] .
                    '</td>
				 <td><button type="button" name="delete" class="btn btn-danger bt-xs delete" id="' .
                    $fetch_image_result[$k]["Imageid"] .
                    '">Remove</button></td>
				</tr>
			   ';
            }
            $output .= "</table>";
        }
        echo $output;
    }

    if ($_POST["action"] == "insert") {
        $deliveryid = $_POST["delid"];
        $imagedescription = $_POST["imgdesc"];
        $img_other_desc = $_POST["img_other_desc"];
        if ($_FILES["image"]["name"]) {
            $year = date("Y");
            $month = date("m");
            $filename_year = "../../uploads/Delivery/" . $year;
            $filename_month = "../../uploads/Delivery/" . $year . "/" . $month;
            $relativefilename_month =
                $website_url . "/uploads/Delivery/" . $year . "/" . $month;
            if (!file_exists($filename_year)) {
                mkdir($filename_year, 0777);
            }
            if (!file_exists($filename_month)) {
                mkdir($filename_month, 0777);
            }

            $path_parts = pathinfo($_FILES["image"]["name"]);
            $fileName =
                $path_parts["filename"] .
                "_" .
                time() .
                "." .
                $path_parts["extension"];
            $onlyfileName = $path_parts["filename"].$path_parts["extension"];
            $relativefilePath = $relativefilename_month . "/" . $fileName;
            $targetFilePath = $filename_month . "/" . $fileName;
            $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
            if (
                move_uploaded_file(
                    $_FILES["image"]["tmp_name"],
                    $targetFilePath
                )
            ) {
                $statusMsg = "";
            } else {
                $statusMsg = "Sorry, there was an error uploading your file.";
            }
        }

        if (empty($statusMsg)) {
            $insert_image_query = "INSERT into images(DeliveryID,ImageName,ImagePath,ImageDescription,OtherDescription,RelativeImagePath) values('$deliveryid','$onlyfileName','$relativefilePath','$imagedescription','$img_other_desc','$targetFilePath')";
            $insert_image_result = $db_handle->executeQuery(
                $insert_image_query
            );
            if ($insert_image_result == 1) {
                $statusMsg = "Image Added Successfully";
            } else {
                $statusMsg = "There is an issue on updating Delivery Record";
            }
        }
        echo $statusMsg;
    }
    if ($_POST["action"] == "delete") {
        $delete_img_id = $_POST["image_id"];

        $get_relative_file_path_query = "Select RelativeImagePath FROM images WHERE Imageid='$delete_img_id'";
        $get_relative_file_path_result = current(
            $db_handle->runQuery($get_relative_file_path_query)
        );

        $delete_image_query = "DELETE FROM images WHERE Imageid='$delete_img_id'";
        $delete_image_result = $db_handle->executeQuery($delete_image_query);

        $del_img_file = $get_relative_file_path_result["RelativeImagePath"];

        if ($delete_image_result) {
            if (!empty($del_img_file)) {
                unlink($del_img_file);
            }
            echo "Image Deleted Successfully";
        }
    }
}
?>
