<?php 
require 'inc/_global/config.php';
require 'inc/_global/db_pdo.php';
require 'inc/_global/auth.php'; 
require 'inc/backend/config.php'; 
require 'inc/_global/views/head_start.php'; 

// Codebase - Page specific configuration
$cb->l_sidebar_inverse = true;
$cb->l_header_style    = 'glass-inverse';

// Page JS Plugins CSS 
$cb->get_css('js/plugins/select2/css/select2.min.css'); 
$cb->get_css('js/plugins/jquery-tags-input/jquery.tagsinput.min.css'); 
$cb->get_css('js/plugins/jquery-auto-complete/jquery.auto-complete.min.css');
require 'inc/_global/views/head_end.php'; 
require 'inc/_global/views/page_start.php'; 

date_default_timezone_set("Australia/Melbourne");

$debugdate = date("Y-m-d H:i:s");
$debugsql = "INSERT INTO debug (note, created_at) VALUES (?,?)";
$debugnote = "================================ ITEM EDIT REVIEW ====================================================";
//$pdo->prepare($debugsql)->execute([$debugnote, $debugdate]);

$store_id = $_SESSION['store_id'];
$subdomain = $_SESSION['subdomain'];
$item_id = $_REQUEST['id'];

$stmt = $pdo->prepare("SELECT * FROM items WHERE id=:iid");
$stmt->execute(['iid' => $item_id]); 
$item = $stmt->fetch();

$item_code = $item['item_code'];
$item_price = $item['price'];
$consignor_id = $item['consignor_id'];
$brand = $item['brand'];

$stmt = $pdo->prepare("SELECT * from consignors WHERE id=:cid");
$stmt->execute(['cid' => $consignor_id]); 
$consignor = $stmt->fetch();
$consignor_code = $consignor['consignor_code'];
$price = $item['price'];
$consignment = '1';

/// how many unreviewed items are there for this consignor.
$ss='SUBMITTED';
$stmt = $pdo->prepare("SELECT count(*) FROM items WHERE consignor_id=:cid AND status=:status");
$stmt->execute(['cid' => $consignor_id, 'status'=>$ss]);
$submitted_items = $stmt->fetchColumn();

?>

<link rel="stylesheet" href="/assets/css/modal_rounded.css" type="text/css" />

<?php if ($_SESSION['mobile_device'] == "yes") {?>
	<input type="hidden" id="mobile" name="mobile"  value="yes">
<?php } else { ?>	
	<input type="hidden" id="mobile" name="mobile"  value="no">
<?php } ?>

<div class="bg-black-sm-100">
	<div class="content text-center">
		<h1 class="h2 font-w700 text-white mb-5"><i class="fa fa-camera text-success-light mr-5"></i>&nbsp;&nbsp;Review Item</h1>
	</div>
</div>
<div class="bg-black-op-25 ">
	<div class="content py-5 text-center">
		<h1 class="h3 font-w400 text-sm mb-5">&nbsp;&nbsp;Submitted by <a class="text-primary link-effect" href="consignor.php?id=<?php echo $consignor_id; ?>"><?php echo $consignor['first_name'].' '.$consignor['last_name']; ?> (<?php echo $consignor_code; ?>)</a>.</h3>
	</div>
</div>

<!-- Breadcrumb -->
<div class="bg-body-light border-b">
    <div class="content py-5 text-center">
        <nav class="breadcrumb bg-body-light mb-0">
            <a class="breadcrumb-item" href="dashboard.php">Dashboard</a>
            <a class="breadcrumb-item" href="review_items.php">Review Items</a>
            <span class="breadcrumb-item active"><?php echo $item['brand'];?></span>
        </nav>
    </div>
</div>
<!-- END Breadcrumb -->

