<?php

session_start();
if (!isset($_SESSION['userid'])) {
    // Redirect to login page if userid is not set
    header("Location: ../index.php");
    exit(); // Always use exit after header redirection
}
include '../config.php';

// Check DB connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$message = "";
$segmentName = "";
$editMode = false;
$editId = 0;

// Delete segment
if (isset($_GET['delete_id'])) {
    $delete_id = intval($_GET['delete_id']);
    $stmt = $conn->prepare("DELETE FROM segments WHERE id = ?");
    $stmt->bind_param("i", $delete_id);
    if ($stmt->execute()) {
        $message = "Segment deleted successfully.";
    } else {
        $message = "Error deleting segment: " . $stmt->error;
    }
    $stmt->close();
}

// Edit mode: fetch segment
if (isset($_GET['edit_id'])) {
    $editId = intval($_GET['edit_id']);
    $stmt = $conn->prepare("SELECT segment_name FROM segments WHERE id = ?");
    $stmt->bind_param("i", $editId);
    $stmt->execute();
    $stmt->bind_result($segmentName);
    if ($stmt->fetch()) {
        $editMode = true;
    } else {
        $message = "Segment not found.";
    }
    $stmt->close();
}

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $segmentInput = strtoupper(trim($_POST['segment']));
    $editIdPosted = intval($_POST['edit_id']);

    if ($segmentInput === "") {
        $message = "Please enter a segment.";
    } else {
        if ($editIdPosted > 0) {
            $stmt = $conn->prepare("UPDATE segments SET segment_name = ? WHERE id = ?");
            $stmt->bind_param("si", $segmentInput, $editIdPosted);
            $stmt->execute();
            $stmt->close();
            $message = "Segment updated.";
            $editMode = false;
        } else {
            $stmt = $conn->prepare("INSERT INTO segments (segment_name) VALUES (?)");
            $stmt->bind_param("s", $segmentInput);
            $stmt->execute();
            $stmt->close();
            $message = "New segment added.";
        }
    }
}

// Pagination setup
$limit = 20;
$page = isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0 ? intval($_GET['page']) : 1;
$currentPage = $page;
$offset = ($page - 1) * $limit;

// Fetch segments in descending order
$segments = [];
$stmt = $conn->prepare("SELECT id, segment_name FROM segments ORDER BY id DESC LIMIT ? OFFSET ?");
$stmt->bind_param("ii", $limit, $offset);
$stmt->execute();
$resultSegments = $stmt->get_result();
$stmt->close();

// Get total records for pagination
$totalResult = $conn->query("SELECT COUNT(*) AS total FROM segments");
$totalRow = $totalResult->fetch_assoc();
$totalPages = ceil($totalRow['total'] / $limit);
?>
<!-- Keep your HTML unchanged below this line -->

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Leads Programers International</title>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link href="assets/vendor/bootstrap-select/dist/css/bootstrap-select.min.css" rel="stylesheet" />
    <link href="assets/vendor/bootstrap-datepicker-master/css/bootstrap-datepicker.min.css" rel="stylesheet" />
    <link href="assets/vendor/owl-carousel/owl.carousel.css" rel="stylesheet" />
    <link href="assets/css/jquery.localizationTool.css" rel="stylesheet" />
    <link class="main-css" href="assets/css/style.css" rel="stylesheet" />
