<!-- 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 = "pintb";
$table_name_advance = "devop";
$table_name_sort = 'sortm';
$page_mac = "parent_pin.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';


/////////////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 pin LIKE :searchTerm";
    $placeholders[':searchTerm'] = "%$searchTerm%";
}

// 2. Determine sort order (default A-Z)
$sortOrder = 'macad ASC';



// 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 pin or password can be added for one Mac Address. reset it if you want to make default pin 0000.");</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 = "pintb";
    $page_m = "parent_pin.php";
    $ret = $db->select($table_name, '*', 'id = :id', '', [':id' => $idmy]);
    
    $page_no;
    $newmark = "0000";
	
	
	if($pages > 0){
	    $page_no = "&view=".$pages;
	}
	else{
	    $page_no = '';
	}
    

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


?>
<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 Parental PIN</h6>
                    <form method="post">
                        <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">Parental PIN</label>
                            <input type="text" name="pin" class="form-control date-white" placeholder="Parental PIN" required>
                        </div>
                        <button type="submit" name="submit" class="btn btn-primary">Save</button>
                    </form>
            </div>
        </div>
    </div>
</div>
<!-- Form End -->

<?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">
                            <button type="submit" class="btn btn-primary">Search</button>
                        </div>
                    </form>

                </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">Parental PIN/Password</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>Mac Address</th>
                                    <th>PIN</th>
                                    <th>Delete</th>
                                    <th>Reset pin</th>
                                </tr>
                            </thead>
                            <?php foreach ($res as $row) { 
							?>
                            <tbody>
                                <tr>
                                    <td><?=$row['id']; ?></a></td>
                                    <td><?=$row['macad'] ?></td>
                                    <td><?=($row['pin'] === "0000") ? "0000" : "****" ?></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 btn-warning m-2"
                                            href="<?php echo $page_mac; ?>?block=<?php echo $row['id']; ?><?php echo $selected_page; ?>">
                                            <i class="fa fa-recycle"></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>