<?php
session_start();
include("../include/config.php");
include("../include/functions.php");
include("../include/simpleimage.php");
validate_admin();


function isValidImage($tmpPath) {
    if (!file_exists($tmpPath)) return false;

    $allowedMime = ['image/jpeg', 'image/png', 'image/webp'];

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime  = finfo_file($finfo, $tmpPath);
    finfo_close($finfo);

    if (!in_array($mime, $allowedMime)) return false;
    if (getimagesize($tmpPath) === false) return false;

    // Block embedded scripts
    $head = file_get_contents($tmpPath, false, null, 0, 512);
    if (preg_match('/<\?php|<script|<html|<!DOCTYPE/i', $head)) return false;

    return true;
}
require_once __DIR__ . '/../include/S3Helper.php';
$s3 = new S3Helper();

if ($_REQUEST['submitForm'] == 'yes') {
	$title = mysqli_real_escape_string($GLOBALS['conn'], $_REQUEST['title']);
	$storeid = mysqli_real_escape_string($GLOBALS['conn'], $_REQUEST['store']);
	$order_no = mysqli_real_escape_string($GLOBALS['conn'], $_REQUEST['order_no']);
	if ($_FILES['poster_img']['size'] > 0 && $_FILES['poster_img']['error'] === 0 && isValidImage($_FILES['poster_img']['tmp_name'])) {

		$photo = 'posterimg' . time() . substr($_FILES['poster_img']['name'], -5);

        $path = $s3->upload($_FILES['poster_img']['tmp_name'], 'upload_images/reels/', $photo);

		if (!$path) {
				die("Something went wrong, unable to upload featured image, contact to site administrator."); // do whatever it is that you want to do when you are unable to upload the file.
		}

		//ftp start
		// if (SITE_URL == 'https://admin.quicklly.com/') {
		// 	$conn_id = ftp_connect("3.133.214.148") or die("Error in FTP connection");
		// 	$login_status = ftp_login($conn_id, "mainuser@quicklly.com", "n3At8hv3LZKCiF6") or die("Error in FTP login");  // Login to the FTP server.
		// 	ftp_pasv($conn_id, true);

			//to upload from local
			//ftp_pasv($conn_id, true);
			//to create dir
			//ftp_mkdir($conn_id, "imageststs");
			// $target_file = $_FILES['poster_img']['tmp_name'];
			// $destination_file = "upload_images/reels/" . $photo;  // 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) {
			// 	die("Something went wrong, unable to upload featured image, 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);
	// 	} else {
	// 	}
	// 	//ftp ends

	// 	move_uploaded_file($_FILES['poster_img']['tmp_name'], "../upload_images/reels/" . $photo);
	}
	if ($_FILES['video_url']['size'] > 0 && $_FILES['video_url']['error'] == '') {
        header('Access-Control-Allow-Origin: *');
        header('Content-type: application/json');
        http_response_code(200);
    
        $file_name = $title . '-' . substr(md5(mt_rand()), 0, 5) . '.mp4';
        $file_tmp  = $_FILES['video_url']['tmp_name'];
    
        try {
            $folder = (SITE_URL == 'https://admin.quicklly.com/') ? 'reels' : 'reels-dev';
    
            $s3Url = $s3->upload($file_tmp, $folder, $file_name);
    
            $finalvideourl = SITE_URL_CDN."/$folder/$file_name";
    
        } catch (Exception $e) {
            $response = array(
                'success' => false,
                'msg'     => $e->getMessage()
            );
            echo json_encode($response);
        }
    }
	if ($_REQUEST['id'] == '') {

		$obj->query("insert into tbl_store_reels set title='$title', video_url='$finalvideourl',poster_img='$photo',order_no='$order_no',storeid='$storeid',status=1");
		$_SESSION['sess_msg'] = 'Reels added successfully';
	} else {
		$sql = " update tbl_store_reels set title='$title',order_no='$order_no',storeid='$storeid',status=1";

		if ($photo) {
			$imageArr = $obj->query("select poster_img from tbl_store_reels where id='" . $_REQUEST['id'] . "' ");
			$resultImage = $obj->fetchNextObject($imageArr);
			@unlink("../images/reels/" . $resultImage->poster_img);
			$sql .= " ,poster_img='$photo'";
		}
		if ($file_name) {
			$imageArr = $obj->query("select video_url from tbl_store_reels where id='" . $_REQUEST['id'] . "' ");
			$resultImage = $obj->fetchNextObject($imageArr);
			@unlink("upload-tmp/" . $resultImage->video_url);
			$sql .= " ,video_url='$finalvideourl' ";
		}
		$sql .= " where id='" . $_REQUEST['id'] . "'";
		$obj->query($sql);
		$_SESSION['sess_msg'] = 'Reel updated successfully';
	}
	header("location:reels-list.php");
	exit();
}


if ($_REQUEST['id'] != '') {
	$sql = $obj->query("select * from tbl_store_reels 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.name.value == '') {
				alert("Please enter Heading");
				obj.name.focus();
				return false;
			}
			if (obj.url.value == '') {
				alert("Please enter url");
				obj.url.focus();
				return false;
			}


		}
	</script>
	<script type="text/javascript" src="../include/ckeditor/ckeditor.js"></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:<?php if ($_REQUEST['id'] == '') { ?> Add<?php } else { ?>Update<?php } ?> Reels
										<span style="float:right; padding-right:10px;">
											<input type="button" name="add" value="View Reels" class="button" onclick="location.href='reels-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> Title:</strong></td>
													<td align="left" class="paddBot11">
														<input type="text" name="title" id="title" size="150" value="<?php echo stripslashes($result->title); ?>" required>
												</tr>
												<tr>
													<td align="right" class="paddBot11 paddRt14"><strong>Display Order :</strong></td>
													<td align="left" class="paddBot11">
														<input type="number" name="order_no" id="order_no" size="150" value="<?php echo stripslashes($result->order_no); ?>" required>
												</tr>

												<tr>
													<td align="right" class="paddBot11 paddRt14"><strong> Stores:</strong></td>
													<td align="left" class="paddBot11">
														<select name="store" id="store" required>
															<option value=""> Select Store</option>
															<?php
															$sqlforsto = $obj->Query("SELECT storeid,storename FROM stores WHERE sectionid in(3,39) AND status=1");
															while ($linestor = $obj->fetchNextObject($sqlforsto)) { ?>
																<option value="<?php echo $linestor->storeid ?>" <?php if ($result->storeid == $linestor->storeid) { ?>selected<?php } ?>><?php echo $linestor->storename; ?></option>
															<?php } ?>
														</select>
												</tr>
												<tr>
													<td align="right" class="paddBot11 paddRt14"><strong>Upload Video(In Mp4 Format-480X720):</strong></td>
													<td align="left" class="paddBot11"><input name="video_url" size="150" type="file" /><br />
														<?php if ($result->video_url) { ?>
															<?php echo $result->video_url; ?>
														<?php } ?>
													</td>
												</tr>

												<tr>
													<td align="right" class="paddBot11 paddRt14"><strong>Poster Image(In Png format only-480X720):</strong></td>
													<td align="left" class="paddBot11"><input name="poster_img" size="150" type="file" /><br />
														<?php if ($result->poster_img) { ?>
															<img src="<?php echo SITE_URL_CDN; ?>/upload_images/reels/<?php echo $result->poster_img; ?>" width="100" height="100" />
														<?php } ?>
													</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>