<?php 
ini_set('display_errors', 1);
$db = new SQLite3('./api/.db.db');

$db->exec("CREATE TABLE IF NOT EXISTS store(id INTEGER PRIMARY KEY NOT NULL, added_date VARCHAR(50), description VARCHAR(50), icon VARCHAR(50), app_id VARCHAR(50), name VARCHAR(50), url VARCHAR(50), version VARCHAR(50), version_code VARCHAR(50), sort INTEGER)");

$res = $db->query('SELECT * FROM store ORDER BY sort ASC');

if (empty($_POST['version_code'])) {
	@$pin='0000';
}else{
	@$pin=$_POST['version_code'];
}

@$base64 = base64_encode($_POST['description']);

$uploadPath = "uploads/icons";

if(isset($_GET['delete'])){
    global $uploadPath;
    // select icons to delete from storage
    $rowQuery = $db->query("SELECT icon FROM store WHERE id = ". $_GET['delete']);
    $iconsToDelete = explode(';; ', $rowQuery->fetchArray()[0]);
    // delete app
	$response = $db->exec("DELETE FROM store WHERE id=".$_GET['delete']);
    if($response) {
        // delete icon from storage
        foreach($iconsToDelete as $iconToDelete) {
            if(!empty($iconToDelete)) {
                $iconToDelete = $uploadPath .'/'. $iconToDelete;
                if(file_exists($iconToDelete)) {
                    unlink($iconToDelete);
                }
            }
        }
        header("Location: store.php");
    }
}

$errors = [];

function checkIconExtension($files) {
    global $uploadPath;
    $extensions = ["jpeg","jpg","png","gif"];
    $errors = [];
    foreach($files["tmp_name"] as $key => $tmp_name) {
        // old_icon_count is a hidden input in update app
        if(isset($_POST['old_icon_count']) && $_POST['old_icon_count'] > 0) {
            break;
        }

        $file_tmp = $files["tmp_name"][$key];
        if(empty($file_tmp)) {
            // no icon uploded
            $errors[] = 'icon is required';
            break;
        }

        $file_name = $files["name"][$key];
        $ext = pathinfo($file_name, PATHINFO_EXTENSION);

        if(!in_array($ext, $extensions)) {
            $errors[] = "The file ". $file_name ." must be ". implode(", ", $extensions);
        }
    }
    return $errors;
}

function uploadIcons($files) {
    global $uploadPath;
    $icon = [];
    foreach($files["tmp_name"] as $key => $tmp_name) {
        $file_name = $files["name"][$key];
        $file_tmp = $files["tmp_name"][$key];
        if(empty($file_tmp)) {
            // no icon uploded
            break;
        }
        $ext = pathinfo($file_name, PATHINFO_EXTENSION);

        if(file_exists($uploadPath ."/". $file_name)) {
            $basename = basename($file_name, ".". $ext);
            $file_name = $basename ."-". time() .".". $ext;
        }

        move_uploaded_file($file_tmp, $uploadPath ."/". $file_name);
        $icon[] = $file_name;
    }
    return $icon;
}

if(isset($_POST['store'])) {
    $errors = checkIconExtension($_FILES["icon"]);
    if(count($errors) == 0) {
        $icon = uploadIcons($_FILES["icon"]);
        $sortQuery = $db->query('SELECT MAX(id) FROM store');
        $sort = $sortQuery->fetchArray()[0] + 1;
        $db->exec("INSERT INTO store(added_date,description,icon,name,url,version,version_code,sort) VALUES('".date('Y m d')."','".$base64."','".implode(";; ", $icon)."','".$_POST['name']."','".$_POST['url']."','".$_POST['version']."','".$pin."',$sort)");
        header("Location: store.php");
    }
}

@$resU = $db->query("SELECT * FROM store WHERE id='{$_GET['update']}'");
@$rowU=$resU->fetchArray();
if (isset($_POST['storeU'])){
    $errors = checkIconExtension($_FILES["icon"]);
    if(count($errors) == 0) {
        $icon = uploadIcons($_FILES["icon"]);
        $oldIcon = explode(';; ', $rowU['icon']);
        $newIcon = array_merge((empty($oldIcon[0]) ? [] : $oldIcon), $icon);
        $db->exec("UPDATE store SET added_date='".date('Y-m-d')."',description='{$base64}',icon='".implode(";; ", $newIcon)."',name='{$_POST['name']}',url='{$_POST['url']}',version='{$_POST['version']}',version_code='{$pin}'WHERE id='{$_POST['update']}'");
        header("Location: store.php");
    }
}

