<?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 'branch_connection.php';

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

// AJAX Handlers
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Search Handler
    if (isset($_POST['search'])) {
        $searchTerm = trim($_POST['search']);
        $segments = [];
        if (!empty($searchTerm)) {
            $stmt = $conn->prepare("SELECT id, segment_name FROM segments WHERE segment_name LIKE ? ORDER BY id DESC");
            $searchParam = "%" . $searchTerm . "%";
            $stmt->bind_param("s", $searchParam);
            $stmt->execute();
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $segments[] = $row;
            }
            $stmt->close();
        }
        header('Content-Type: application/json');
        echo json_encode(['segments' => $segments, 'isSearch' => true]);
        exit();
    }

    // Load Paginated Data Handler
    if (isset($_POST['load_page'])) {
        $page = intval($_POST['page']);
        $limit = 20;
        $offset = ($page - 1) * $limit;

        $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();
        $segments = [];
        while ($row = $resultSegments->fetch_assoc()) {
            $segments[] = $row;
        }
        $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);

        header('Content-Type: application/json');
        echo json_encode([
            'segments' => $segments,
            'totalPages' => $totalPages,
            'currentPage' => $page,
            'totalRecords' => $totalRow['total'],
            'isSearch' => false
        ]);
        exit();
    }
}

$message = "";
$segmentName = "";
$editMode = false;
$editId = 0;
$searchMode = false; // Track if in search mode

// 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" && !isset($_POST['search']) && !isset($_POST['load_page'])) {
    $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 (for initial load)
$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 (for initial load)
$segments = [];
$resultSegments = null;
if (!$searchMode) {
    $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();
    while ($row = $resultSegments->fetch_assoc()) {
        $segments[] = $row;
    }
    $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);
?>
<!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" id="segmentForm">
                            <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="mb-3" style="display:flex; align-items:center; gap:5px;">
                    <input type="text" id="searchInput" class="form-control" placeholder="Search by segment name..." style="flex:1;">
                    <button type="button" id="clearSearch" class="btn btn-secondary" style="display:none;">Clear</button>
                </div>

                    <div class="table-responsive">
                        <table class="table table-hover table-responsive-sm" id="segmentsTable">
                            <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 id="segmentsTbody">
                                <?php if (!empty($segments)): ?>
                                    <?php
                                    $counter = $totalRow['total'] - $offset;
                                    foreach ($segments as $row): ?>
                                        <tr>
                                            <th><?php echo $counter--; ?></th>
                                            <td><?php echo htmlspecialchars($row['segment_name']); ?></td>
                                            <td><?php echo htmlspecialchars($row['id']); ?></td>
                                            <td style="text-align:center;"><span class="d-flex">
                                                <a href="add-segment.php?edit_id=<?php echo intval($row['id']); ?>&page=<?php echo $currentPage; ?>" style="color:#ffc107; margin-right:8px;"><i class="fa fa-edit"></i></a>
                                                <a href="add-segment.php?delete_id=<?php echo intval($row['id']); ?>&page=<?php echo $currentPage; ?>" onclick="return confirm('Are you sure?');" style="color:#dc3545;"><i class="fa fa-trash"></i></a>
                                            </span></td>
                                            <td></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr><td colspan="5" class="text-center">No segments found.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>

                        <div id="paginationContainer">
                            <?php if ($totalPages > 1): ?>
                            <nav aria-label="Page navigation">
                                <ul class="pagination justify-content-center" id="pagination">
                                    <li class="page-item <?php echo ($currentPage <= 1) ? 'disabled' : ''; ?>">
                                        <a class="page-link" href="#" data-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="#" data-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="#" data-page="<?php echo $currentPage+1; ?>">Next</a>
                                    </li>
                                </ul>
                            </nav>
                            <?php endif; ?>
                        </div>
                    </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>

