<?php
include("includes/session.php");
include 'includes/db.php';

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$title = "Manage Categories";
include("includes/head.php");

// Fetch Categories and Subcategories Data
$stmt = $conn->prepare("SELECT subcategory.product_class, category.category_name, category.group_target, subcategory.subcategory_id, category.category_id
                        FROM subcategory
                        JOIN category ON subcategory.category_id = category.category_id");
$stmt->execute();
$subcategories = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
	<body>
	
	
		<!-- Main Wrapper -->
		<div class="main-wrapper">
		
			<!-- Header -->
			<?php include("includes/header.php"); ?>
			<!-- /Header -->
			
				<!-- Sidebar -->
				<?php include("includes/sidebar.php"); ?>
				<!-- /Sidebar -->
	
			<!-- Page Wrapper -->
			<div class="page-wrapper">
				<div class="content container-fluid">				
					<!-- Page Header -->
					<div class="page-header">
						<div class="content-page-header ">
							<h5>Categories</h5>
							<div class="list-btn">
					<ul class="filter-list">
    <!-- Add Category -->
    <li>
        <a class="btn btn-primary" href="javascript:void(0);" data-bs-toggle="modal" data-bs-target="#add_category">
            <i class="fa fa-plus-circle me-2" aria-hidden="true"></i>Add Category
        </a>
    </li>
    <!-- Add Sub Category -->
    <li>
        <a class="btn btn-primary" href="javascript:void(0);" data-bs-toggle="modal" data-bs-target="#add_subcategory">
            <i class="fa fa-plus-circle me-2" aria-hidden="true"></i>Add Sub Category
        </a>
    </li>
</ul>

							</div>
						</div>
					</div>
					<!-- /Page Header -->
					
					<div class="row">
    <div class="col-sm-12">
        <div class="card-table">
            <div class="card-body">
                <div class="table-responsive">
                  <table class="table table-center table-hover datatable">
    <thead class="thead-light">
        <tr>
            <th>#</th>
            <th>Category Name</th>
            <th>Group Target</th>
            <th>Product Class</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <?php 
        $displayIndex = 1;
        foreach ($subcategories as $subcategory) { 
        ?>
        <tr>
            <td><?= $displayIndex ?></td>
            <td><?= htmlspecialchars($subcategory['category_name']) ?></td>
            <td><?= htmlspecialchars($subcategory['group_target']) ?></td>
            <td><?= htmlspecialchars($subcategory['product_class']) ?></td>
            <td>
                <!-- Edit and Delete buttons -->
                <button 
    class="btn btn-sm btn-primary edit-subcategory-btn" 
    data-id="<?= $subcategory['subcategory_id'] ?>" 
    data-category-name="<?= htmlspecialchars($subcategory['category_name']) ?>" 
    data-group-target="<?= htmlspecialchars($subcategory['group_target']) ?>" 
    data-product-class="<?= htmlspecialchars($subcategory['product_class']) ?>">
    Edit
</button>
                <a href="delete_subcategory.php?id=<?= $subcategory['subcategory_id'] ?>" class="btn btn-sm btn-danger">Delete</a>
            </td>
        </tr>
        <?php $displayIndex++; } ?>
    </tbody>
</table>
                </div>
            </div>
        </div>
    </div>
</div>

				</div>
			</div>
			<!-- /Page Wrapper -->

			<!-- Add Asset -->
			<div class="toggle-sidebar">
				<div class="sidebar-layout-filter">
					<div class="sidebar-header">
						<h5>Filter</h5>
						<a href="#" class="sidebar-closes"><i class="fa-regular fa-circle-xmark"></i></a>
					</div>
					<div class="sidebar-body">						
						<form action="#" autocomplete="off">
							<!-- Customer -->
							<div class="accordion" id="accordionMain1">
								<div class="card-header-new" id="headingOne">
									<h6 class="filter-title">
									<a href="javascript:void(0);" class="w-100" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
										Customer	
										<span class="float-end"><i class="fa-solid fa-chevron-down"></i></span>
									</a> 
									</h6>
								</div>
							
								<div id="collapseOne" class="collapse show" aria-labelledby="headingOne"  data-bs-parent="#accordionExample1">
									<div class="card-body-chat">
										<div class="row">
											<div class="col-md-12">
												<div id="checkBoxes1">
													<div class="form-custom">														
														<input type="text" class="form-control" id="member_search1" placeholder="Search here">
														<span><img src="assets/img/icons/search.svg" alt="img"></span>
													</div>
													<div class="selectBox-cont">
														<label class="custom_check w-100">
															<input type="checkbox" name="username">
															<span class="checkmark"></span>  John Smith
														</label>
														<label class="custom_check w-100">
															<input type="checkbox" name="username">
															<span class="checkmark"></span>  Johnny
														</label>
														<label class="custom_check w-100">
															<input type="checkbox" name="username">
															<span class="checkmark"></span>  Robert
														</label>
														<label class="custom_check w-100">
															<input type="checkbox" name="username">
															<span class="checkmark"></span> Sharonda
														</label>
														<!-- View All -->
														<div class="view-content">
															<div class="viewall-One">	
																<label class="custom_check w-100">
																	<input type="checkbox" name="username">
																	<span class="checkmark"></span> Pricilla
																</label>
																<label class="custom_check w-100">
																	<input type="checkbox" name="username">
																	<span class="checkmark"></span> Randall
																</label>
															</div>
															<div class="view-all">
																<a href="javascript:void(0);" class="viewall-button-One"><span class="me-2">View All</span><span><i class="fa fa-circle-chevron-down"></i></span></a>
															</div>
														</div>
														<!-- /View All -->
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
							<!-- /Customer -->

							<!-- Select Date -->
							<div class="accordion" id="accordionMain2">
								<div class="card-header-new" id="headingTwo">
									<h6 class="filter-title">
									<a href="javascript:void(0);" class="w-100 collapsed"  data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">
										Select Date	
										<span class="float-end"><i class="fa-solid fa-chevron-down"></i></span>
									</a> 
									</h6>
								</div>
							
								<div id="collapseTwo" class="collapse" aria-labelledby="headingTwo"  data-bs-parent="#accordionExample2">
									<div class="card-body-chat">
										<div class="input-block mb-3">
											<label class="form-control-label">From</label>
											<div class="cal-icon">
												<input type="email" class="form-control datetimepicker" placeholder="DD-MM-YYYY">
											</div>
										</div>
										<div class="input-block mb-3">
											<label class="form-control-label">To</label>
											<div class="cal-icon">
												<input type="email" class="form-control datetimepicker" placeholder="DD-MM-YYYY">
											</div>
										</div>
									</div>
								</div>
							</div>
							<!-- /Select Date -->

							<!-- By Status -->
							<div class="accordion accordion-last" id="accordionMain3">
								<div class="card-header-new" id="headingThree">
									<h6 class="filter-title">
									<a href="javascript:void(0);" class="w-100 collapsed"  data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="true" aria-controls="collapseThree">
										By Status	
										<span class="float-end"><i class="fa-solid fa-chevron-down"></i></span>
									</a> 
									</h6>
								</div>
							
								<div id="collapseThree" class="collapse" aria-labelledby="headingThree"  data-bs-parent="#accordionExample3">
									<div class="card-body-chat">
										<div id="checkBoxes2">
											<div class="form-custom">														
												<input type="text" class="form-control" id="member_search2" placeholder="Search here">
												<span><img src="assets/img/icons/search.svg" alt="img"></span>
											</div>
											<div class="selectBox-cont">
												<label class="custom_check w-100">
													<input type="checkbox" name="bystatus">
													<span class="checkmark"></span> Active
												</label>
												<label class="custom_check w-100">
													<input type="checkbox" name="bystatus">
													<span class="checkmark"></span>  Restricted
												</label>
											</div>
										</div>	
									</div>
								</div>
							</div>
							<!-- /By Status -->
							<div class="filter-buttons">
								<button type="submit" class="d-inline-flex align-items-center justify-content-center btn w-100 btn-primary">
									Apply
								</button>
								<button type="submit" class="d-inline-flex align-items-center justify-content-center btn w-100 btn-secondary">
									Reset
								</button>
							</div>
						</form>
						
					</div>
				</div>
			</div>	
			<!--/Add Asset -->

			<!-- Add User -->
	<div class="modal custom-modal modal-lg fade" id="add_category" role="dialog">
    <div class="modal-dialog modal-dialog-centered modal-md">
        <div class="modal-content">
            <div class="modal-header border-0 pb-0">
                <div class="form-header modal-header-title text-start mb-0">
                    <h4 class="mb-0">Add Category</h4>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="add_categoryForm" method="POST">
    <div class="modal-body">
        <div class="input-block mb-3">
            <label for="category_name">Category Name</label>
            <input name="category_name" type="text" class="form-control" id="category_name" placeholder="Enter Category Name" required>
        </div>
        <div class="input-block mb-3">
            <label for="group_target">Group Target</label>
            <input name="group_target" type="text" class="form-control" id="group_target" placeholder="Enter Group Target" required>
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-back cancel-btn me-2" data-bs-dismiss="modal">Cancel</button>
        <button type="submit" class="btn btn-primary">Add Category</button>
    </div>
</form>
        </div>
    </div>
</div>

<div class="modal custom-modal modal-lg fade" id="add_subcategory" role="dialog">
    <div class="modal-dialog modal-dialog-centered modal-md">
        <div class="modal-content">
            <div class="modal-header border-0 pb-0">
                <div class="form-header modal-header-title text-start mb-0">
                    <h4 class="mb-0">Add Subcategory</h4>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form  id="add_subcategoryForm" method="POST">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card-body">
                                <div class="form-groups-item">
                                    <div class="row">
                                        <div class="col-lg-4 col-md-6 col-sm-12">
                                            <div class="input-block mb-3">
                                                <label>Product Class</label>
                                                <input name="product_class" type="text" class="form-control" placeholder="Enter Product Class" required>
                                            </div>
                                        </div>
                                        <div class="col-lg-4 col-md-6 col-sm-12">
                                            <div class="input-block mb-3">
                                                <label>Category</label>
                                                <select name="category_id" class="form-control" required>
                                                    <option value="" disabled selected>Select Category</option>
                                                    <!-- Fetch categories dynamically here -->
                                                    <?php
                                                    $stmt = $conn->prepare("SELECT * FROM category");
                                                    $stmt->execute();
                                                    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                                    foreach ($categories as $category) {
                                                        echo "<option value='{$category['category_id']}'>{$category['category_name']}</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>                         
                            </div>
                        </div>
                    </div>
                </div>
               <div class="modal-footer">
        <button type="button" class="btn btn-back cancel-btn me-2" data-bs-dismiss="modal">Cancel</button>
        <button type="submit" class="btn btn-primary">Add Subcategory</button>
    </div>
            </form>
        </div>
    </div>
</div>

<div class="modal custom-modal modal-lg fade" id="edit_subcategory" role="dialog">
    <div class="modal-dialog modal-dialog-centered modal-md">
        <div class="modal-content">
            <div class="modal-header border-0 pb-0">
                <div class="form-header modal-header-title text-start mb-0">
                    <h4 class="mb-0">Edit Subcategory</h4>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="edit_subcategory_form" method="post">
                <div class="modal-body">
                    <input type="hidden" name="subcategory_id" id="edit_subcategory_id">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card-body">
                                <div class="form-groups-item">
                                    <div class="row">
                                        <div class="col-lg-6 col-md-6 col-sm-12">
                                            <div class="input-block mb-3">
                                                <label>Category Name</label>
                                                <select name="category_id" id="edit_category_name" class="form-control" required>
                                                    <option value="" disabled>Select Category</option>
                                                    <!-- Populate with categories dynamically -->
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-lg-6 col-md-6 col-sm-12">
                                            <div class="input-block mb-3">
                                                <label>Group Target</label>
                                                <input name="group_target" id="edit_group_target" type="text" class="form-control" placeholder="Enter Group Target" required>
                                            </div>
                                        </div>
                                        <div class="col-lg-6 col-md-6 col-sm-12">
                                            <div class="input-block mb-3">
                                                <label>Product Class</label>
                                                <input name="product_class" id="edit_product_class" type="text" class="form-control" placeholder="Enter Product Class" required>
                                            </div>
                                        </div>
                                    </div>
                                </div>                        
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" data-bs-dismiss="modal" class="btn btn-back cancel-btn me-2">Cancel</button>
                    <button name="update_subcategory" type="submit" class="btn btn-primary paid-continue-btn">Update Subcategory</button>
                </div>
            </form>
        </div>
    </div>
</div>




			<!-- /Add User -->
			
		</div>
		<!-- /Main Wrapper -->

		<!-- jQuery -->
        <script src="assets/js/jquery-3.7.1.min.js"></script>
		
		<!-- Bootstrap Core JS -->
		<script src="assets/js/bootstrap.bundle.min.js"></script>

		<!-- Datatable JS -->
		<script src="assets/plugins/datatables/datatables.min.js"></script>

		<!-- select CSS -->
		<script src="assets/plugins/select2/js/select2.min.js"></script>
		
		<!-- Slimscroll JS -->
		<script src="assets/plugins/slimscroll/jquery.slimscroll.min.js"></script>
		
		<!-- Datepicker Core JS -->
		<script src="assets/plugins/moment/moment.min.js"></script>
		<script src="assets/js/bootstrap-datetimepicker.min.js"></script>
		
		<!-- multiselect JS -->
		<script src="assets/js/jquery-ui.min.js"></script>

		<!-- Theme Settings JS -->
		<script src="assets/js/theme-settings.js"></script>
		<script src="assets/js/greedynav.js"></script>
		
		<!-- Custom JS -->
		<script src="assets/js/script.js"></script>

	</body>
<script>
$(document).ready(function() {
    // Submit category form via AJAX
    $('#add_categoryForm').on('submit', function(e) {
        e.preventDefault(); // Prevent default form submission

        // Get form data
        var formData = $(this).serialize();

        // Send AJAX request
        $.ajax({
            type: 'POST',
            url: 'insert_category.php', // The PHP file to handle category insertion
            data: formData,
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    // Display success message
                    toastr.success(response.message);
                    $('#add_category').modal('hide'); // Close the modal
                    $('#add_categoryForm')[0].reset(); // Reset the form
                } else {
                    // Display error message
                    toastr.error(response.message);
                }
            },
            error: function() {
                // Handle AJAX error
                toastr.error('An error occurred. Please try again later.');
            }
        });
    });
     // Submit subcategory form via AJAX
    $('#add_subcategoryForm').on('submit', function(e) {
        e.preventDefault(); // Prevent default form submission

        // Get form data
        var formData = $(this).serialize();

        // Send AJAX request
        $.ajax({
            type: 'POST',
            url: 'insert_subcategory.php', // The PHP file to handle subcategory insertion
            data: formData,
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    // Display success message
                    toastr.success(response.message);
                    $('#add_subcategory').modal('hide'); // Close the modal
                    $('#add_subcategoryForm')[0].reset(); // Reset the form
                } else {
                    // Display error message
                    toastr.error(response.message);
                }
            },
            error: function() {
                // Handle AJAX error
                toastr.error('An error occurred. Please try again later.');
            }
        });
    });
    
    $(document).on('click', '.edit-subcategory-btn', function() {
    var subcategoryId = $(this).data('id');
    var categoryName = $(this).data('category-name');
    var groupTarget = $(this).data('group-target');
    var productClass = $(this).data('product-class');

console.log('categoryName', categoryName);
    // Populate the modal fields
    $('#edit_subcategory_id').val(subcategoryId);
    $('#edit_category_name').val(categoryName);
    $('#edit_group_target').val(groupTarget);
    $('#edit_product_class').val(productClass);

    // Show the modal
    $('#edit_subcategory').modal('show');
});

    
    
});





</script>
</html>