<!-- index.php -->
<?php 
include ('includes/header.php');

$selected_uid = isset($_GET['uuid']) ? $_GET['uuid'] : '';
$get_macaddress = isset($_GET['mac']) ? $_GET['mac'] : '';

/////////cerent currunt page/////////
$currunt_page = isset($_GET['view']) ? $_GET['view'] : '';
$selected_page;

if($currunt_page > 0){
	 $selected_page = "&view=".$currunt_page;
}else{
	 $selected_page = '';
}
/////////cerent currunt page/////////	
//table name
$table_name = "ibof";
$table_name_advance = "devop";
$table_name_sort = 'sort';
$table_name_dns = "dns";
$page_user = "user_manage.php";
$pagemac = "mac_manage.php";


//table call
//$res = $db->select($table_name, '*', '', '');

//dns call
$resdns = $db->select($table_name_dns, '*', '', '');

//advance option db
$advance = $db->select($table_name_advance, '*', 'id = :id', '', [':id' => 1]);
$per_pagexx = !empty($advance[0]['maxpg']) ? $advance[0]['maxpg'] : '8';

//update call
@$resU = $db->select($table_name, '*', 'id = :id', '', [':id' => $_GET['update']]);

//sort table
$ressort = $db->select($table_name_sort, '*', '', '');
$sortval = $ressort[0]['sort'] ? : 'def';


$data_sort = ['sort' => 'def'];
$db->insertIfEmpty($table_name_sort, $data_sort);

/////////////Search and page aria////////////////////////////

$results_per_page = $per_pagexx;

if (isset($_GET['view'])) {
    $page = $_GET['view'];
} else {
    $page = 1;
}

$start_from = ($page - 1) * $results_per_page;


$searchTerm = isset($_GET['search']) ? $_GET['search'] : '';
$placeholders = [];
$searchQuery = '';

if (!empty($searchTerm)) {
    $searchQuery = "macad LIKE :searchTerm OR name LIKE :searchTerm";
    $placeholders[':searchTerm'] = "%$searchTerm%";
}

// 2. Determine sort order (default A-Z)
$sortOrder = 'name ASC';
switch ($sortval) {
        case 'def':
            $sortOrder = 'name ASC';
            break;
        case 'AtoZ':
            $sortOrder = 'name ASC';
            break;
        case 'ZtoA':
            $sortOrder = 'name DESC';
            break;
        case 'Mark_F':
            $sortOrder = 'mark DESC';
            break;
        case 'UNMark_F':
            $sortOrder = 'mark ASC';
            break;
        case 'new_F':
            $sortOrder = 'cdate DESC';
            break;
        case 'old_F':
            $sortOrder = 'cdate ASC';
            break;
        case 'newu_F':
            $sortOrder = 'udate DESC';
            break;
        case 'oldu_F':
            $sortOrder = 'udate ASC';
            break;
    
}

// 3. Pagination calculation
$countResult = $db->selectWithCount($table_name, "id", $searchQuery, $placeholders);
$totaleview = $countResult[0]['total'];
$total_pages = ceil($totaleview / $results_per_page);

// 4. Fetch records
$res = $db->select(
    $table_name,
    '*',
    $searchQuery,
    "$sortOrder LIMIT $start_from, $results_per_page", // directly insert integers
    $placeholders
);

/////////////////////////////////////////////////////////////

if(isset($_POST['submitU'])){
	unset($_POST['submitU']);
	$updateData = $_POST;
	$db->update($table_name, $updateData, 'id = :id',[':id' => $_GET['update']]);
	echo "<script>window.location.href='".$page_user."?status=ok$selected_page'</script>";
}

//submit new
if (isset($_POST['submit'])){
	unset($_POST['submit']);
	$db->insert($table_name, $_POST);
	$db->close();
	echo "<script>window.location.href='".$page_user."?status=ok'</script>";
}

//sort save
if(isset($_POST['submitS'])){
	unset($_POST['submitS']);
	$updateData = $_POST;
	$db->update($table_name_sort, $updateData, 'id = :id',[':id' => 1]);
	echo "<script>window.location.href='".$page_user."?status=ok'</script>";
}