<script>
$(document).ready(function() {
    var currentPage = <?php echo $currentPage; ?>;
    var isSearchMode = false;
    var totalPages = <?php echo $totalPages; ?>;
    var totalRecords = <?php echo $totalRow['total']; ?>;

    // Search functionality
    $('#searchInput').on('keyup', function() {
        var searchTerm = $(this).val().trim();
        if (searchTerm.length > 0) {
            isSearchMode = true;
            $('#clearSearch').show();
            performSearch(searchTerm);
        } else {
            isSearchMode = false;
            $('#clearSearch').hide();
            loadPaginatedData(currentPage);
        }
    });

    // Clear search button
    $('#clearSearch').on('click', function() {
        $('#searchInput').val('');
        isSearchMode = false;
        $(this).hide();
        loadPaginatedData(currentPage);
    });

    // Pagination click handlers (prevent default)
    $(document).on('click', '#pagination .page-link', function(e) {
        e.preventDefault();
        var page = $(this).data('page');
        if (page && !$(this).parent().hasClass('disabled')) {
            if (isSearchMode) {
                // If in search mode, clear search and go to page 1
                $('#searchInput').val('');
                $('#clearSearch').hide();
                isSearchMode = false;
                currentPage = 1;
            } else {
                currentPage = page;
            }
            loadPaginatedData(currentPage);
        }
    });

    // Function to perform search
    function performSearch(searchTerm) {
        $.ajax({
            url: 'add-segment.php',
            type: 'POST',
            data: {search: searchTerm},
            dataType: 'json',
            success: function(response) {
                updateTable(response.segments, true);
                $('#paginationContainer').hide();
            },
            error: function() {
                alert('Search error occurred.');
            }
        });
    }

    // Function to load paginated data
    function loadPaginatedData(page) {
        $.ajax({
            url: 'add-segment.php',
            type: 'POST',
            data: {load_page: 1, page: page},
            dataType: 'json',
            success: function(response) {
                updateTable(response.segments, false, response.totalRecords, page);
                updatePagination(response.totalPages, page);
                $('#paginationContainer').show();
                currentPage = page;
                totalPages = response.totalPages;
                totalRecords = response.totalRecords;
            },
            error: function() {
                alert('Error loading data.');
            }
        });
    }

    // Function to update table
    function updateTable(segments, hidePagination, totalRec = totalRecords, pageNum = currentPage) {
        var tbody = $('#segmentsTbody');
        tbody.empty();
        if (segments.length > 0) {
            var counter;
            if (hidePagination) {
                counter = segments.length; // For search, count from top
            } else {
                counter = totalRec - ((pageNum - 1) * 20); // Calculate starting number
            }
            $.each(segments, function(index, row) {
                var tr = '<tr>';
                tr += '<th>' + counter-- + '</th>';
                tr += '<td>' + $('<div>').text(row.segment_name).html() + '</td>';
                tr += '<td>' + $('<div>').text(row.id).html() + '</td>';
                tr += '<td style="text-align:center;"><span class="d-flex">';
                tr += '<a href="add-segment.php?edit_id=' + row.id + '&page=' + currentPage + '" style="color:#ffc107; margin-right:8px;"><i class="fa fa-edit"></i></a>';
                tr += '<a href="add-segment.php?delete_id=' + row.id + '&page=' + currentPage + '" onclick="return confirm(\'Are you sure?\');" style="color:#dc3545;"><i class="fa fa-trash"></i></a>';
                tr += '</span></td><td></td></tr>';
                tbody.append(tr);
            });
        } else {
            tbody.html('<tr><td colspan="5" class="text-center">No segments found.</td></tr>');
        }
        if (hidePagination) {
            $('#paginationContainer').hide();
        }
    }

    // Function to update pagination
    function updatePagination(totalPages, currentPageNum) {
        var pagination = $('#pagination');
        pagination.empty();

        // Previous
        var prevClass = (currentPageNum <= 1) ? 'disabled' : '';
        pagination.append('<li class="page-item ' + prevClass + '"><a class="page-link" href="#" data-page="' + (currentPageNum - 1) + '">Previous</a></li>');

        // Page numbers
        var maxDisplay = 7;
        var startPage = Math.max(1, currentPageNum - Math.floor(maxDisplay / 2));
        var endPage = Math.min(totalPages, startPage + maxDisplay - 1);
        if (endPage - startPage + 1 < maxDisplay) {
            startPage = Math.max(1, endPage - maxDisplay + 1);
        }
        for (var i = startPage; i <= endPage; i++) {
            var activeClass = (i == currentPageNum) ? 'active' : '';
            pagination.append('<li class="page-item ' + activeClass + '"><a class="page-link" href="#" data-page="' + i + '">' + i + '</a></li>');
        }

        // Next
                // Next
        var nextClass = (currentPageNum >= totalPages) ? 'disabled' : '';
        pagination.append('<li class="page-item ' + nextClass + '"><a class="page-link" href="#" data-page="' + (currentPageNum + 1) + '">Next</a></li>');

        // Re-attach event handlers if needed (but since we use delegation, it's fine)
    }

    // Handle form submission with AJAX to avoid full page refresh
    $('#segmentForm').on('submit', function(e) {
        e.preventDefault();
        var formData = $(this).serialize();
        $.ajax({
            url: 'add-segment.php',
            type: 'POST',
            data: formData,
            success: function(response) {
                // Parse the response (since it's HTML, we need to extract message)
                // For simplicity, reload the page after form submission to show message and reset
                location.reload();
            },
            error: function() {
                alert('Error submitting form.');
            }
        });
    });

    // Handle delete and edit links to prevent full refresh where possible
    // But since they redirect, we'll let them handle as is for now
});
</script>
</body>
</html>
<?php $conn->close(); ?>