<?php
include 'branch_connection.php';

$limit = 20;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$offset = ($page - 1) * $limit;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

$where = '';
if($search != ''){
    $where = " WHERE segment_name LIKE '%".mysqli_real_escape_string($conn, $search)."%'";
}

// Fetch segments
$sql = "SELECT * FROM segments $where ORDER BY id DESC LIMIT $limit OFFSET $offset";
$result = mysqli_query($conn, $sql);

// Total rows
$totalRes = mysqli_query($conn, "SELECT COUNT(*) as total FROM segments $where");
$totalRow = mysqli_fetch_assoc($totalRes);
$totalPages = ceil($totalRow['total'] / $limit);
?>

<table class="table table-hover table-responsive-sm">
<thead>
<tr>
<th style="width: 10px;">R#</th>
<th style="width: 200px;">Segment</th>
<th style="width: 200px;">Segment ID</th>
<th style="text-align: left!important;">Action</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$counter = $totalRow['total'] - $offset;
if(mysqli_num_rows($result) > 0){
    while($row = mysqli_fetch_assoc($result)){
        echo '<tr>';
        echo '<th>'.$counter--.'</th>';
        echo '<td>'.htmlspecialchars($row['segment_name'], ENT_QUOTES).'</td>';
        echo '<td>'.$row['id'].'</td>';
        echo '<td style="text-align:center;"><span class="d-flex">';
        echo '<a href="add-segment.php?edit_id='.$row['id'].'" style="color:#ffc107; margin-right:8px;"><i class="fa fa-edit"></i></a>';
        echo '<a href="add-segment.php?delete_id='.$row['id'].'" onclick="return confirm(\'Are you sure?\');" style="color:#dc3545;"><i class="fa fa-trash"></i></a>';
        echo '</span></td><td></td></tr>';
    }
} else {
    echo '<tr><td colspan="5" class="text-center">No segments found.</td></tr>';
}
?>
</tbody>
</table>

<?php if($totalPages > 1){ ?>
<nav aria-label="Page navigation">
    <ul class="pagination justify-content-center">
        <?php for($i=1;$i<=$totalPages;$i++){ ?>
        <li class="page-item <?php if($i==$page) echo 'active'; ?>">
            <a href="#" class="page-link" data-page="<?php echo $i; ?>"><?php echo $i; ?></a>
        </li>
        <?php } ?>
    </ul>
</nav>
<?php } ?>
