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



/////////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_advance = "devop";
$table_name = "menualusers";
$table_name_sort = 'sort';
$page_panel_user = "panel_user.php";

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

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



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

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


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

// 2. Determine sort order (default A-Z)
$sortOrder = 'title ASC';
switch ($sortval) {
        case 'def':
            $sortOrder = 'title ASC';
            break;
        case 'AtoZ':
            $sortOrder = 'title ASC';
            break;
        case 'ZtoA':
            $sortOrder = 'title 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_panel_user."?status=1'</script>";
}

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

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


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

//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_panel_user."?status=ok'</script>";
}

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

function block($idmy,$pages){
    global $db;
    $table_name = "menualusers";
    $page_m = "panel_user.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>";
    
}

?>
<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>
<?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" id="userForm">
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Title</label>
                            <input type="text" name="title" class="form-control" placeholder="Title" required>
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">UserName</label>
                            <input type="text" name="username" class="form-control" placeholder="UserName" required>
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Password</label>
                            <input type="text" name="password" class="form-control" placeholder="Password" required>
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Expire</label>
                            <input type="date" name="expire_date" class="form-control date-white" placeholder="Expire" required>
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Maximum devices</label>
                            <input type="number" name="quota" class="form-control" placeholder="Login quota" required>
                            <div id="emailHelp" class="form-text">Applying 1970 makes it unlimited..
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Remaining devices</label>
                            <input type="number" name="rquota" class="form-control" placeholder="Login quota" readonly>
                        </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>
                         <button type="button" id="autoFill" class="btn btn-primary">Auto Generate</button>
                    </form>
            </div>
        </div>
    </div>
</div>


