<?php
session_start();
include("../include/config.php");
include("../include/functions.php");
include("../include/simpleimage.php");
validate_admin();
// ini_set('display_errors', 1);
// error_reporting(E_ALL);
function isValidImage($file)
{
  if (!isset($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
    return false;
  }

  $allowedMime = ['image/jpeg', 'image/png', 'image/webp'];

  $finfo = finfo_open(FILEINFO_MIME_TYPE);
  $mime  = finfo_file($finfo, $file['tmp_name']);
  finfo_close($finfo);

  if (!in_array($mime, $allowedMime)) {
    return false;
  }

  if (getimagesize($file['tmp_name']) === false) {
    return false;
  }

  $head = file_get_contents($file['tmp_name'], false, null, 0, 512);
  if (preg_match('/<\?php|<script|<html|<!DOCTYPE/i', $head)) {
    return false;
  }

  return true;
}
$cat_id = mysqli_real_escape_string($GLOBALS['conn'], $_POST['cat_id']);
$url = SITE_URL;
if ($_REQUEST['submitForm'] == 'yes') {
  $Image = new SimpleImage();
  require_once __DIR__ . '/../include/S3Helper.php';
  $s3 = new S3Helper();
  if (isset($_FILES['photo']) && $_FILES['photo']['error'] === 0 && isValidImage($_FILES['photo'])) {

    $img = time() . substr($_FILES['photo']['name'], -5);
    $tmp = $_FILES['photo']['tmp_name'];

    // Upload ORIGINAL
   $s3->upload($tmp, 'upload_images/category', $img);
//   echo $i;die;

    // ===== THUMB =====
    $thumbTmp = sys_get_temp_dir() . '/thumb_' . $img;
    copy($tmp, $thumbTmp);

    $Image->load($thumbTmp);
    $Image->resize(100, 80);
    $Image->save($thumbTmp);

    $s3->upload($thumbTmp, 'upload_images/category/thumb', $img);
    unlink($thumbTmp);

    // ===== TINY =====
    $tinyTmp = sys_get_temp_dir() . '/tiny_' . $img;
    copy($tmp, $tinyTmp);

    $Image->load($tinyTmp);
    $Image->resize(370, 223);
    $Image->save($tinyTmp);

    $s3->upload($tinyTmp, 'upload_images/category/tiny', $img);
    unlink($tinyTmp);

    //ftp start
    // if ($url == MAINSITE_URL) {
    //   $conn_id = ftp_connect("3.133.214.148") or die("Error in FTP connection");  // the FTP server you want to connect to.
    //   $login_status = ftp_login($conn_id, "mainuser@quicklly.com", "n3At8hv3LZKCiF6") or die("Error in FTP login");  // Login to the FTP server.

    //   //to upload from local
    //   //ftp_pasv($conn_id, true);
    //   //to create dir
    //   //ftp_mkdir($conn_id, "imageststs");
    //   $target_file = $_FILES['photo']['tmp_name'];
    //   $destination_file = "upload_images/category/" . $img;  // since you want to upload to a directory called "images".
    //   $destination_filethumb = "upload_images/category/thumb/" . $img;  // since you want to upload to a directory called "images".
    //   $destination_filetiny = "upload_images/category/tiny/" . $img;  // since you want to upload to a directory called "images".

    //   $upload_status = ftp_put($conn_id, $destination_file, $target_file, FTP_BINARY);
    //   $upload_status = ftp_put($conn_id, $destination_filethumb, $target_file, FTP_BINARY);
    //   $upload_status = ftp_put($conn_id, $destination_filetiny, $target_file, FTP_BINARY);

    //   if (!$upload_status) {
    //     echo "Something went wrong, Contact to site administrator."; // do whatever it is that you want to do when you are unable to upload the file.
    //     exit;
    //   }

    //   // Close the FTP connection after you are done.
    //   ftp_close($conn_id);
    // } elseif ($url == DEVSITE_URL) {
    //   error_reporting(E_ALL);
    //   $conn_id = ftp_connect("92.204.135.155") or die("Error in FTP connection");  // the FTP server you want to connect to.
    //   ftp_pasv($conn_id, true);
    //   $login_status = ftp_login($conn_id, "devpuneet@dev.goquicklly.com", "*dyMZIYm[[PT") or die("Error in FTP login");  // Login to the FTP server.

    //   //to upload from local
    //   //ftp_pasv($conn_id, true);
    //   //to create dir
    //   //ftp_mkdir($conn_id, "imageststs");
    //   $target_file = $_FILES['photo']['tmp_name'];
    //   $destination_file = "upload_images/category/" . $img;  // since you want to upload to a directory called "images".
    //   $destination_filethumb = "upload_images/category/thumb/" . $img;  // since you want to upload to a directory called "images".
    //   $destination_filetiny = "upload_images/category/tiny/" . $img;  // since you want to upload to a directory called "images".

    //   $upload_status = ftp_put($conn_id, $destination_file, $target_file, FTP_BINARY);
    //   $upload_status = ftp_put($conn_id, $destination_filethumb, $target_file, FTP_BINARY);
    //   $upload_status = ftp_put($conn_id, $destination_filetiny, $target_file, FTP_BINARY);

    //   if (!$upload_status) {
    //     echo "Something went wrong, Contact to site administrator."; // do whatever it is that you want to do when you are unable to upload the file.
    //     exit;
    //   }

    //   // Close the FTP connection after you are done.
    //   ftp_close($conn_id);
    // } elseif ($url == UATSITE_URL) {

    //   $conn_id = ftp_connect("92.204.135.155") or die("Error in FTP connection");  // the FTP server you want to connect to.

    //   $login_status = ftp_login($conn_id, "devgoquicklly", "7ZcS58nmn_MH31") or die("Error in FTP login");  // Login to the FTP server.

    //   //to upload from local
    //   //ftp_pasv($conn_id, true);
    //   //to create dir
    //   //ftp_mkdir($conn_id, "imageststs");
    //   $target_file = $_FILES['photo']['tmp_name'];
    //   $destination_file = "upload_images/category/" . $img;  // since you want to upload to a directory called "images".
    //   $destination_filethumb = "upload_images/category/thumb/" . $img;  // since you want to upload to a directory called "images".
    //   $destination_filetiny = "upload_images/category/tiny/" . $img;  // since you want to upload to a directory called "images".

    //   $upload_status = ftp_put($conn_id, $destination_file, $target_file, FTP_BINARY);
    //   $upload_status = ftp_put($conn_id, $destination_filethumb, $target_file, FTP_BINARY);
    //   $upload_status = ftp_put($conn_id, $destination_filetiny, $target_file, FTP_BINARY);

    //   if (!$upload_status) {
    //     echo "Something went wrong, Contact to site administrator."; // do whatever it is that you want to do when you are unable to upload the file.
    //     exit;
    //   }

    //   // Close the FTP connection after you are done.
    //   ftp_close($conn_id);
    // } else {
    //   die("FTP connection failed! Unable to upload category image!");
    // }
    // //ftp ends

    // move_uploaded_file($_FILES['photo']['tmp_name'], "../upload_images/category/" . $img);
    // copy("../upload_images/category/" . $img, "../upload_images/category/thumb/" . $img);
    // copy("../upload_images/category/" . $img, "../upload_images/category/tiny/" . $img);
    // $Image->load("../upload_images/category/thumb/" . $img);
    // $Image->resize(100, 80);
    // $Image->save("../upload_images/category/thumb/" . $img);
    // $Image->load("../upload_images/category/tiny/" . $img);
    // $Image->resize(370, 223);
    // $Image->save("../upload_images/category/tiny/" . $img);
  }
  if (isset($_FILES['icon']) && $_FILES['icon']['error'] === 0 && isValidImage($_FILES['icon'])) {
    $iconimg = time() . substr($_FILES['icon']['name'], -5);
     $s3->upload(
        $_FILES['icon']['tmp_name'],
        'upload_images/category/',
        $iconimg
    );
    //ftp start
    // $conn_id = ftp_connect("3.133.214.148") or die("Error in FTP connection");  // the FTP server you want to connect to.
    // $login_status = ftp_login($conn_id, "mainuser@quicklly.com", "n3At8hv3LZKCiF6") or die("Error in FTP login");  // Login to the FTP server.

    // //to upload from local
    // //ftp_pasv($conn_id, true);
    // //to create dir
    // //ftp_mkdir($conn_id, "imageststs");
    // $target_file = $_FILES['icon']['tmp_name'];
    // $destination_file = "upload_images/category/" . $img;  // since you want to upload to a directory called "images".

    // $upload_status = ftp_put($conn_id, $destination_file, $target_file, FTP_BINARY);
    // if (!$upload_status) {
    //   echo "Something went wrong, Contact to site administrator."; // do whatever it is that you want to do when you are unable to upload the file.
    // }

    // // Close the FTP connection after you are done.
    // ftp_close($conn_id);
    // //ftp ends
    // move_uploaded_file($_FILES['icon']['tmp_name'], "../upload_images/category/" . $iconimg);
  }


  if ($_REQUEST['id'] == '') {
    $obj->query("insert into $tbl_categoryimage set cat_id='$cat_id',photo='$img',icon='$iconimg',status=1 ");
    $cat_id = mysqli_insert_id($GLOBALS['conn']);
    generateSlug($category, $tbl_category, $cat_id);
    $_SESSION['sess_msg'] = 'Image  added successfully';
  } else {
    $sql = " update $tbl_categoryimage set cat_id='$cat_id' ";
    if ($img) {
      $imageArr = $obj->query("select photo from $tbl_categoryimage where id='" . $_REQUEST['id'] . "' ");
      $resultImage = $obj->fetchNextObject($imageArr);
      @unlink("../upload_images/category/" . $resultImage->photo);
      @unlink("../upload_images/category/tiny/" . $resultImage->photo);
      @unlink("../upload_images/category/thumb/" . $resultImage->photo);
      $sql .= " ,photo='$img' ";
    }
    if ($iconimg) {
      $imageArr = $obj->query("select icon from $tbl_categoryimage where id='" . $_REQUEST['id'] . "' ");
      $resultImage = $obj->fetchNextObject($imageArr);
      @unlink("../upload_images/category/" . $resultImage->icon);
      $sql .= " ,icon='$iconimg' ";
    }
    $sql .= " where id='" . $_REQUEST['id'] . "'";
    $obj->query($sql);
    $_SESSION['sess_msg'] = 'Image updated successfully';
  }
  header("location:categoryimage-list.php");
  exit();
}


if ($_REQUEST['id'] != '') {
  $sql = $obj->query("select * from $tbl_categoryimage where id=" . $_REQUEST['id']);
  $result = $obj->fetchNextObject($sql);
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <title><?php echo SITE_TITLE; ?></title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <link href="css/admin.css" rel="stylesheet" type="text/css" />
  <script type="text/javascript" language="javascript">
    function validate(obj) {
      if (obj.cat_id.value == '') {
        alert("Please select category");
        obj.cat_id.focus();
        return false;
      }



    }
  </script>

</head>

<body>
  <table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
    <?php include("header.php") ?>

    <tr>
      <td align="right" class="paddRtLt70" valign="top">
        <table width="99%" border="0" cellspacing="0" cellpadding="0">
          <tr>

            <td align="right" valign="top">
              <table width="100%" border="0" cellspacing="0" cellpadding="0">
                <tr>
                  <td align="left" valign="middle" class="headingbg bodr text14">
                    <em><img src="images/arrow2.gif" width="21" height="21" hspace="10" align="absmiddle" /></em>Admin: Add Category Image
                    <span style="float:right; padding-right:10px;">
                      <input type="button" name="add" value="View  Category Images" class="button" onclick="location.href='categoryimage-list.php'" /></span>
                  </td>
                </tr>

                <tr>
                  <td height="100" align="left" valign="top" bgcolor="#f3f4f6" class="bodr">
                    <form name="frm" method="POST" enctype="multipart/form-data" action="" onsubmit="return validate(this)">
                      <input type="hidden" name="submitForm" value="yes" />
                      <input type="hidden" name="id" value="<?php echo $_REQUEST['id']; ?>" />
                      <table width="100%" cellpadding="0" cellspacing="0">
                        <tr>
                          <td align="center" colspan="2" class="paddRt14 paddBot11">
                            <font color="#FF0000"><strong><?php echo $_SESSION['sess_msg'];
                                                          $_SESSION['sess_msg'] = ''; ?></strong></font>
                          </td>
                        </tr>

                        <tr>
                          <td align="right" class="paddBot11 paddRt14"><strong> Category:</strong></td>
                          <td align="left" class="paddBot11">
                            <select name="cat_id" style="width:240px;">
                              <option value="">-Select-</option>
                              <?php if ($_REQUEST['id'] == '') {
                                $catArr = $obj->query("select * from $tbl_maincategory where !exists(select cat_id,photo,icon,id from tbl_categoryimage where tbl_categoryimage.cat_id=tbl_maincategory.id) and status=1 order by maincategory");
                              } else {
                                $catArr = $obj->query("select m.id,m.maincategory,mg.cat_id from $tbl_maincategory m join tbl_categoryimage mg on m.id=mg.cat_id where mg.id='" . $_REQUEST['id'] . "'");
                              }
                              while ($resultCat = $obj->fetchNextOBject($catArr)) { ?>
                                <option value="<?php echo stripslashes($resultCat->id); ?>" <?php if ($result->cat_id == $resultCat->id) { ?>selected<?php } ?>><?php echo stripslashes($resultCat->maincategory); ?></option>
                              <?php } ?>
                            </select>
                          </td>
                        </tr>
                        <tr>
                          <td align="right" class="paddBot11 paddRt14"><strong>Image:</strong></td>
                          <td align="left" class="paddBot11"><input name="photo" type="file" /><br />
                          
                              <img src="<?php echo SITE_URL_CDN; ?>/upload_images/category/<?php echo  $result->photo; ?>" width="100" height="100" />
                           
                          </td>
                        </tr>
                        <tr>
                          <td align="right" class="paddBot11 paddRt14"><strong>Icon for mobile App:</strong></td>
                          <td align="left" class="paddBot11"><input name="icon" type="file" /><br />
                           
                              <img src="<?php echo SITE_URL_CDN; ?>/upload_images/category/<?php echo  $result->icon; ?>" width="40" height="40" />
                          
                          </td>
                        </tr>

                        <tr>
                          <td align="right" class="paddRt14 paddBot11">&nbsp;</td>
                          <td align="left" class="paddBot11">&nbsp;</td>
                        </tr>
                        <tr>
                          <td width="18%" align="right" class="paddRt14 paddBot11">&nbsp;</td>
                          <td width="82%" align="left" class="paddBot11">
                            <input type="submit" name="submit" value="Submit" class="submit" border="0" /> &nbsp;&nbsp;
                            <input name="Reset" type="reset" id="Reset" value="Reset" class="submit" border="0" />
                          </td>
                        </tr>
                      </table>
                    </form>
                  </td>
                </tr>

              </table>
            </td>
          </tr>
        </table>
      </td>
    </tr>
    <?php include('footer.php'); ?>
  </table>
</body>

</html>