<?php
session_start();
include_once "../config/database.php";

if(!isset($_SESSION['user_id'])){
    header("Location: /beauty_pos/login.php");
    exit;
}

$search = isset($_GET['search']) ? mysqli_real_escape_string($conn,$_GET['search']) : "";

$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if($page < 1) $page = 1;

$offset = ($page-1) * $limit;

$where = "";

if($search!=""){
    $where = "WHERE brand_name LIKE '%$search%'";
}

$totalQuery = mysqli_query($conn,"
SELECT COUNT(*) total
FROM brands
$where
");

$totalRow = mysqli_fetch_assoc($totalQuery);

$totalRecords = $totalRow['total'];

$totalPages = ceil($totalRecords/$limit);

$query = mysqli_query($conn,"
SELECT *
FROM brands
$where
ORDER BY id DESC
LIMIT $offset,$limit
");

include_once "../includes/header.php";
include_once "../includes/sidebar.php";
?>

<div class="overlay" id="overlay"></div>

<div class="main-content">

<?php include_once "../includes/topbar.php"; ?>

<div class="container-fluid">

<div class="d-flex justify-content-between align-items-center mb-3">

<h4>Brands</h4>

<a href="/beauty_pos/brands/add.php" class="btn btn-primary">
<i class="fa fa-plus"></i> Add Brand
</a>

</div>

<form method="GET" class="mb-3">

<div class="row g-2">

<div class="col-md-10">

<input
type="text"
name="search"
class="form-control"
placeholder="Search Brand..."
value="<?php echo $search; ?>"
>

</div>

<div class="col-md-2">

<button class="btn btn-dark w-100">
Search
</button>

</div>

</div>

</form>

<div class="card-box table-box rounded-4 shadow">

<div class="table-responsive">

<table class="table table-hover align-middle">

<thead class="table-dark">

<tr>

<th width="70">#</th>

<th>Brand Name</th>

<th width="180">Created</th>

<th width="160">Action</th>

</tr>

</thead>

<tbody>

<?php

$i=$offset+1;

while($row=mysqli_fetch_assoc($query)){

?>

<tr>

<td><?php echo $i++; ?></td>

<td><?php echo $row['brand_name']; ?></td>

<td><?php echo $row['created_at']; ?></td>

<td>

<a
href="/beauty_pos/brands/edit.php?id=<?php echo $row['id']; ?>"
class="btn btn-warning btn-sm">

<i class="fa fa-edit"></i>

</a>

<a
href="/beauty_pos/brands/delete.php?id=<?php echo $row['id']; ?>"
class="btn btn-danger btn-sm"
onclick="return confirm('Delete this brand?')">

<i class="fa fa-trash"></i>

</a>

</td>

</tr>

<?php } ?>

<?php if(mysqli_num_rows($query)==0){ ?>

<tr>

<td colspan="4" class="text-center">
No Brands Found
</td>

</tr>

<?php } ?>

</tbody>

</table>

</div>

</div>

<nav class="mt-3">

<ul class="pagination justify-content-center">

<?php

for($p=1;$p<=$totalPages;$p++){

?>

<li class="page-item <?php if($p==$page) echo "active"; ?>">

<a
class="page-link"
href="?page=<?php echo $p; ?>&search=<?php echo urlencode($search); ?>">

<?php echo $p; ?>

</a>

</li>

<?php } ?>

</ul>

</nav>

</div>

<?php include_once "../includes/footer.php"; ?>

</div>