<!-- Page Content -->
<div class="content">

	<div class="row gutters-tiny; margin-bottom: 0px">

		<!-- Accept Item -->
		<div class="col-xl-4">
			<a class="block block-rounded block-link-shadow" href="javascript:void(0)" data-toggle="modal" onclick="javascript:accept_item();">
				<div class="block-content block-content-full block-sticky-options">
					<div class="py-15 text-center">
						<?php if ($item['status'] == 'ACCEPTED') { ?>
							<div class="font-size-h2 font-w700 mb-0 text-success">
								<i class="fa fa-save"></i>
							</div>
							<div class="font-size-sm font-w600 text-uppercase text-muted">Save Item</div>
						<?php } else { ?>			
							<div class="font-size-h2 font-w700 mb-0 text-success">
								<i class="fa fa-check"></i>
							</div>
							<div class="font-size-sm font-w600 text-uppercase text-muted">Accept Item</div>
						<?php } ?>			
						
					</div>
				</div>
			</a>
		</div>

		<?php if ($item['status'] == 'SUBMITTED') { ?>

			<!-- IF ITEM IS ACCEPTED AND IT IS LAST ITEM FOR CONSIGNOR, POST WARNING BEFORE ALLOWING REJECTION -->
			<!-- Reject Item -->
			<div class="col-xl-4">
				<a class="block block-rounded block-link-shadow" href="javascript:void(0)" data-toggle="modal" onclick="javascript:reject_submitted_item();">
					<div class="block-content block-content-full block-sticky-options">
						<div class="py-15 text-center">
							<div class="font-size-h2 font-w700 mb-0 text-danger">
								<i class="fa fa-times"></i>
							</div>
							<div class="font-size-sm font-w600 text-uppercase text-muted">Reject Item</div>
						</div>
					</div>
				</a>
			</div>
		<?php } ?>

		<?php if (($item['status'] == 'ACCEPTED') && ($_SESSION['role']!='Staff')) { ?>

			<!-- Reject Item -->
			<div class="col-xl-4">
				<a class="block block-rounded block-link-shadow" href="javascript:void(0)" data-toggle="modal" onclick="javascript:reject_accepted_item();">
					<div class="block-content block-content-full block-sticky-options">
						<div class="py-15 text-center">
							<div class="font-size-h2 font-w700 mb-0 text-danger">
								<i class="fa fa-times"></i>
							</div>
							<div class="font-size-sm font-w600 text-uppercase text-muted">Reject Item</div>
						</div>
					</div>
				</a>
			</div>
		<?php } ?>

		
		<?php if (($item['status'] != 'ACCEPTED') || ($_SESSION['role']!='Staff')) { ?>
		
			<!-- Delete Item -->
			<div class="col-xl-4">
				<a class="block block-rounded block-link-shadow" href="javascript:void(0)" data-toggle="modal" onclick="javascript:delete_item();">
					<div class="block-content block-content-full block-sticky-options">
						<div class="py-15 text-center">
							<div class="font-size-h2 font-w700 mb-0 text-danger">
								<i class="fa fa-trash"></i>
							</div>
							<div class="font-size-sm font-w600 text-uppercase text-muted">Delete Item</div>
						</div>
					</div>
				</a>
			</div>
		<?php } ?>

	</div>

    <div class="alert alert-danger display-error" style="display: none"></div>
    
	<br>
    <div class="row gutters-tiny">
        <!-- Basic Info -->
        <div class="col-md-9">
            <form class="js-validation-item" action="" method="post" id="edit-item-form">
			
                <div id="basic-info-block" class="block block-rounded block-themed">
                    <div class="block-header bg-gd-primary">
                        <h3 class="block-title">Review Item</h3>
                    </div>
                    <div class="block-content block-content-full">
                        <div class="form-group row">
							<div class="col-2">Item Code:</div>
							<div class="col-4">
								<div class="floating input-group">	 
									<label for="item-code"><?php echo $item['item_code']; ?></label>
									<input type="hidden" class="form-control" id="item-code" name="item-code" value="<?php echo $item['item_code']; ?>">
									<input type="hidden" class="form-control" id="item-id" name="item-id" value="<?php echo $item['id']; ?>">
									<input type="hidden" class="form-control" id="status" name="status" value="<?php echo $item['status']; ?>">
									<input type="hidden" class="form-control" id="submitted-items" name="submitted-items" value="<?php echo $submitted_items; ?>">
								</div>
							</div>
							<div class="col-6"></div>
						</div>
                        <div class="form-group row">
                            <label class="col-12" for="brand">Brand <span class="text-danger">*</span></label>
							<div class="form-group">
						
								<div class="input-group">
									<input style="height:auto !important" onClick="this.setSelectionRange(0, this.value.length);" type="text"
											class="js-autocompletebrand form-control uc_brand" id="filter_by_brand" name="filter_by_brand"
											value="<?php echo $brand; ?>" placeholder="Enter brand name ..." />
									<div class="input-group-append">
										<button id="search_brand" name="search_brand" class="btn btn-secondary">
											<i class="fa fa-search"></i>
										</button>
									</div>
									<div id="mydiv">
										<?php if (!empty($_POST['filter_by_brand'])) { ?>
											<?php if ($filter_brand_status == "unbranded") { ?>
												<span style="margin-left: 20px; margin-right: 30px" class="font-size-h2 font-w700 text-warning">
													<i class="fa fa-circle-exclamation"></i>
												</span>
												<span class="font-size-h4 font-w400 text-warning">Make sure that this is genuinely unbranded</span>
											<?php } else if ($filter_brand_status == "accepted") { ?>
												<span style="margin-left: 20px; margin-right: 30px" class="font-size-h2 font-w700 text-success">
													<i class="fa fa-check-circle"></i>
												</span>
												<span class="font-size-h4 font-w400 text-success">Brand Accepted</span>
											<?php } else if ($filter_brand_status == "notaccepted") { ?>
												<span style="margin-left: 20px; margin-right: 20px" class="font-size-h2 font-w700 text-danger">
													<i class="fa fa-times-circle"></i>
												</span>
												<span class="font-size-h4 font-w400 text-danger">Brand Not Accepted</span>
											<?php } else if ($filter_brand_status == "notdefined") { ?>
												<span style="margin-left: 20px; margin-right: 30px" class="font-size-h2 font-w700 text-grey">
													<i class="fa fa-question-circle fa-lg tt-colour"></i>
												</span>
												<span class="font-size-h4 font-w400 text-grey">Brand Not Listed</span>
											<?php } ?>
										<?php }	?>
									</div>
								</div>
							</div>
							<div class="col-md-12">
								<input type="hidden" class="form-control form-control-lg" id="brand-name" name="brand-name" value="<?php echo $brand; ?>">
								<span class="text-danger"  id="brand-err"></span>
							</div>
                        </div>
                        <div class="form-group row">
                            <label class="col-12" for="description">Description</label>
                            <div class="col-12">
                                <textarea class="form-control" id="description" name="description" placeholder="Description" rows="6"><?php echo $item['description']; ?></textarea>
                            </div>
                        </div>
                        <div class="form-group row">
							<div class="col-2">Size:</div>
							<div class="col-4">
								<div class="floating input-group">	 
									<label for="size"><?php echo $item['size']; ?></label>
								</div>
							</div>
							
                        </div>
                        <div class="form-group row">
                            <label class="col-12" for="review-note">Note for Consignor</label>
                            <div class="col-12">
                                <textarea class="form-control" id="review-note" name="review-note" placeholder="e.g. Not right brand"><?php echo $item['review_note'];?></textarea>
                            </div>
                        </div>

                        <div class="form-group row">
							<div class="col-6">
								<div class="form-group row">
									<label class="col-12" for="price">Price <span class="text-danger">*</span></label>
									<div class="col-12">
										<div class="input-group">
											<div class="input-group-prepend">
												<span class="input-group-text">
													<i class="fa fa-fw fa-usd"></i>
												</span>
											</div>
											<input type="text" class="form-control allow_numeric" id="price" name="price" <?php if (($_SESSION['role']=='Staff') && ($item['status'] != 'ACTIVE') && ($item['status'] != 'INACTIVE')) {?>readonly="readonly"<?php } ?> placeholder="" value="<?php echo $item['price']; ?>">
											
										</div>
									</div>
									<div class="col-12">
										<span class="text-danger"  id="price-err"></span>
									</div>
								</div>
							
							</div>
							
						</div>

                        <div class="py-20 font-size-xs">
							<div class="clearfix float-left">
								Date Submitted: <?php echo date('d/m/Y H:i:s', strtotime($item['created_at'])); ?>.	
							</div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
        <!-- END Basic Info -->

        <div class="col-md-3">
            <!-- Images -->
            <div class="block block-rounded block-themed">
                <div class="block-header bg-gd-primary">
                    <h3 class="block-title">Photos</h3>
                </div>

                <div class="block-content block-content-full">
                    <!-- Existing Images -->
                    <div id="image_preview" class="row gutters-tiny items-push">
						<!-- image section -->
						<div class="col-auto m-auto mb-2">
							<div class="options-container">

								<div class="slideshow-container">

									<?php if (!empty($item['photo'])) { 
										$photocount++;?>
										
										<div class="mySlides" id="fade">
											<img style="width: 210px; height: 280px;" src="assets/media/items/<?php echo $subdomain; ?>/<?php echo $item['photo']; ?>">
												<div class="options-overlay bg-black-op-75">
												<div class="options-overlay-content">

													<a class="btn btn-sm btn-rounded btn-alt-info min-width-50" href="javascript:void(0)" 
													data-toggle="modal" onclick="javascript:display_item('<?php echo $item_id; ?>', '<?php echo $subdomain . '/' . $item['photo']; ?>', '<?php $item['photo']; ?>');">
														<i class="fa fa-search"></i> View
													</a>
											
											</div>
											</div>
										</div>

										<?php if (!empty($item['photo2'])) { 
											$photocount++;?>
											<div class="mySlides" id="fade">
												<img style="width: 210px; height: 280px;" src="assets/media/items/<?php echo $subdomain; ?>/<?php echo $item['photo2']; ?>">
													<div class="options-overlay bg-black-op-75">
													<div class="options-overlay-content">

														<a class="btn btn-sm btn-rounded btn-alt-info min-width-50" href="javascript:void(0)" 
														data-toggle="modal" onclick="javascript:display_item('<?php echo $item_id; ?>', '<?php echo $subdomain . '/' . $item['photo2']; ?>', '<?php $item['photo2']; ?>');">
															<i class="fa fa-search"></i> View
														</a>
												
												</div>
												</div>
											</div>
										<?php }else{}?>

										<?php if (!empty($item['photo3'])) { 
											$photocount++;?>
											<div class="mySlides" id="fade">
												<img style="width: 210px; height: 280px;" src="assets/media/items/<?php echo $subdomain; ?>/<?php echo $item['photo3']; ?>">
													<div class="options-overlay bg-black-op-75">
													<div class="options-overlay-content">

														<a class="btn btn-sm btn-rounded btn-alt-info min-width-50" href="javascript:void(0)" 
														data-toggle="modal" onclick="javascript:display_item('<?php echo $item_id; ?>', '<?php echo $subdomain . '/' . $item['photo3']; ?>', '<?php $item['photo3']; ?>');">
															<i class="fa fa-search"></i> View
														</a>
												
												</div>
												</div>
											</div>
										<?php }else{}?>

											<?php if (!empty($item['photo4'])) { 
												$photocount++;?>
											<div class="mySlides" id="fade">
												<img style="width: 210px; height: 280px;" src="assets/media/items/<?php echo $subdomain; ?>/<?php echo $item['photo4']; ?>">
													<div class="options-overlay bg-black-op-75">
													<div class="options-overlay-content">

														<a class="btn btn-sm btn-rounded btn-alt-info min-width-50" href="javascript:void(0)" 
														data-toggle="modal" onclick="javascript:display_item('<?php echo $item_id; ?>', '<?php echo $subdomain . '/' . $item['photo4']; ?>', '<?php $item['photo4']; ?>');">
															<i class="fa fa-search"></i> View
														</a>
												
												</div>
												</div>
											</div>
											<?php }else{}?>
									<?php }else{?>
										<img class="circular--square" style="width: 210px; height: 280px;" src="assets/media/esale/image-not-found.png">   
									<?php } ?>

								</div>					
								<div class="options-overlay-remove bg-black-op-75"></div>
							</div>
							<div class="overlay"></div>
							<?php if ($photocount > 1) { ?>
								<div style="width: 100%;">
									<div class="slider-button" style="display: inline-block;"><a class="prev" onclick="plusSlides(-1)"><img src="https://img.icons8.com/metro/35/000000/circled-chevron-left.png"/></a></div>
									<div class="slider-button" style="display: inline-block;margin-left: auto;float: right;"><a class="next" onclick="plusSlides(1)"><img src="https://img.icons8.com/metro/35/000000/circled-chevron-right.png"/></a></div>
								</div>
							<?php }?>
						</div>
					</div>
                </div>
            </div>
            <!-- END Images -->
        </div>
        <!-- END More Options -->
    </div>

    <!-- END Update Product -->