include ('includes/header.php');
?>

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content" style="background-color: black;">
			<div class="modal-header">
				<h2 style="color: white;">Confirm</h2>
			</div>
			<div class="modal-body" style="color: white;">
				Do you really want to delete?
			</div>
			<div class="modal-footer" style="background-color: black;">
				<button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
				<a style="color: white;" class="btn btn-danger btn-ok">Delete</a>
			</div>
		</div>
	</div>
</div>
<div class="has-sidebar-left has-sidebar-tabs">
    <div class="container-fluid relative animatedParent animateOnce p-lg-5">

<?php
if (isset($_GET['create'])){

//create form
?>

        <div class="col-md-8 mx-auto">
            <div class="card-body">
                <div class="card bg-primary text-white">
                    <div class="card-header card-header-warning">
                        <center>
                            <h2><i class="icon icon-window-restore"></i> Add Store Config</h2>
                        </center>
                    </div>

                    <div class="card-body">
                            <form method="post" enctype="multipart/form-data">
                                <div class="form-group">
                                    <label class="form-label " for="version" >Category Name</label>
                                    <input class="form-control" id="version" name="version" value="Main" type="text"/>
                                </div>   
                                <div class="form-group">
                                    <label class="form-label " for="name" >App Name</label>
                                    <input class="form-control" id="name" name="name" value="" type="text"/>
                                </div>

                                <div class="form-group">
                                    <label class="form-label " for="url" >App URL</label>
                                    <input class="form-control" id="url" name="url" value="" type="text"/>
                                </div>
                                <div class="form-group">
                                    <label class="form-label " for="icon" >App Icon</label>
                                    <input class="form-control" id="icon" name="icon[]" value="" type="file" multiple accept="image/png, image/jpeg, image/jpg, image/gif"/>
                                    <?php
                                        if(count($errors) > 0) {
                                            foreach($errors as $error) {
                                                echo '<h5 style="color: red !important">'. $error . '</h5>';
                                            }
                                        }
                                    ?>
                                </div>             
                                <div class="form-group">
                                    <label class="form-label " for="description" >App Description</label>
									<textarea rows="6" class="form-control" id="description" name="description" type="text"/></textarea>
                                </div>
                                <div class="form-group">
                                    <label class="form-label " for="version_code" >Category Pin (Blank For None)</label>
                                    <input class="form-control" id="version_code" name="version_code" value="" type="text"/>
                                </div>       
                                <div class="form-group">
                                    <center>
                                        <button class="btn btn-info " name="store" type="submit">
                                            <i class="icon icon-check"></i> Submit
                                        </button>
                                    </center>
                                </div>
                            </form>
                    </div>
                </div>
            </div>
        </div>
<?php 
}else if (isset($_GET['update'])){ 

//update form
?>

        <div class="col-md-8 mx-auto">
            <div class="card-body">
                <div class="card bg-primary text-white">
                    <div class="card-header card-header-warning">
                        <center>
                            <h2><i class="icon icon-window-restore"></i> Add Store Config</h2>
                        </center>
                    </div>

                    <div class="card-body">
                            <form method="post" enctype="multipart/form-data">
                                <div class="form-group">
                                    <label class="form-label " for="version" >Category Name</label>
                                    <input class="form-control" id="version" name="version" value="<?=$rowU['version']?>" type="text" />
                                </div>   
                                <div class="form-group">
                                    <label class="form-label " for="name" >App Name</label>
                                    <input class="form-control" id="name" name="name" value="<?=$rowU['name']?>" type="text" />
                                </div>

                                <div class="form-group">
                                    <label class="form-label " for="url" >App URL</label>
                                    <input class="form-control" id="url" name="url" value="<?=$rowU['url']?>" type="text" />
                                </div>
                                <div class="form-group">
                                    <label class="form-label " for="icon" >App Icon</label>
                                    <div id="iconList" data-appid="<?=$rowU['id']?>">
                                        <?php
                                            $icons = explode(';; ', $rowU['icon']);
                                            foreach($icons as $icon) {
                                                if($icon) {
                                                    echo '<div class="iconDiv"><img src="'. $uploadPath .'/'. $icon .'"><span class="iconDelete" data-icon="'. $icon .'">✖</span></div>';
                                                }
                                            }
                                        ?>
                                    </div>
                                    <input type="hidden" id="oldIconCount" name="old_icon_count"  value="<?=empty($icons[0]) ? 0 : count($icons)?>">
                                </div>
                                <div class="form-group">
                                    <label class="form-label " for="icon" >New App Icon</label>
                                    <input class="form-control" id="icon" name="icon[]" value="" type="file" multiple accept="image/png, image/jpeg, image/jpg, image/gif"/>
                                    <?php
                                        if(count($errors) > 0) {
                                            foreach($errors as $error) {
                                                echo '<h5 style="color: red !important">'. $error . '</h5>';
                                            }
                                        }
                                    ?>
                                </div>     
                                <div class="form-group">
                                    <label class="form-label " for="description" >App Description</label>
                                    <textarea rows="6" class="form-control" id="description" name="description" type="text"/><?=base64_decode($rowU['description'])?></textarea>
                                </div>
                                <div class="form-group">
                                    <label class="form-label " for="version_code" >Category Pin (Blank For None)</label>
                                    <input class="form-control" id="version_code" name="version_code" value="<?=$rowU['version_code']?>" type="text" />
                                </div>  
								<input type="hidden" name="update"  value="<?=$_GET['update']?>">
                                <div class="form-group">
                                    <center>
                                        <button class="btn btn-info " name="storeU" type="submit">
                                            <i class="icon icon-check"></i> Submit
                                        </button>
                                    </center>
                                </div>
                            </form>
                    </div>
                </div>
            </div>
        </div>

<?php
 }else{
//main table/form
	 ?>

        <div class="col-lg mx-auto">
            <div class="card-body">
                <div class="card bg-primary text-white">
                    <div class="card-header card-header-warning">
                        <center>
                            <h2><i class="icon icon-window-restore"></i>Manage App Store</h2>
                        </center>
                    </div>

                    <div class="card-body">
                        <div class="col-12">
                        	<center>
	        					<a id="button" href="./store.php?create" class="btn btn-info">Add apps</a>
	        				</center>
    					</div>

    					<hr>

						<div class="table-responsive">
							<table id="storeTable" class="table table-sm">
							<thead style="color:white!important">
								<tr>
                                <th></th>
								<th>Icon</th>
								<th>Name</th>
								<th>Description</th>
								<th>URL</th>
								<th>Date added</th>
								<th>Edit</th>
								<th>Delete</th>
								</tr>
							</thead>
                            <tbody class="bg-white">
							<?php 
                            while ($row = $res->fetchArray()) {
                                $icons = explode(';; ', $row['icon']);
                            ?>
								<tr data-rowid="<?=$row['id'];?>">
                                    <td><span class="ui-icon ui-icon-arrowthick-2-n-s"></span></td>
                                    <td>
                                        <div class="slider slider-store">
                                            <div class="wrapper">
                                                <div id="items">
                                                    <?php
                                                        foreach($icons as $icon) {
                                                            echo '<span class="slide">';
                                                            if($icon) {
                                                                echo '<img src="'. $uploadPath .'/'. $icon .'" style="height:75px;width:auto!important;" alt="">';
                                                            } else {
                                                                echo '<img src="img/no-img-available.png" style="height:75px;width:auto!important;" alt="">';
                                                            }
                                                            echo '</span>';
                                                        }
                                                    ?>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                    <td><?=$row['name'] ?></td>
                                    <td><?=base64_decode($row['description'])?></td>
                                    <td><?=$row['url'] ?></td>
                                    <td><?=$row['added_date'] ?></td>
                                    <td><a class="btn btn-info btn-ok" href="./store.php?update=<?=$row['id'] ?>"></i>Edit</a></td>
                                    <td><a class="btn btn-danger btn-ok" href="#" data-href="./store.php?delete=<?=$row['id'] ?>" data-toggle="modal" data-target="#confirm-delete">Remove</a></td>
								</tr>
							<?php }?>
							</tbody>
							</table>
						</div>
					</div>
				</div>
			</div>
		</div>
<?php }?>
	</div>
