<?php
include 'branch_connection.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
}
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Pagination setup
$itemsPerPage = 20;
if (isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0) {
    $currentPage = $_GET['page'];
} else {
    $currentPage = 1;
}

// Messages
$message = "";

// Handle delete
if (isset($_GET['delete_id'])) {
    $delete_id = $_GET['delete_id'];
    $stmtDelete = $conn->prepare("DELETE FROM categories WHERE id = ?");
    $stmtDelete->bind_param("i", $delete_id);
    if ($stmtDelete->execute()) {
        $message = "Category deleted successfully.";
    } else {
        $message = "Error deleting category: " . $stmtDelete->error;
    }
    $stmtDelete->close();
    header("Location: add-category.php?page=" . $currentPage . "&msg=" . urlencode($message));
    exit;
}

// Initialize variables for edit mode
$editMode = false;
$editName = "";
$editId = 0;

// Handle edit retrieval
if (isset($_GET['edit_id'])) {
    $editId = $_GET['edit_id'];
    $stmtEdit = $conn->prepare("SELECT name FROM categories WHERE id = ?");
    $stmtEdit->bind_param("i", $editId);
    $stmtEdit->execute();
    $stmtEdit->bind_result($editName);
    if ($stmtEdit->fetch()) {
        $editMode = true;
    }
    $stmtEdit->close();
}

// Handle form submission (add or update)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $categoryName = strtoupper($_POST['category']);
    $postedEditId = $_POST['edit_id'];

    if ($categoryName === '') {
        $message = "Please enter a category.";
    } else {
        if ($postedEditId > 0) {
            // Update
            $stmtUpdate = $conn->prepare("UPDATE categories SET name = ? WHERE id = ?");
            $stmtUpdate->bind_param("si", $categoryName, $postedEditId);
            if ($stmtUpdate->execute()) {
                $message = "Category updated successfully.";
            } else {
                $message = "Error updating category: " . $stmtUpdate->error;
            }
            $stmtUpdate->close();
        } else {
            // Insert new
            $stmtInsert = $conn->prepare("INSERT INTO categories (name) VALUES (?)");
            $stmtInsert->bind_param("s", $categoryName);
            if ($stmtInsert->execute()) {
                $message = "New category added successfully.";
            } else {
                $message = "Error adding category: " . $stmtInsert->error;
            }
            $stmtInsert->close();
        }
        header("Location: add-category.php?page=" . $currentPage . "&msg=" . urlencode($message));
        exit;
    }
}

// Show message from redirects
if (isset($_GET['msg'])) {
    $message = htmlspecialchars($_GET['msg']);
}

// Pagination calculations
$offset = ($currentPage - 1) * $itemsPerPage;

$resultTotal = $conn->query("SELECT COUNT(*) AS total FROM categories");
$rowTotal = $resultTotal->fetch_assoc();
$totalItems = $rowTotal['total'];
$totalPages = ceil($totalItems / $itemsPerPage);

// Fetch paginated categories in DESCENDING order (newest first)
$stmtList = $conn->prepare("SELECT id, name FROM categories ORDER BY id DESC LIMIT ? OFFSET ?");
$stmtList->bind_param("ii", $itemsPerPage, $offset);
$stmtList->execute();
$resultList = $stmtList->get_result();

// Calculate the starting number for the current page (for descending order)
$startingNumber = $totalItems - $offset;
?>

<!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="author" content="DexignLab">
      <meta name="robots" content="index, follow">
      <meta name="format-detection" content="telephone=no">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="shortcut icon" type="image/png" href="assets/images/favicon.png">
      <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="preloader">
         <div class="lds-ripple">
            <div></div>
            <div></div>
         </div>
      </div>
      <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 class="nav-control">
               <div class="hamburger">
                  <span class="line"></span><span class="line"></span><span class="line"></span>
               </div>
            </div>
         </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">
                           Category
                        </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 id="icon-light" class="fas fa-sun"></i>
                              <i id="icon-dark" class="fas fa-moon"></i>
                           </a>
                        </li>
                        <?php
                        $title = "Php Header Footer";
                        include "logout.php";
                        ?>
                     </ul>
                  </div>
               </nav>
            </div>
         </div>
         <?php
         $title = "Php Header Footer";
         include "header.php";
         ?>
         <div class="content-body">
            <div class="container-fluid">
               <div class="row">
                  <div class="col-xl-12">
                     <div class="row">
                        <div class="col-xl-5">
                           <div class="card">
                              <div class="card-body">
                                 <div class="basic-form">
                                    <form method="POST" action="">
                                       <div class="row">
                                          <div class="mb-3 col-md-13">
                                             <input 
                                                type="text" 
                                                name="category" 
                                                class="form-control" 
                                                placeholder="Add Category" 
                                                value="<?php echo htmlspecialchars($editMode ? $editName : ''); ?>"
                                                required>
                                          </div>
                                       </div>
                                       <?php if ($editMode): ?>
                                          <input type="hidden" name="edit_id" value="<?php echo intval($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-7">
                           <div class="table-responsive">
                              <table class="table table-hover table-responsive-sm">
                                 <thead>
                                    <tr>
                                       <th class="td-padding-no" style="width: 10px;">R#</th>
                                       <th class="td-padding-no" style="width: 200px;">Category</th>
                                       <th class="td-padding-no" style="text-align: left!important;">Action</th>
                                       <th></th>
                                    </tr>
                                 </thead>
                                 <tbody>
                                    <?php
                                    if ($resultList && $resultList->num_rows > 0) {
                                        $counter = $startingNumber;
                                        while ($row = $resultList->fetch_assoc()) {
                                            echo '<tr>';
                                            echo '<th class="td-padding-no">' . $counter-- . '</th>';
                                            echo '<td class="td-padding-no">' . htmlspecialchars($row['name']) . '</td>';
                                            echo '<td class="td-padding-no" style="text-align:center;">';
                                            echo '<span style="gap:2px;width: 100%;text-align:center;" class="d-flex">';
                                            echo '<a href="add-category.php?edit_id=' . intval($row['id']) . '&page='.$currentPage.'" title="Edit" class="text-warning me-3"><i class="fa fa-edit"></i></a>';
                                            echo '<a href="add-category.php?delete_id=' . intval($row['id']) . '&page='.$currentPage.'" title="Delete" style="color:#dc3545;" onclick="return confirm(\'Are you sure you want to delete this category?\');"><i class="fa fa-trash"></i></a>';
                                            echo '</span>';
                                            echo '</td>';
                                            echo '<td></td>';
                                            echo '</tr>';
                                        }
                                    } else {
                                        echo '<tr><td colspan="4" class="text-center">No categories 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-category.php?page=<?php echo $currentPage-1; ?>" tabindex="-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-category.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-category.php?page=<?php echo $currentPage+1; ?>">Next</a>
                                  </li>
                                </ul>
                              </nav>
                              <?php endif; ?>

                           </div>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
         <?php
         $title = "Php Header Footer";
         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
$stmtList->close();
$conn->close();
?>