</div>
<!-- END Page Content -->

<div class="modal fade" id="modal-image" tabindex="-1" role="dialog" aria-labelledby="modal-image" aria-hidden="true">
	<div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-popout" role="document">
		<div class="modal-content rounded">
			<div class="block block-rounded block-transparent mb-0 bg-pattern">
				<div class="block-header justify-content-end">
					<div class="block-options">
						<a class="font-size-xl text-danger" href="#" data-dismiss="modal" aria-label="Close">
							<b> X</b>
						</a>
					</div>
				</div>
				<form id="file_upload_edit" method="post" enctype="multipart/form-data">
					<div id="modal-img" class="block-content block-content-full">
					</div>
				</form>
			</div>
		</div>
	</div>
</div>


<?php require 'inc/_global/views/page_end.php'; ?>
<?php require 'inc/_global/views/footer_start.php'; ?>

<!-- Page JS Plugins -->
<?php $cb->get_js('js/plugins/ckeditor/ckeditor.js'); ?>
<?php $cb->get_js('js/plugins/bootstrap-maxlength/bootstrap-maxlength.min.js'); ?>
<?php $cb->get_js('js/plugins/select2/js/select2.full.min.js'); ?>
<?php $cb->get_js('js/plugins/jquery-tags-input/jquery.tagsinput.min.js'); ?>
<?php $cb->get_js('js/plugins/jquery-validation/jquery.validate.min.js'); ?>
<?php $cb->get_js('js/daypilot-modal-3.15.1.min.js'); ?>
<?php $cb->get_js('js/plugins/jquery-auto-complete/jquery.auto-complete.min.js'); ?>