</div>

<?php include ('includes/footer.php');?>

<script>
	$('#confirm-delete').on('show.bs.modal', function(e) {
	    $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
	});

    $(function() {
        $("#storeTable").sortable({
            items: 'tbody>tr',
            placeholder: 'ui-state-highlight',
            opacity: '0.55',
            helper: function(e, ui) {
                ui.children().each(function() {
                    $(this).width($(this).width());
                });
                return ui;
            },
            stop: function(event, ui) {
                let itemsSorted = [];
                $(this).find('tbody>tr').each(function(index, elem) {
                    itemsSorted.push($(elem).data('rowid'));
                });
                $.ajax('requests.php', {
                    type: 'POST',
                    data: {request_type : 'sortApps', itemsSorted : itemsSorted}
                });
            }
        });

        $(".iconDelete").click((e) => {
            let appid = $(e.target).closest('#iconList').data('appid');
            let icon = $(e.target).data('icon');
            $.ajax('requests.php', {
                type: 'POST',
                data: {request_type : 'deleteIcon', appid, icon},
                success: (resp) => {
                    if(resp) {
                        $(e.target).closest('.iconDiv').remove();
                        $('#oldIconCount').val(parseInt($('#oldIconCount').val()) - 1);
                    } else {
                        alert('Error while trying to delete the icon');
                    }
                }
            });
        });
    });

</script>

</body>
</html>