<?php
require_once __DIR__ . "/../auth/init.php";
authorize();

require_once __DIR__ . "/../config/db.php";

/* =========================
   ADD CATEGORY
========================= */
if (isset($_POST['add_category'])) {

    $name = trim($_POST['name']);
    $department_id = intval($_POST['department_id']);

    if ($name != "" && $department_id > 0) {

        $stmt = mysqli_prepare($conn, "INSERT INTO categories (name, department_id) VALUES (?, ?)");
        mysqli_stmt_bind_param($stmt, "si", $name, $department_id);
        mysqli_stmt_execute($stmt);

        $_SESSION['cat_success'] = "Category added successfully.";
    } else {
        $_SESSION['cat_error'] = "Please fill all fields.";
    }

    header("Location: Category.php");
    exit();
}

/* =========================
   DELETE CATEGORY
========================= */
if (isset($_GET['delete'])) {

    $id = intval($_GET['delete']);

    $stmt = mysqli_prepare($conn, "DELETE FROM categories WHERE id=?");
    mysqli_stmt_bind_param($stmt, "i", $id);
    mysqli_stmt_execute($stmt);

    $_SESSION['cat_success'] = "Category deleted successfully.";

    header("Location: Category.php");
    exit();
}

/* =========================
   FETCH DATA
========================= */
$result = mysqli_query($conn, "
    SELECT c.*, d.name AS department_name
    FROM categories c
    LEFT JOIN departments d ON c.department_id = d.id
    ORDER BY c.id DESC
");

$deptResult = mysqli_query($conn, "SELECT id, name FROM departments ORDER BY name ASC");
?>

<!DOCTYPE html>
<html>
<head>
    <title>Category Management - QRCareTrack</title>

    <link rel="stylesheet" href="../assets/style.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">

    <style>
        .box {
            background:#fff;
            padding:20px;
            border-radius:12px;
        }

        .top-actions {
            display:flex;
            justify-content:space-between;
            align-items:center;
            gap:10px;
            margin-bottom:15px;
            flex-wrap:wrap;
        }

        .form-inline {
            display:flex;
            gap:10px;
            align-items:center;
            flex-wrap:wrap;
        }

        .form-inline input, .form-inline select {
            padding:10px;
            border:1px solid #ddd;
            border-radius:8px;
        }

        .btn {
            padding:10px 14px;
            border:none;
            border-radius:8px;
            cursor:pointer;
            font-weight:500;
        }

        .btn.primary { background:#2ecc71; color:#fff; }
        .btn.danger { background:#e74c3c; color:#fff; }
        .btn.back { background:#7f8c8d; color:#fff; text-decoration:none; }

        table {
            width:100%;
            border-collapse:collapse;
            margin-top:15px;
        }

        table th {
            background:#f8f9fa;
            text-align:left;
            padding:12px;
        }

        table td {
            padding:12px;
            border-bottom:1px solid #eee;
        }

        .alert {
            padding:10px;
            border-radius:8px;
            margin-bottom:10px;
        }

        .success { background:#e8fff1; color:#1e7e34; }
        .error { background:#ffe8e8; color:#c0392b; }
    </style>
</head>

<body>

<?php include __DIR__ . "/../includes/sidebar.php"; ?>

<div class="main">

    <h1>Category Management</h1>
    <p>Each category is assigned to a department.</p>

    <!-- ALERT -->
    <?php if(isset($_SESSION['cat_success'])): ?>
        <div class="alert success"><?= $_SESSION['cat_success']; unset($_SESSION['cat_success']); ?></div>
    <?php endif; ?>

    <?php if(isset($_SESSION['cat_error'])): ?>
        <div class="alert error"><?= $_SESSION['cat_error']; unset($_SESSION['cat_error']); ?></div>
    <?php endif; ?>

    <div class="box">

        <!-- TOP -->
        <div class="top-actions">

            <a href="../items.php" class="btn back">
                <i class="fas fa-arrow-left"></i> Back
            </a>

            <!-- ADD FORM -->
            <form method="POST" class="form-inline">

                <input type="text" name="name" placeholder="Category name" required>

                <select name="department_id" required>
                    <option value="">Select Department</option>
                    <?php while($d = mysqli_fetch_assoc($deptResult)): ?>
                        <option value="<?= $d['id'] ?>">
                            <?= htmlspecialchars($d['name']) ?>
                        </option>
                    <?php endwhile; ?>
                </select>

                <button class="btn primary" name="add_category">
                    <i class="fas fa-plus"></i> Add
                </button>
            </form>

        </div>

        <!-- TABLE -->
        <table>
            <tr>
                <th>ID</th>
                <th>Category</th>
                <th>Department</th>
                <th>Created At</th>
                <th>Action</th>
            </tr>

            <?php while($row = mysqli_fetch_assoc($result)): ?>
                <tr>
                    <td><?= $row['id'] ?></td>
                    <td><?= htmlspecialchars($row['name']) ?></td>
                    <td><?= htmlspecialchars($row['department_name'] ?? '-') ?></td>
                    <td><?= date("d M Y H:i", strtotime($row['created_at'])) ?></td>
                    <td>
                        <a href="Category.php?delete=<?= $row['id'] ?>"
                           class="btn danger"
                           onclick="return confirm('Delete category?')">
                            Delete
                        </a>
                    </td>
                </tr>
            <?php endwhile; ?>

        </table>

    </div>
</div>

</body>
</html>