<?php $cb->get_js('_es6/pages/item.js'); ?>
<?php $cb->get_js('_es6/pages/brand_list.js'); ?>

<!-- Page JS Helpers (CKEditor + BS Maxlength + Select + Tags Inputs plugins) -->
<script>jQuery(function(){ Codebase.helpers(['ckeditor', 'maxlength', 'select2', 'tags-inputs']); });</script>

<script>
jQuery(function(){ jQuery('#filter_by_brand').focus(); });

jQuery(function(){ 

	$(".allow_name").on("keypress", function(evt) {
		var self = $(this);
		var inputValue = event.which;
		// allow letters, whitepsaces, apostrophe and hyphen
		if(!(inputValue >= 65 && inputValue <= 90) && !(inputValue >= 97 && inputValue <= 122) && (inputValue != 32 && inputValue != 0 && inputValue != 39 && inputValue != 45)) { 
			event.preventDefault(); 
		}
	});

	$(".allow_numeric").on("keypress", function(evt) {
	    var self = $(this);
		self.val(self.val().replace(/[^0-9\.]/g, ''));
		if ((evt.which != 46 || self.val().indexOf('.') != -1) && (evt.which < 48 || evt.which > 57)) 
		{
		    evt.preventDefault();
		}
	 });

	$(".uc_brand").change(function(e){
		e.preventDefault();

		  var formData = new FormData($('#edit-item-form')[0]);

		  $.ajax({
			  type: "POST",
			  url: "./ajax/ajaxSearchBrand.php",
			  data: formData,
			  dataType: 'json',
			  contentType: false,
			  processData:false,
			  cache: false,
			  success: function(data) {
					console.log(data);
					var type = data.filter_brand_status;
					if(type == "accepted")
					{
						$("#mydiv").html('<span style="margin-left: 20px; margin-right: 30px" class="font-size-h2 font-w700 text-success">															<i class="fa fa-check-circle"></i>														</span><span class="font-size-h4 font-w400 text-success">Brand Accepted</span>');
					} else if(type == "unbranded") {
						  $("#mydiv").html('<span style="margin-left: 20px; margin-right: 20px" class="font-size-h2 font-w700 text-warning-dark">													<i class="fa fa-circle-exclamation"></i>														</span>	<span class="font-size-h4 font-w500 text-warning-dark">Ensure item is genuinely unbranded</span>');
					} else if(type == "notaccepted") {
						  $("#mydiv").html('<span style="margin-left: 20px; margin-right: 20px" class="font-size-h2 font-w700 text-danger">															<i class="fa fa-times-circle"></i>														</span>	<span class="font-size-h4 font-w400 text-danger">Brand Not Accepted</span>');
					} else if(type == "notdefined") {
						  $("#mydiv").html('<span style="margin-left: 20px; margin-right: 30px" class="font-size-h2 font-w700 text-grey">															<i class="fa fa-question-circle"></i>														</span> <span class="font-size-h4 font-w400 text-grey">Brand Not Listed</span>');
					} 
			  },
			  error: function(data){
				  var errorMessage = data.status + ': ' + data.statusText;
				   DayPilot.Modal.alert('Error - ' + errorMessage, {theme: "modal_rounded"});
				   $('#add-item').html('<i class="si si-login mr-10"></i> Add Item');
			  }
		  });

	});

	$(".uc_brand").bind('keyup', function (evt) {
        $(".uc_brand").val(($(".uc_brand").val()).toUpperCase());
    });

	jQuery('#search_brand').click(function(e){
        e.preventDefault();

		var formData = new FormData($('#edit-item-form')[0]);

		$.ajax({
            type: "POST",
            url: "./ajax/ajaxSearchBrand.php",
            data: formData,
            dataType: 'json',
   			contentType: false,
   			processData:false,
            cache: false,
            success: function(data) {
				console.log(data);
				var type = data.filter_brand_status;
				if(type == "accepted")
				{
					$("#mydiv").html('<span style="margin-left: 20px; margin-right: 30px" class="font-size-h2 font-w700 text-success">															<i class="fa fa-check-circle"></i>														</span><span class="font-size-h4 font-w400 text-success">Brand Accepted</span>');
				}
				else if(type == "notaccepted")
				{
					$("#mydiv").html('<span style="margin-left: 20px; margin-right: 20px" class="font-size-h2 font-w700 text-danger">															<i class="fa fa-times-circle"></i>														</span>	<span class="font-size-h4 font-w400 text-danger">Brand Not Accepted</span>');
				}
				else if(type == "notdefined")
				{
					$("#mydiv").html('<span style="margin-left: 20px; margin-right: 30px" class="font-size-h2 font-w700 text-grey">															<i class="fa fa-question-circle"></i>														</span> <span class="font-size-h4 font-w400 text-grey">Brand Not Listed</span>');
				}
				else
				{
				}
			},
			error: function(data){
	            var errorMessage = data.status + ': ' + data.statusText;
         		DayPilot.Modal.alert('Error - ' + errorMessage, {theme: "modal_rounded"});
         		$('#add-item').html('<i class="si si-login mr-10"></i> Add Item');
	        }
        });

          return false;

    });
   
});