//delete row
if(isset($_GET['delete'])){
	$db->delete($table_name, 'id = :id',[':id' => $_GET['delete']]);
	echo "<script>window.location.href='".$page_user."?status=ok'</script>";
}

if(isset($_GET['mark'])){
	mark($_GET['mark'],$currunt_page);
}

function mark($idmy,$page){
    global $db;
    $table_name = "ibof";
    $page_user = "user_manage.php";
    $ret = $db->select($table_name, '*', 'id = :id', '', [':id' => $idmy]);
    
    $page_no;
    $newmark;
	$mark = $ret[0]['mark'];
	
	if($mark == 0){
	    $newmark = 1;
	}else{
	    $newmark = 0;
	}
	
	if($page > 0){
	    $page_no = "&view=".$page;
	}
	else{
	    $page_no = '';
	}
    
    //$data = ['name' => $name,'macad' => $macad,'uuid' => $uuid,'username' => $username,'password' => $password,'cdate' => $cdate,'udate' => $udate,'mark' => $newmark];
    $data = ['mark' => $newmark];
    $db->update($table_name, $data, 'id = :id',[':id' => $idmy]);
	echo "<script>window.location.href='".$page_user."?status=ok$page_no'</script>";
    
}

function getdnsname($uuidmy){
    global $db;
    $ret = $db->select('dns', '*', 'uid = :uid', '', [':uid' => $uuidmy]);
    $dnsname =  $ret[0]['title'];
    $dnsurl =  $ret[0]['url'];
    
    if($dnsname =='' || $dnsname == null){
        return 'DNS missing ➤ '.$uuidmy;
    }else{
      return $dnsname .' ➤ '. $dnsurl;  
    }
    
    
}

function getCurrentDateTimeAuto() {
    $timezone = @date_default_timezone_get();
    if (!$timezone) {
        $timezone = 'UTC';
    }
    date_default_timezone_set($timezone);
    return date('Y-m-d H:i:s');
}

function PlaylistID() {
    $timezone = @date_default_timezone_get();
    if (!$timezone) {
        $timezone = 'UTC';
    }
    date_default_timezone_set($timezone);
    $time = date('Y-m-d H:i:s');
    $mix = md5($time).$time;
    return hash('sha256', $mix);
}



?>
<style>
.pagination-gap {
    margin-left: 2px;
    margin-right: 2px;
    background-color: red;
    color: white;
    padding: 5px 10px;
}

.pagination-red {
    margin-left: 2px;
    margin-right: 2px;
    background-color: red;
    color: white;
    text-align: center;
    padding: 5px 10px;
}

.text-color {
    color: white;
}

.pagination .btn-group {
    flex-wrap: wrap;
    /* Buttons wrap to next line on small screens */
    gap: 4px;
    /* Buttons අතර gap එක */
}

