<?php
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Enable error reporting for development
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors on page
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

require_once('../includes/admin-security.php');
include_once('includes/config.php');

// Access Check
if (!has_permission('manage_categories')) {
    echo "<script>alert('Access Denied. Redirecting to Dashboard...'); window.location.href='dashboard.php';</script>";
    exit();
}

// Handle category deletion
if (isset($_GET['del'])) {
    if (!has_permission('manage_categories')) {
        $_SESSION['error'] = "You do not have permission to delete categories.";
        header('location: manage-categories.php');
        exit();
    }
    $catId = intval($_GET['id']);
    $catData = mysqli_query($con, "SELECT categoryName FROM category WHERE id = $catId");
    $catRow = mysqli_fetch_array($catData);
    $catName = $catRow['categoryName'] ?? 'Unknown';

    mysqli_query($con, "DELETE FROM category WHERE id = $catId");
    log_activity("Deleted Category", "Category Name: $catName (ID: $catId)");
    $_SESSION['delmsg'] = "Category deleted successfully!";
    header('location: manage-categories.php');
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Manage Categories - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" />
    <link href="css/styles.css" rel="stylesheet" />
    <link href="css/admin-professional.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"
        crossorigin="anonymous"></script>


</head>

<body class="sb-nav-fixed">
    <?php include_once('includes/header.php'); ?>

    <div id="layoutSidenav">
        <?php include_once('includes/sidebar.php'); ?>



        <div id="layoutSidenav_content">
            <main>
                <div class="container-fluid px-4">
                    <!-- Page Header -->
                    <div class="page-header mt-4">
                        <div>
                            <h1><i class="fas fa-tags me-2"></i> Manage Categories</h1>
                            <p>Organize your product categories</p>
                        </div>
                        <a href="add-category.php" class="btn btn-primary">
                            <i class="fas fa-plus me-2"></i> Add New Category
                        </a>
                    </div>



                    <!-- Success Message -->
                    <?php if (isset($_SESSION['msg'])) { ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle me-2"></i>
                            <?php echo htmlentities($_SESSION['msg']); ?>
                            <?php $_SESSION['msg'] = ""; ?>
                        </div>
                    <?php } ?>

                    <?php if (isset($_SESSION['delmsg'])) { ?>
                        <div class="alert alert-danger">
                            <i class="fas fa-trash-alt me-2"></i>
                            <?php echo htmlentities($_SESSION['delmsg']); ?>
                            <?php $_SESSION['delmsg'] = ""; ?>
                        </div>
                    <?php } ?>

                    <!-- Categories Table -->
                    <div class="table-card">
                        <table class="table table-hover" id="datatablesSimple">
                            <thead>
                                <tr>
                                    <th width="8%">#</th>
                                    <th>Category Name</th>
                                    <th width="15%">Created</th>
                                    <th width="15%">Updated</th>
                                    <th width="15%">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $query = mysqli_query($con, "SELECT * FROM category ORDER BY id DESC");
                                $cnt = 1;
                                while ($row = mysqli_fetch_array($query)) {
                                    ?>
                                    <tr>
                                        <td><?php echo $cnt; ?></td>
                                        <td>
                                            <span class="badge bg-secondary">
                                                <?php echo htmlentities($row['categoryName']); ?>
                                            </span>
                                        </td>
                                        <td><?php echo date('M d, Y', strtotime($row['creationDate'])); ?></td>
                                        <td><?php echo date('M d, Y', strtotime($row['updationDate'])); ?></td>
                                        <td>
                                            <a href="edit-category.php?id=<?php echo $row['id']; ?>"
                                                class="btn btn-sm btn-outline-primary" title="Edit Category">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <a href="manage-categories.php?id=<?php echo $row['id']; ?>&del=delete"
                                                class="btn btn-sm btn-outline-danger" title="Delete Category"
                                                onclick="return confirm('Are you sure you want to delete this category?')">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php $cnt++;
                                } ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </main>
            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
        crossorigin="anonymous"></script>
    <script src="js/scripts.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/simple-datatables@latest" crossorigin="anonymous"></script>
    <script src="js/datatables-simple-demo.js"></script>
</body>

</html>