function remove_item() {
	jQuery('#modal-normal').modal('show');
}

function display_item(id, subdomainItem, photo) {
	
	html_data = '<div class="form-group">';

	if (photo != null || photo != '') {

		html_data += '<div id="image_preview" class="row gutters-tiny items-push"><div class="col-12"><div class="options-container"><center><img id="blah" name="blah" style="width: 30%;" src="assets/media/items/' + subdomainItem + '"></center>                                </div></div></div>';
	}

	$('#modal-img').empty();
	$('#modal-img').append(html_data);

	$("#modal-image").removeClass("fade");

	$("#modal-image").modal({
		backdrop: 'static',
		keyboard: true
	});
}

function accept_item() {

	var price = $('#price').val();
	var brand  = $('#filter_by_brand').val();
	var item_id  = $('#item-id').val();	

	//clear up ssv error messages  
	$("#price-err").html('');
	$("#brand-err").html('');

	$.ajax({
		type: "POST",
		url: "./ajax/ajaxAcceptItemCheck.php",
		data:{itemid:item_id,price:price,brand:brand},
		dataType: 'json',
		success: function(data) { 
			if(data.code =='404'){
				if(data.msg.price && data.msg.price!=''){
					$("#price-err").html(data.msg.price);    
				}
				if(data.msg.brand && data.msg.brand!=''){
					$("#brand-err").html(data.msg.brand);    
				}
			}else{  
				if (data.msg.addbrand && data.msg.addbrand != '') {

					var msg = 'The brand ' + brand + ' is unknown.  What would you like to do?';
					const resources = [
						{ name: "  Accept item and add brand", id: "A" },
						{ name: "  Accept item but do not add brand", id: "B" },
						{ name: "  Cancel", id: "C" },
					];
					
					const form = [
						{
						  name: msg,
						  id: "resource",
						  options: resources,
						  type: "radio",
						},
					];

					const data = {
						resource: "A",
					};

					(async function() {
						const modal = await DayPilot.Modal.form(form, data);
						alert(modal.result);
						if (modal.result == 'A') {
							var addbrand = "yes";
							acceptitemconfirmed1(addbrand);
						} else if (modal.result == 'B') {
							var addbrand = "no";
							acceptitemconfirmed1(addbrand);
						} else {	
							$(location).attr("href", "item_edit_review.php?id="+item_id);
						}
					})();
					
				} else {
					addbrand = "no";
					acceptitemconfirmed1(addbrand);
				}	


			}    
		},
		error: function(data){
			var errorMessage = data.status + ': ' + data.statusText;
			DayPilot.Modal.alert('Error - ' + errorMessage, {theme: "modal_rounded"});
		}
	});
  
	return false;

}