/* Mobile button size adjust */
@media (max-width: 768px) {
    .pagination .btn {
        padding: 6px 10px;
        font-size: 14px;
        margin-bottom: 2px;
    }
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function() {
    var macAddressInput = document.getElementById("mac_address");

    macAddressInput.addEventListener("input", function(e) {
        var value = e.target.value;
        value = value.replace(/[^a-fA-F0-9]/g, "").toUpperCase();

        var formattedValue = "";
        for (var i = 0; i < value.length; i++) {
            formattedValue += value[i];
            if ((i + 1) % 2 === 0 && i < value.length - 1) {
                formattedValue += ":";
            }
        }

        e.target.value = formattedValue;
    });
});
</script>
<?php if (isset($_GET['create'])){?>

<!-- Form Start -->
<div class="container-fluid pt-4 px-4">
    <div class="row g-4">
        <div class="col-12">
            <div class="bg-secondary rounded h-100 p-4">
                <h2 class="mb-4">Add New User</h6>
                    <form method="post">
                        <div class="mb-3">
                            <input type="hidden" name="plid" class="form-control" value="<?=PlaylistID(); ?>"
                                placeholder="PlaylistID" readonly>
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Playlist Name</label>
                            <input type="text" name="name" class="form-control" placeholder="Playlist Name">
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">DNS</label>

                            <select class="form-select mb-3" id="uuid" name="uuid">

                                <?php foreach ($resdns as $title): ?>
                                <option value="<?= htmlspecialchars($title['uid']); ?>"
                                    <?= $title['uid'] == $selected_uid ? 'selected' : ''; ?>>
                                    <?= htmlspecialchars($title['title']); ?> ➤ <?= htmlspecialchars($title['url']); ?>
                                </option>
                                <?php endforeach; ?>

                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">MAC Address</label>
                            <input type="text" name="macad" id="mac_address" value="<?=$get_macaddress ?>" class="form-control"
                                placeholder="MAC Address">
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Username</label>
                            <input type="text" name="username" class="form-control" placeholder="Username">
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Password</label>
                            <input type="text" name="password" class="form-control" placeholder="Password">
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Date added</label>
                            <input type="text" name="cdate" class="form-control" value="<?=getCurrentDateTimeAuto(); ?>"
                                placeholder="Password" readonly>
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Updated date</label>
                            <input type="text" name="udate" class="form-control" value="<?=getCurrentDateTimeAuto(); ?>"
                                placeholder="Password" readonly>
                        </div>
                        <div class="mb-3" type="hidden">
                            <input type="hidden" name="mark" class="form-control" value="0" placeholder="Password"
                                readonly>
                        </div>
                        <button type="submit" name="submit" class="btn btn-primary">Save</button>
                    </form>
            </div>
        </div>
    </div>
</div>
<!-- Form End -->

<?php }else if (isset($_GET['update'])){ ?>
<div class="container-fluid pt-4 px-4">
    <div class="row g-4">
        <div class="col-12">
            <div class="bg-secondary rounded h-100 p-4">
                <h2 class="mb-4">Edit User</h6>
                    <form method="post">
                        <div class="mb-3">
                            <input type="hidden" name="plid" class="form-control" value="<?=$resU[0]['plid'] ?>"
                                placeholder="PlaylistID" readonly>
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Playlist Name</label>
                            <input type="text" name="name" class="form-control" value="<?=$resU[0]['name'] ?>"
                                placeholder="Playlist Name">
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">DNS</label>
                            <select class="form-select mb-3" id="uuid" name="uuid">

                                <?php foreach ($resdns as $title): ?>
                                <option value="<?= htmlspecialchars($title['uid']); ?>"
                                    <?= $title['uid'] == $selected_uid ? 'selected' : ''; ?>>
                                    <?= htmlspecialchars($title['title']); ?> ➤ <?= htmlspecialchars($title['url']); ?>
                                </option>
                                <?php endforeach; ?>

                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">MAC Address</label>
                            <input type="text" name="macad" id="mac_address" class="form-control"
                                value="<?=$resU[0]['macad'] ?>" placeholder="MAC Address">
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Username</label>
                            <input type="text" name="username" class="form-control" value="<?=$resU[0]['username'] ?>"
                                placeholder="Username">
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Password</label>
                            <input type="text" name="password" class="form-control" value="<?=$resU[0]['password'] ?>"
                                placeholder="Password">
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Date added</label>
                            <input type="text" name="cdate" class="form-control" placeholder="Password"
                                value="<?=$resU[0]['cdate'] ?>" readonly>
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Updated date</label>
                            <input type="text" name="udate" class="form-control" value="<?=getCurrentDateTimeAuto(); ?>"
                                placeholder="Password" readonly>
                        </div>
                        <div class="mb-3" type="hidden">
                            <input type="hidden" name="mark" class="form-control" value="<?=$resU[0]['mark'] ?>"
                                placeholder="Password" readonly>
                        </div>
                        <button type="submit" name="submitU" class="btn btn-primary">Update</button>
                    </form>
            </div>
        </div>
    </div>
</div>
<?php }else if (isset($_GET['mark'])){ ?>

<?php }else{?>

<!-- Table Start -->
<div class="container-fluid pt-4 px-4">
    <div class="row g-4">
        <div class="col-12">
            <div class="bg-secondary rounded h-100 p-4">
                <h6 class="mb-4">Search User</h6>
                <div class="d-flex align-items-center gap-2">

                    <!-- Search form -->
                    <form method="get" class="mb-0 flex-grow-1">
                        <div class="input-group w-100">
                            <input type="text" name="search" class="form-control"
                                placeholder="Search by Mac Address or Title">
                            <button type="submit" class="btn btn-primary">Search</button>
                        </div>
                    </form>

                    <!-- Sort form -->
                    <div class="nav-item dropdown">
                        <a href="#" class="nav-link dropdown-toggle" data-bs-toggle="dropdown">
                            <img class="rounded-circle me-lg-2" src="img/sort.png" alt=""
                                style="width: 40px; height: 40px;">
                        </a>
                        <div class="dropdown-menu dropdown-menu-end bg-secondary border-0 rounded-0 rounded-bottom m-0">
                            
                            <form method="post" class="mb-0">
                                <input type="hidden" name="sort" class="form-control" value="def">
                                <button type="submit" name="submitS" class="dropdown-item" style="color: red;">
                                    Default
                                </button>
                            </form>

                            <!-- Sort 1 -->
                            <form method="post" class="mb-0">
                                <input type="hidden" name="sort" class="form-control" value="AtoZ">
                                <button type="submit" name="submitS" class="dropdown-item" style="color: red;">
                                    A to Z
                                </button>
                            </form>

                            <!-- Sort 2 -->
                            <form method="post" class="mb-0">
                                <input type="hidden" name="sort" class="form-control" value="ZtoA">
                                <button type="submit" name="submitS" class="dropdown-item" style="color: red;">
                                    Z to A
                                </button>
                            </form>

                            <!-- Sort 3 -->
                            <form method="post" class="mb-0">
                                <input type="hidden" name="sort" class="form-control" value="Mark_F">
                                <button type="submit" name="submitS" class="dropdown-item" style="color: red;">
                                    Marked First
                                </button>
                            </form>
                            
                            <form method="post" class="mb-0">
                                <input type="hidden" name="sort" class="form-control" value="UNMark_F">
                                <button type="submit" name="submitS" class="dropdown-item" style="color: red;">
                                    Unmarked First
                                </button>
                            </form>
                            
                            <form method="post" class="mb-0">
                                <input type="hidden" name="sort" class="form-control" value="new_F">
                                <button type="submit" name="submitS" class="dropdown-item" style="color: red;">
                                    Newest First
                                </button>
                            </form>
                            
                            <form method="post" class="mb-0">
                                <input type="hidden" name="sort" class="form-control" value="old_F">
                                <button type="submit" name="submitS" class="dropdown-item" style="color: red;">
                                    Oldest First
                                </button>
                            </form>
                            
                            <form method="post" class="mb-0">
                                <input type="hidden" name="sort" class="form-control" value="newu_F">
                                <button type="submit" name="submitS" class="dropdown-item" style="color: red;">
                                    Newest Updated First
                                </button>
                            </form>
                            
                            <form method="post" class="mb-0">
                                <input type="hidden" name="sort" class="form-control" value="oldu_F">
                                <button type="submit" name="submitS" class="dropdown-item" style="color: red;">
                                    Oldest Updated First
                                </button>
                            </form>

                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid pt-4 px-4">
    <div class="row g-4">
        <div class="col-12">
            <div class="bg-secondary rounded h-100 p-4">
                <h2 class="mb-4">Current User</h6>
                    <div class="text-end">
                        <a type="button" href="./<?=$page_user ?>?create" class="btn btn-square btn-primary m-2"><i
                                class="fa fa-plus"></i></a>
                    </div>

                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Playlist Name</th>
                                    <th>DNS</th>
                                    <th>Mac Address</th>
                                    <th>Mac Settings</th>
                                    <th>Edit</th>
                                    <th>Delete</th>
                                    <th>Mark</th>
                                </tr>
                            </thead>
                            <?php foreach ($res as $row) {
							?>
                            <tbody>
                                <tr>
                                    <td><?=$row['id']; ?></a></td>
                                    <td><?=$row['name'] ?></a></td>
                                    <td><?=getdnsname($row['uuid'])?></a></td>
                                    <td><?=$row['macad'] ?></td>
                                    <td><a class="btn btn-square btn-warning m-2"
                                            href="<?php echo $pagemac; ?>?create&mac=<?php echo $row['macad']; ?>&name=<?php echo $row['name']; ?>">
                                            <i class="fa fa-id-card"></i>
                                        </a></td>
                                    <td><a class="btn btn-square btn-success m-2"
                                            href="<?php echo $page_user; ?>?update=<?php echo $row['id']; ?>&uuid=<?php echo $row['uuid']; ?><?php echo $selected_page; ?>">
                                            <i class="fa fa-pencil-square-o"></i>
                                        </a></td>
                                    <td><a class="btn btn-square btn-primary m-2" href="#"
                                            data-href="<?php echo $page_user; ?>?delete=<?php echo $row['id']; ?>"
                                            data-bs-toggle="modal" data-bs-target="#confirm-delete">
                                            <i class="fa fa-trash"></i>
                                        </a></td>

                                    <td>
                                        <a name="submitmark"
                                            class="btn btn-square <?=($row['mark'] == 1 ? 'btn-warning' : 'btn-outline-warning')?> m-2"
                                            href="<?php echo $page_user; ?>?mark=<?php echo $row['id']; ?><?php echo $selected_page; ?>">
                                            <i class="fa fa-star"></i>
                                        </a>
                                    </td>

                                </tr>
                            </tbody>
                            <?php
							}?>
                        </table>
                    </div>
            </div>
        </div>
    </div>
</div>



<div class="container-fluid pt-4 px-4">
    <div class="row g-4">
        <div class="col-12">
            <div class="bg-secondary rounded h-100 p-4">
                <?php
                        $is_mobile = false;
                        if (preg_match('/(android|iphone|ipad|ipod|blackberry|iemobile|opera mini)/i', $_SERVER['HTTP_USER_AGENT'])) {
                            $is_mobile = true;
                        }
                        
                        $max_window = $is_mobile ? 3 : 5; // mobile -> 3, desktop -> 5
                        ?>
                <style>
                @media (max-width: 768px) {

                    .pagination .btn-primary,
                    .pagination .btn-warning {
                        padding: 5px 8px;
                    }
                }
                </style>

                <?php if ($results_per_page < $totaleview) { ?>
                <div class="pagination">
                    <div class="btn-toolbar" role="toolbar" aria-label="Pagination">
                        <div class="btn-group me-2" role="group" aria-label="Pagination group">

                            <?php 
                                    $window_start = max(1, $page - floor($max_window / 2));
                                    $window_end = min($total_pages, $window_start + $max_window - 1);
                        
                                    if ($window_end - $window_start + 1 < $max_window) {
                                        $window_start = max(1, $window_end - $max_window + 1);
                                    }
                        
                                    // Previous button
                                    if ($page > 1) { 
                                    ?>
                            <a class="btn btn-primary" href='<?=$pagem ?>?view=<?=$page - 1?><?=$searchTerm?>'>
                                <?=$is_mobile ? '&lt;' : 'Previous'?>
                            </a>
                            <?php } ?>

                            <!-- First pages if window doesn't start from 1 -->
                            <?php if ($window_start > 1) { ?>
                            <a class="btn btn-primary" href='<?=$pagem ?>?view=1<?=$searchTerm?>'>1</a>
                            <?php if ($window_start > 2) echo "..."; ?>
                            <?php } ?>

                            <!-- Page window -->
                            <?php for ($i = $window_start; $i <= $window_end; $i++) { ?>
                            <a class="btn <?php echo $i == $page ? 'btn-warning' : 'btn-primary'; ?>"
                                href='<?=$pagem ?>?view=<?=$i?><?=$searchTerm?>'><?=$i?></a>
                            <?php } ?>

                            <!-- Last pages if window doesn't reach the end -->
                            <?php if ($window_end < $total_pages) { ?>
                            <?php if ($window_end < $total_pages - 1) echo "..."; ?>
                            <a class="btn btn-primary"
                                href='<?=$pagem ?>?view=<?=$total_pages?><?=$searchTerm?>'><?=$total_pages?></a>
                            <?php } ?>

                            <!-- Next button -->
                            <?php if ($page < $total_pages) { ?>
                            <a class="btn btn-primary" href='<?=$pagem ?>?view=<?=$page + 1?><?=$searchTerm?>'>
                                <?=$is_mobile ? '&gt;' : 'Next'?>
                            </a>
                            <?php } ?>

                        </div>
                    </div>
                </div>
                <?php } ?>

            </div>
        </div>
    </div>
</div>
<!-- Table End -->

<?php }?>
<!-- Footer Start -->
<?php include ('includes/footer.php');?>
<!-- Footer End -->
</body>

</html>