<?php
session_start();
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}
include '../db.php';

// Handle update
if (isset($_POST['edit_id'], $_POST['new_name'])) {
    $stmt = $pdo->prepare("UPDATE categories SET name = ? WHERE id = ?");
    $stmt->execute([trim($_POST['new_name']), $_POST['edit_id']]);
}

// Handle delete
if (isset($_GET['delete_id'])) {
    $stmt = $pdo->prepare("DELETE FROM categories WHERE id = ?");
    $stmt->execute([$_GET['delete_id']]);
    header('Location: edit_categories.php');
    exit;
}

// Fetch all categories
$categories = $pdo->query("SELECT * FROM categories ORDER BY id DESC")->fetchAll();
?>

<?php include 'menu.php'; ?>
<!DOCTYPE html>
<html>
<head>
    <title>Edit Categories</title>
    <link rel="stylesheet" href="../style.css">
    <style>
        form.inline { display:inline; }
        input[type="text"] { padding:2px; }
    </style>
</head>
<body>
<div class="container">
    <h2>Edit / Delete Categories</h2>
    <table border="1" cellpadding="5">
        <tr>
            <th>ID</th><th>Name</th><th>Action</th>
        </tr>
        <?php foreach($categories as $cat): ?>
        <tr>
            <td><?= $cat['id'] ?></td>
            <td>
                <form method="POST" class="inline">
                    <input type="hidden" name="edit_id" value="<?= $cat['id'] ?>">
                    <input type="text" name="new_name" value="<?= htmlspecialchars($cat['name']) ?>" required>
                    <button type="submit">Update</button>
                </form>
            </td>
            <td>
                <a href="?delete_id=<?= $cat['id'] ?>" onclick="return confirm('Are you sure?');">Delete</a>
            </td>
        </tr>
        <?php endforeach; ?>
    </table>
    <p><a href="dashboard.php">Back to Dashboard</a></p>
</div>
</body>
</html>