function acceptitemconfirmed1(addbrand) {

	if (addbrand == 'yes') {

		var new_name = $('#filter_by_brand').val();
		new_name = new_name.replace(" & ", " ");
		var dataString = 'name=' + new_name;

		var brands = [];		

		$.ajax ({
			type:"POST",
			url: "./ajax/ajaxFindSimilarBrands.php",
			data: dataString,
			dataType: 'json',
			success: function(data){
				console.log(data);

				for (var i = 0; i < data.length; i++) {
					brands.push(data[i].brand_name);
					if (i == 0) {
						var brands_list = '&nbsp;&nbsp;' + data[i].brand_name;
					} else {
						brands_list = brands_list + '<br>&nbsp;&nbsp;' + data[i].brand_name;
					}	
						
				}
				
				if (i > 0) {
					if (i > 12) {
						var message = 'More than 12 similar brands exist in the list.<br><br>Are you sure this brand is unique?<br><br>If not, please search for the brand to ensure that it is unique before adding it.';
					} else {
						var message = 'Similar brands exist in the list. They are: <br> ' + brands_list + '.<br><br>Are you sure you want to add this?';		
					}		
					DayPilot.Modal.confirm(message, {theme: "modal_rounded", okText: "Accept item and add brand", cancelText: "Accept item but don't add brand" }).then(
					function(args){			
						 console.log(args.result);
						if (args.result) {
							acceptitemconfirmed2(addbrand);
						} else {
							addbrand="no";
							acceptitemconfirmed2(addbrand);							
						}   
					});
				} else {
					acceptitemconfirmed2(addbrand);
				}	

			},
			error: function(data){
					var errorMessage = data.status + ': ' + data.statusText;
					DayPilot.Modal.alert('Error - ' + errorMessage, {theme: "modal_rounded"});
				}
		});



	} else {
		acceptitemconfirmed2(addbrand);
	}


}

