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

$selected_mac = isset($_GET['mac']) ? $_GET['mac'] : '';
$selected_name = isset($_GET['name']) ? $_GET['name'] : '';


/////////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 = "mactb";
$table_name_advance = "devop";
$table_name_sort = 'sortm';
$page_mac = "mac_manage.php";

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


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

//duplocate find
$duplicates = $db->findDuplicates($table_name, "macad");

//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 = 'blok DESC';
            break;
        case 'UNMark_F':
            $sortOrder = 'blok 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_mac."?status=ok$selected_page'</script>";
}

//submit new
if (isset($_POST['submit'])){
	unset($_POST['submit']);
	
	$macAddress = strtolower($_POST['macad']);
	
	if ($db->nameExists($table_name, "LOWER(macad)", $macAddress)) {
        echo '<script>alert("Only one subscription period can be added for one Mac Address. Edit it if you want to make any changes.");</script>';
    } else {
        $db->insert($table_name, $_POST);
    	$db->close();
    	echo "<script>window.location.href='".$page_mac."?status=ok'</script>";
    }
}

//delete row
if(isset($_GET['delete'])){
	$db->delete($table_name, 'id = :id',[':id' => $_GET['delete']]);
	echo "<script>window.location.href='".$page_mac."?status=2'</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_mac."?status=ok'</script>";
}

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

function block($idmy,$pages){
    global $db;
    $table_name = "mactb";
    $page_m = "mac_manage.php";
    $ret = $db->select($table_name, '*', 'id = :id', '', [':id' => $idmy]);
    
    $page_no;
    $newmark;
	$mark = $ret[0]['blok'];
	
	if($mark == 0){
	    $newmark = 1;
	}else{
	    $newmark = 0;
	}
	
	if($pages > 0){
	    $page_no = "&view=".$pages;
	}
	else{
	    $page_no = '';
	}
    

    $data = ['blok' => $newmark];
    $db->update($table_name, $data, 'id = :id',[':id' => $idmy]);
	echo "<script>window.location.href='".$page_m."?status=ok$page_no'</script>";
    
}


function checkmac(){
    global $db;
    $table_name = "mactb";
}

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


?>
<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;
    }
}

input.date-white::-webkit-calendar-picker-indicator {
    filter: invert(1);       /* invert color to white */
    opacity: 1;              /* ensure visible */
}
</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 MAC</h6>
                    <form method="post">
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Identification</label>
                            <input type="text" name="name" value="<?=$selected_name; ?>" class="form-control" placeholder="Identification" required>
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">MAC Address</label>
                            <input type="text" name="macad" id="mac_address" value="<?=$selected_mac; ?>" class="form-control" placeholder="MAC Address" required>
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">App Expired Date</label>
                            <input type="date" name="expir" class="form-control date-white" placeholder="App Expired Date" required>
                        </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="blok" 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 MAC</h6>
                    <form method="post">
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Identification</label>
                            <input type="text" name="name" class="form-control" value="<?=$resU[0]['name'] ?>" placeholder="Identification" required>
                        </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" required>
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">App Expired Date</label>
                            <input type="date" name="expir" class="form-control date-white" value="<?=$resU[0]['expir'] ?>" placeholder="App Expired Date" required>
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Date added</label>
                            <input type="text" name="cdate" class="form-control" value="<?=$resU[0]['cdate'] ?>"
                                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="blok" class="form-control" value="<?=$resU[0]['blok'] ?>" placeholder="Password"
                                readonly>
                        </div>
                        <button type="submit" name="submitU" class="btn btn-primary">Save</button>
                    </form>
            </div>
        </div>
    </div>
</div>
<?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 Mac</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 Identification Name">
                            <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;">
                                    Blocked 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;">
                                    Unblocked 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 MAC</h6>
                    <div class="text-end">
                        <a type="button" href="./<?=$page_mac ?>?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>Identification Name</th>
                                    <th>Mac Address</th>
                                    <th>App Expired Date</th>
                                    <th>Edit</th>
                                    <th>Delete</th>
                                    <th>Block</th>
                                </tr>
                            </thead>
                            <?php foreach ($res as $row) {
							?>
                            <tbody>
                                <tr>
                                    <td><?=$row['id']; ?></a></td>
                                    <td><?=$row['name'] ?></a></td>
                                    <td><?=$row['macad'] ?></td>
                                    <td><?=$row['expir'] ?></td>
                                    
                                    <td><a class="btn btn-square btn-success m-2" href="<?php echo $page_mac; ?>?update=<?php echo $row['id']; ?>">
                                            <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_mac; ?>?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['blok'] == 1 ? 'btn-warning' : 'btn-outline-warning')?> m-2"
                                            href="<?php echo $page_mac; ?>?block=<?php echo $row['id']; ?><?php echo $selected_page; ?>">
                                            <i class="<?=($row['blok'] == 1 ? 'fa fa-lock' : 'fa fa-unlock-alt')?>"></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>