</head>
<body>
<div id="main-wrapper">
    <div class="nav-header"><a href="index.html" class="brand-logo"><img src="assets/images/logo-02.svg" alt="" /></a></div>
    <div class="header">
        <div class="header-content">
            <nav class="navbar navbar-expand">
                <div class="collapse navbar-collapse justify-content-between">
                    <div class="header-left"><div class="dashboard_bar">Segment</div></div>
                    <ul class="navbar-nav header-right">
                        <li class="nav-item dropdown notification_dropdown">
                            <a class="nav-link bell dlab-theme-mode p-0" href="javascript:void(0);"><i class="fas fa-sun"></i><i class="fas fa-moon"></i></a>
                        </li>
                        <?php include "logout.php"; ?>
                    </ul>
                </div>
            </nav>
        </div>
    </div>
    <?php include "header.php"; ?>
    <div class="content-body">
        <div class="container-fluid">
            <div class="row">
                <div class="col-xl-4">
                    <div class="card"><div class="card-body"><div class="basic-form">
                        <form action="" method="POST">
                            <div class="row">
                                <div class="mb-3 col-md-13">
                                    <input type="text" name="segment" value="<?php echo htmlspecialchars($segmentName); ?>" class="form-control" placeholder="Add Segment" required />
                                </div>
                            </div>
                            <?php if ($editMode) : ?>
                                <input type="hidden" name="edit_id" value="<?php echo $editId; ?>" />
                            <?php endif; ?>
                            <button type="submit" class="btn btn-primary w-100"><?php echo $editMode ? 'Update' : 'Submit'; ?></button>
                        </form>
                        <?php if ($message) : ?>
                            <div class="mt-3 alert alert-info"><?php echo htmlspecialchars($message); ?></div>
                        <?php endif; ?>
                    </div></div></div>
                </div>
                <div class="col-xl-8">
                    <div class="table-responsive">
                        <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; // Calculate the starting number for the current page
                                if ($resultSegments && $resultSegments->num_rows > 0) {
                                    while ($row = $resultSegments->fetch_assoc()) {
                                        echo '<tr>';
                                        echo '<th>' . $counter-- . '</th>'; // Decrement the counter
                                        echo '<td>' . htmlspecialchars($row['segment_name']) . '</td>';
                                        echo '<td>' . htmlspecialchars($row['id']) . '</td>';
                                        echo '<td style="text-align:center;"><span class="d-flex">';
                                        echo '<a href="add-segment.php?edit_id=' . intval($row['id']) . '&page=' . $currentPage . '" style="color:#ffc107; margin-right:8px;"><i class="fa fa-edit"></i></a>';
                                        echo '<a href="add-segment.php?delete_id=' . intval($row['id']) . '&page=' . $currentPage . '" 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="4" 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">
                                <li class="page-item <?php echo ($currentPage <= 1) ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="add-segment.php?page=<?php echo $currentPage-1; ?>">Previous</a>
                                </li>
                                <?php
                                $maxDisplay = 7;
                                $startPage = max(1, $currentPage - intval($maxDisplay/2));
                                $endPage = min($totalPages, $startPage + $maxDisplay - 1);
                                if ($endPage - $startPage + 1 < $maxDisplay) {
                                    $startPage = max(1, $endPage - $maxDisplay + 1);
                                }
                                for ($i = $startPage; $i <= $endPage; $i++): ?>
                                <li class="page-item <?php echo ($i == $currentPage) ? 'active' : ''; ?>">
                                    <a class="page-link" href="add-segment.php?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                </li>
                                <?php endfor; ?>
                                <li class="page-item <?php echo ($currentPage >= $totalPages) ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="add-segment.php?page=<?php echo $currentPage+1; ?>">Next</a>
                                </li>
                            </ul>
                        </nav>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php include "footer.php"; ?>
</div>

<script src="assets/vendor/global/global.min.js"></script>
<script src="assets/vendor/bootstrap-select/dist/js/bootstrap-select.min.js"></script>
<script src="assets/vendor/bootstrap-datepicker-master/js/bootstrap-datepicker.min.js"></script>
<script src="assets/vendor/apexchart/apexchart.js"></script>
<script src="assets/vendor/chartjs/chart.bundle.min.js"></script>
<script src="assets/vendor/peity/jquery.peity.min.js"></script>
<script src="assets/js/dashboard/dashboard-1.js"></script>
<script src="assets/vendor/owl-carousel/owl.carousel.js"></script>
<script src="assets/js/jquery.localizationTool.js"></script>
<script src="assets/js/translator.js"></script>
<script src="assets/js/custom.min.js"></script>
<script src="assets/js/dlabnav-init.js"></script>
<script src="assets/js/demo.js"></script>
</body>
</html>
<?php $conn->close(); ?>