function acceptitemconfirmed2(addbrand) {

	var price = $('#price').val();
	var brand  = $('#filter_by_brand').val();
	var item_id  = $('#item-id').val();	
	var review_note  = $('#review-note').val();	
	var description = $('#description').val();
	var action = "accept";

	$.ajax({
		type: "POST",
		url: "./ajax/ajaxAcceptRejectItem.php",
		data:{itemid:item_id,price:price,brand:brand,description:description,note:review_note,action:action,addbrand:addbrand},
		dataType: 'json',
		success: function(data) { 
			if(data.code =='404'){
				if(data.msg.email && data.msg.email!=''){
					DayPilot.Modal.alert(data.msg.email, {theme: "modal_rounded"}).then(function(args){			console.log(args.result);
					if (args.result) {
						$(location).attr("href", "review_items.php");
					}
					});	
				}
				
			}else{  
				$(location).attr("href", "review_items.php");
			}    
		},
		error: function(data){
			var errorMessage = data.status + ': ' + data.statusText;
			DayPilot.Modal.alert('Error - ' + errorMessage, {theme: "modal_rounded"});
		}
	});
  
	return false;

}

function reject_submitted_item() {
	rejectitem();
}

function reject_accepted_item() {
	
	var submitted_items = $('#submitted-items').val();

	//if there are no submitted (unreviewed items), then show alert as the consignor has already been notified of accepted items
	if (submitted_items ==0) {
	
		DayPilot.Modal.confirm('The consignor has already been notified of their accepted items and may be planning to bring this item in.  Are you sure you want to reject this?', {theme: "modal_rounded", okText: "Yes", cancelText: "No" }).then(function(args){			
		console.log(args.result);
		if (args.result) {
			rejectitem();
		}   
		});
	} else {
		rejectitem();
	}	
	
}

function delete_item() {

	var status = $('#status').val();	

	//clear up ssv error messages  
	$("#price-err").html('');
	$("#brand-err").html('');

	if (status == 'ACCEPTED') {
		var $msg = 'If you delete this item the consignor will not be notified of the status.  The consignor may have already been notified that this item has been accepted' +
			'.<br>Are you certain you wish to delete it?';
	} else {
		var $msg = 'If you delete this item the consignor will not be notified of the status.  If you are not ' +
					'going to sell this item it may be best to reject it instead.  Are you certain you wish to delete it?';
	}

	if (status == 'REJECTED') {
		delitem();
	} else {
		DayPilot.Modal.confirm($msg, {theme: "modal_rounded", okText: "Yes", cancelText: "No" }).then(function(args){			console.log(args.result);
		if (args.result) {
			delitem();
		} else {
			$(location).attr("href", "item_edit_review.php?id=<?php echo $item_id; ?>");
			return;
		}	
		});		
	}
 
	return false;

}

