<?php 
session_start();

// DEBUG MODE (error show karega)
error_reporting(E_ALL);
ini_set('display_errors', 1);

include 'includes/header.php'; 
include 'includes/sidebar.php'; 
include 'includes/connect.php';

// PAGINATION
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 10;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$start = ($page - 1) * $limit;

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

// Fetch categories with search & limit
$query = "SELECT * FROM category 
          WHERE category_name LIKE '%$search%' 
          ORDER BY id DESC 
          LIMIT $start, $limit";
$result = mysqli_query($conn, $query);

// Total records
$total_query = "SELECT COUNT(*) as total FROM category WHERE category_name LIKE '%$search%'";
$total_result = mysqli_query($conn, $total_query);
$total_row = mysqli_fetch_assoc($total_result);
$total_records = $total_row['total'];
$total_pages = ceil($total_records / $limit);
?>

<div class="main-content-inner">
    <div class="main-content-wrap">

        <div class="flex items-center flex-wrap justify-between gap20 mb-30">
            <h3>All Category</h3>
            <ul class="breadcrumbs flex items-center flex-wrap justify-start gap10">
                <li><a href="index.php"><div class="text-tiny">Dashboard</div></a></li>
                <li><i class="icon-chevron-right"></i></li>
                <li><a href="category-list.php"><div class="text-tiny">Crop</div></a></li>
                <li><i class="icon-chevron-right"></i></li>
                <li><div class="text-tiny">All Crop</div></li>
            </ul>
        </div>

        <div class="wg-box">
            <div class="flex items-center justify-between gap10 flex-wrap">

                <div class="wg-filter flex-grow flex items-center gap10">

                    <!-- Showing entries -->
                    <div class="show flex items-center gap5">
                        <div class="text-tiny">Showing</div>
                        <div class="select">
                            <form method="GET" id="limitForm">
                                <select name="limit" onchange="document.getElementById('limitForm').submit();">
                                    <option value="10" <?php if($limit==10) echo 'selected'; ?>>10</option>
                                    <option value="20" <?php if($limit==20) echo 'selected'; ?>>20</option>
                                    <option value="30" <?php if($limit==30) echo 'selected'; ?>>30</option>
                                </select>
                            </form>
                        </div>
                        <div class="text-tiny">entries</div>
                    </div>

                    <!-- Search form -->
                    <form class="form-search" method="GET">
                        <input type="hidden" name="limit" value="<?php echo $limit; ?>">
                        <fieldset class="name">
                            <input type="text" placeholder="Search here..." name="search" value="<?php echo htmlspecialchars($search); ?>">
                        </fieldset>
                        <div class="button-submit">
                            <button type="submit"><i class="icon-search"></i></button>
                        </div>
                    </form>

                </div>

                <!-- Add new button -->
                <div>
                    <a class="tf-button px-40" href="add-category.php">
                        <i class="icon-plus"></i>Add new
                    </a>
                </div>

            </div>

            <!-- TABLE -->
            <div class="wg-table table-all-category">

                <ul class="table-title flex gap20 mb-14">
                    <li><div class="body-title">Crop</div></li> 
                    <li><div class="body-title">Status</div></li>
                    <li><div class="body-title">Start date</div></li>
                    <li><div class="body-title">Action</div></li>
                </ul>

                <ul class="flex flex-column">
                    <?php if(mysqli_num_rows($result) > 0){ ?>
                        <?php while($row = mysqli_fetch_assoc($result)){ ?>
                            <li class="wg-product item-row gap20" id="row-<?php echo $row['id']; ?>">

                                <div class="name">
                                    <!--<div class="image">-->
                                    <!--    <img src="images/products/product-1.jpg" alt="image">-->
                                    <!--</div>-->
                                    <div class="title line-clamp-2 mb-0">
                                        <a href="#" class="body-text"><?php echo htmlspecialchars($row['category_name']); ?></a>
                                    </div>
                                </div>

                                <!-- Status Column -->
                                <div class="body-text text-main-dark mt-4">
                                    <?php echo ($row['status']==1) ? 'Active' : 'Inactive'; ?>
                                </div>

                                <!-- Date -->
                                <div class="body-text text-main-dark mt-4">
                                    <?php echo date("d M Y", strtotime($row['created_at'])); ?>
                                </div>

                                <div class="list-icon-function">

                                    <!-- Edit -->
                                    <a href="edit-category.php?id=<?php echo $row['id']; ?>" class="item edit">
                                        <i class="icon-edit-3"></i>
                                    </a>

                                    <!-- Delete with AJAX -->
                                    <button class="item trash delete-btn" data-id="<?php echo $row['id']; ?>" style="background:none;border:none;padding:0;">
                                        <i class="icon-trash-2"></i>
                                    </button>

                                </div>

                            </li>
                        <?php } ?>
                    <?php } else { ?>
                        <li><div class="body-text">No categories found</div></li>
                    <?php } ?>
                </ul>

            </div>

            <div class="divider"></div>

            <!-- Pagination -->
            <div class="flex items-center justify-between flex-wrap gap10">

                <div class="text-tiny text-surface-2">
                    Showing <?php echo mysqli_num_rows($result); ?> of <?php echo $total_records; ?> categories
                </div>

                <ul class="wg-pagination">
                    <?php if($page > 1){ ?>
                        <li><a href="?page=<?php echo $page-1; ?>&limit=<?php echo $limit; ?>&search=<?php echo urlencode($search); ?>"><i class="icon-chevron-left"></i></a></li>
                    <?php } ?>
                    <?php for($i=1;$i<=$total_pages;$i++){ ?>
                        <li class="<?php if($i==$page) echo 'active'; ?>">
                            <a href="?page=<?php echo $i; ?>&limit=<?php echo $limit; ?>&search=<?php echo urlencode($search); ?>"><?php echo $i; ?></a>
                        </li>
                    <?php } ?>
                    <?php if($page < $total_pages){ ?>
                        <li><a href="?page=<?php echo $page+1; ?>&limit=<?php echo $limit; ?>&search=<?php echo urlencode($search); ?>"><i class="icon-chevron-right"></i></a></li>
                    <?php } ?>
                </ul>

            </div>

        </div>

    </div>
</div>

<?php include 'includes/footer.php'; ?>

<!-- AJAX Delete Script -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $('.delete-btn').click(function(){
        var id = $(this).data('id');
        if(confirm('Are you sure you want to delete this category?')){
            $.ajax({
                url: 'delete-category.php',
                type: 'POST',
                data: {id: id},
                success: function(response){
                    // Optionally alert success
                    // Remove row visually (optional)
                    $('#row-' + id).fadeOut('slow', function(){ $(this).remove(); });
                    // Reload page to maintain design/pagination
                    location.reload();
                },
                error: function(){
                    alert('Error deleting category');
                }
            });
        }
    });
});
</script>