<script>
// Random number generator
function randomNumbers(length) {
    let result = '';
    let chars = '0123456789';
    for (let i = 0; i < length; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
}

// Random alphanumeric generator
function randomString(length) {
    let result = '';
    let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    for (let i = 0; i < length; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
}

document.getElementById("autoFill").addEventListener("click", function () {
    let form = document.getElementById("userForm");

    // Title → USER_ + 8 random digits
    form.title.value = "USER_" + randomNumbers(8);

    // Username & Password → random 8 alphanumeric
    form.username.value = randomString(8);
    form.password.value = randomString(8);

    // Quota → always 3
    form.quota.value = "1";
    
    form.rquota.value = "1";

    // Expire date → keep empty (do nothing)
    form.expire_date.value = "";
});

document.addEventListener("DOMContentLoaded", function () {
    const quotaInput = document.querySelector("input[name='quota']");
    const rquotaInput = document.querySelector("input[name='rquota']");

    quotaInput.addEventListener("input", function () {
        rquotaInput.value = quotaInput.value; // copy quota → rquota
    });
});
</script>
<!-- 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" id="userForm">
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Title</label>
                            <input type="text" name="title" class="form-control" value="<?=$resU[0]['title'] ?>"
                                placeholder="Title" required>
                        </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" required>
                        </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" required>
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Expire</label>
                            <input type="date" name="expire_date" class="form-control date-white"
                                value="<?=$resU[0]['expire_date'] ?>" placeholder="Expire" required>
                        </div>
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Maximum devices</label>
                            <input type="number" name="quota" class="form-control" value="<?=$resU[0]['quota'] ?>"
                                placeholder="Login quota" required readonly>
                            <div id="emailHelp" class="form-text">Applying 1970 makes it unlimited..
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="exampleInputEmail1" class="form-label">Remaining devices</label>
                            <input type="number" name="rquota" class="form-control" placeholder="Login quota" value="<?=$resU[0]['rquota'] ?>" readonly 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">Update</button>
                        <button type="button" id="autoFill" class="btn btn-primary">Maximum devices +1</button>
                    </form>
            </div>
        </div>
    </div>
</div>

<script>


document.getElementById("autoFill").addEventListener("click", function () {
    let form = document.getElementById("userForm");

    // quota අගය 1 එක්ක යාවත්කාලීන කිරීම
    let currentQuota = parseInt(form.quota.value) || 0; // value එක number එකකට පරිවර්තනය කර නොමැතිනම් 0 ගන්න
    form.quota.value = currentQuota + 1;

    // rquota අගය 1 එක්ක යාවත්කාලීන කිරීම
    let currentRQuota = parseInt(form.rquota.value) || 0;
    form.rquota.value = currentRQuota + 1;
});


</script>
<?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 Users</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 Title or UserName">
                            <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 Users</h6>
                    <div class="text-end">
                        <a type="button" href="./<?=$page_panel_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>Title</th>
                                    <th>UserName</th>
                                    <th>Password</th>
                                    <th>Expire</th>
                                    <th>Date added</th>
                                    <th>Maximum devices</th>
                                    <th>Edit</th>
                                    <th>Delete</th>
                                    <th>Block</th>
                                    <th>Copy</th>
                                </tr>
                            </thead>
                            <?php foreach ($res as $row) {
							?>
                            <tbody>
                                <tr>
                                    <td><?=$row['id']; ?></a></td>
                                    <td><?=$row['title'] ?></a></td>
                                    <td><?=$row['username'] ?></td>
                                    <td><?=$row['password'] ?></td>
                                    <td>
                                        <?php 
                                            $expireDate = new DateTime($row['expire_date']);
                                            $today = new DateTime();
                                            $diff = $today->diff($expireDate);
                                    
                                            if ($expireDate < $today) {
                                                // Already expired
                                                echo $row['expire_date'] . " <span style='color:red;'>(Expired)</span>";
                                            } else {
                                                $daysLeft = $diff->days;
                                    
                                                if ($daysLeft <= 5) {
                                                    $color = "orange"; // කහ පාට
                                                } elseif ($daysLeft <= 20) {
                                                    $color = "deepskyblue"; // ලා නිල්
                                                } else {
                                                    $color = "green"; // කොළ
                                                }
                                    
                                                echo $row['expire_date'] . " <span style='color:$color;'>($daysLeft days left)</span>";
                                            }
                                        ?>
                                    </td>
                                    <td><?=$row['cdate'] ?></td>
                                    <td>
                                        <?php if ($row['quota'] == '1970'): ?>
                                            <span style="color:orange">No Limit</span>
                                        <?php else: ?>
                                            <?php if ($row['rquota'] == '0'): ?>
                                                <?= "Maximum " . $row['quota'] . " devices , <span style='color:red;'>0 Device left</span>"; ?>
                                            <?php else: ?>
                                                <?= "Maximum " . $row['quota'] . " devices , <span style='color:orange;'>" . $row['rquota'] . " Device left</span>"; ?>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </td>

                                    <td><a class="btn btn-square btn-success m-2"
                                            href="<?php echo $page_panel_user; ?>?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_panel_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['blok'] == 1 ? 'btn-warning' : 'btn-outline-warning')?> m-2"
                                            href="<?php echo $page_panel_user; ?>?block=<?php echo $row['id']; ?><?php echo $selected_page; ?>">
                                            <i class="<?=($row['blok'] == 1 ? 'fa fa-lock' : 'fa fa-unlock-alt')?>"></i>
                                        </a>
                                    </td>   
                                    
                                    <td><a name="submitmark"
                                            class="btn btn-square btn-info m-2"  onclick="copyRow(this)"><i class="fa fa-clipboard"></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 -->
<script>
function copyRow(btn) {
   
    let row = btn.closest("tr");
    let cells = row.getElementsByTagName("td");

    
    let title = cells[1].innerText;
    let username = cells[2].innerText;
    let password = cells[3].innerText;
    let expire = cells[4].innerText;
    let maxd = cells[6].innerText;

    
    let textToCopy = 
      "Name: " + title + "\n" +
      "Username: " + username + "\n" +
      "Password: " + password + "\n" +
      "Expire Date: " + expire + "\n" +
      "Max Devices: " + maxd ;

    
    navigator.clipboard.writeText(textToCopy).then(() => {
        alert("Copied:\n" + textToCopy);
    }).catch(err => {
        console.error("Copy failed", err);
    });
}
</script>
<!-- Table End -->

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

</html>