function delitem(){

	var item_id  = $('#item-id').val();	

	$.ajax({
		type: "POST",
		url: "./ajax/ajaxDelItem.php",
		data: "id=" + item_id,
		cache: false,
		success: function(data) { 
			if(data.code =='404'){
			}else{  
				$(location).attr("href", "review_items.php");
			}    
		},
		error: function(data){
			var errorMessage = data.status + ': ' + data.statusText;
			DayPilot.Modal.alert('Error - ' + errorMessage, {theme: "modal_rounded"});
		}
	});
	
}

</script>

<script>

	let helpDimensions=function (w,h,l,t) {
		screen_height = window.screen.height;
		screen_width = window.screen.width;
		help_height = 0.88 * screen_height;
		help_width = 0.94 * screen_width;
		help_left = 0.03 * screen_width;
		help_top = 0.06 * screen_height;
		
		return 'width=' + help_width + ',height=' + help_height + ',left=' + help_left + ',top=' + help_top;
	}	
    $('#documentation_href').attr('onclick', "window.open('../help.php#Review_Items','Help', helpDimensions())");
</script>

<script>//image silder script code
var slideIndex = 1;
showSlides(slideIndex);

function rejectitem(){
	
	var brand  = $('#filter_by_brand').val();
	
	$.ajax({
	type: "POST",
	url: "./ajax/ajaxSearchBrand.php",
	data:{filter_by_brand:brand},
	dataType: 'json',
	success: function(data) {
		
		if (data.filter_brand_status == "notdefined") {

			// Check if user wishes to add brand as not accepted brand before rejecting item
			DayPilot.Modal.confirm('The brand ' + brand + ' is undefined.  Would you like to add it into the system as a brand that is not accepted?', {theme: "modal_rounded", okText: "Yes", cancelText: "No" }).then(function(args){
					console.log(args.result);
			if (args.result) {
				rejectitemconfirm('yes');
			} else {	
				rejectitemconfirm('no');
			}   
			});		
		} else {
			if (brand == 'UNBRANDED') {
				// do not offer to mark UNBRANDED as NOT ACCEPTED
				rejectitemconfirm('no');
			} else {	
				// Check if user wishes to add brand as not accepted brand before rejecting item
				DayPilot.Modal.confirm('Would you like to modify the the brand ' + brand + ' to &lsquo;NOT ACCEPTED&rsquo;', {theme: "modal_rounded", okText: "Yes", cancelText: "No" }).then(function(args){			
				console.log(args.result);
				if (args.result) {
					rejectitemconfirm('yes');
				} else {	
					rejectitemconfirm('no');
				}   
				});	
			}
		}
	},
		error: function(data) {
			rejectitemconfirm(id, brand, 'no');
		}
	});

	


	return false;

}

function rejectitemconfirm(addbrandreject){

	// Check if user wishes to add brand as not accepted brand before rejecting item

	var item_id  = $('#item-id').val();	
	var action = "reject";
	var review_note  = $('#review-note').val();	
	var brand  = $('#filter_by_brand').val();
	
	//clear up ssv error messages  
	$("#price-err").html('');
	$("#brand-err").html('');

	$.ajax({
		type: "POST",
		url: "./ajax/ajaxAcceptRejectItem.php",
		data:{itemid:item_id,brand:brand,note:review_note,action:action,addbrandreject:addbrandreject},
		dataType: 'json',
		cache: false,
		success: function(data) { 
			if(data.code =='404'){
				if(data.msg.email && data.msg.email!=''){
					DayPilot.Modal.alert(data.msg.email, {theme: "modal_rounded"}).then(function(args){			console.log(args.result);
					if (args.result) {
						$(location).attr("href", "review_items.php");
					}
					});	
				}
			}else{  
				$(location).attr("href", "review_items.php");
			}    
		},
		error: function(data){
			var errorMessage = data.status + ': ' + data.statusText;
			DayPilot.Modal.alert('Error - ' + errorMessage, {theme: "modal_rounded"});
		}
	});
  
	return false;

}

function plusSlides(n) {

  showSlides(slideIndex += n);
}

function showSlides(n) {

	var i;
	var slides = document.getElementsByClassName("mySlides");
	
	if (n > slides.length) {slideIndex = 1}    
	if (n < 1) {slideIndex = slides.length}
	for (i = 0; i < slides.length; i++) {
		slides[i].style.display = "none";  
	}
	slides[slideIndex-1].style.display = "block";  
}
</script>

<?php require 'inc/_global/views/footer_end.php'; ?>