<?php
session_start();
require_once('../config.php');

// Check if user is logged in and is admin
if (!is_logged_in()) {
    redirect(BASE_URL . 'login.php');
}

$user = get_current_user();
if (!$user || $user['role'] !== 'admin') {
    redirect(BASE_URL . 'admin-dashboard.php');
}

$categories = [];
$error = '';
$success = '';

// Fetch all categories
try {
    global $pdo;
    $stmt = $pdo->prepare("SELECT id, name, description, display_order FROM form_categories ORDER BY display_order ASC");
    $stmt->execute();
    $categories = $stmt->fetchAll();
} catch (Exception $e) {
    $error = 'Error loading categories: ' . $e->getMessage();
}

// Handle add/edit category
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_category') {
    $category_id = $_POST['category_id'] ?? null;
    $category_name = trim($_POST['category_name'] ?? '');
    $category_desc = trim($_POST['category_description'] ?? '');
    $display_order = intval($_POST['display_order'] ?? 0);

    if (empty($category_name)) {
        $error = 'Category name is required';
    } else {
        try {
            global $pdo;
            if ($category_id) {
                // Update existing
                $stmt = $pdo->prepare("UPDATE form_categories SET name = ?, description = ?, display_order = ? WHERE id = ?");
                if ($stmt->execute([$category_name, $category_desc, $display_order, $category_id])) {
                    $success = 'Category updated successfully';
                }
            } else {
                // Insert new
                $stmt = $pdo->prepare("INSERT INTO form_categories (name, description, display_order) VALUES (?, ?, ?)");
                if ($stmt->execute([$category_name, $category_desc, $display_order])) {
                    $success = 'Category created successfully';
                }
            }
            // Refresh categories list
            $stmt = $pdo->prepare("SELECT id, name, description, display_order FROM form_categories ORDER BY display_order ASC");
            $stmt->execute();
            $categories = $stmt->fetchAll();
        } catch (Exception $e) {
            $error = 'Error saving category: ' . $e->getMessage();
        }
    }
}

// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_category') {
    $category_id = intval($_POST['category_id'] ?? 0);
    if ($category_id > 0) {
        try {
            global $pdo;
            $stmt = $pdo->prepare("DELETE FROM form_categories WHERE id = ?");
            if ($stmt->execute([$category_id])) {
                $success = 'Category deleted successfully';
                // Refresh
                $stmt = $pdo->prepare("SELECT id, name, description, display_order FROM form_categories ORDER BY display_order ASC");
                $stmt->execute();
                $categories = $stmt->fetchAll();
            }
        } catch (Exception $e) {
            $error = 'Error deleting category: ' . $e->getMessage();
        }
    }
}

// Handle logout
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'logout') {
    session_destroy();
    redirect(BASE_URL . 'login.php');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Categories - Document Signing System</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header h1 {
            font-size: 28px;
            margin: 0;
        }
        .user-info {
            text-align: right;
        }
        .user-info p {
            margin: 5px 0;
            font-size: 14px;
        }
        .logout-btn {
            background: #ff6b6b;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 600;
            margin-top: 10px;
            font-size: 14px;
        }
        .logout-btn:hover {
            background: #ff5252;
        }
        .nav-menu {
            background: #f8f9fa;
            padding: 15px 30px;
            border-bottom: 1px solid #ddd;
            display: flex;
            gap: 20px;
        }
        .nav-menu a {
            color: #667eea;
            text-decoration: none;
            font-weight: 600;
            padding: 10px 15px;
            border-bottom: 2px solid transparent;
        }
        .nav-menu a:hover, .nav-menu a.active {
            border-bottom-color: #667eea;
        }
        .content {
            padding: 40px;
        }
        .section {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 40px;
            margin-bottom: 40px;
        }
        .form-section {
            background: #f8f9fa;
            padding: 30px;
            border-radius: 8px;
        }
        .form-section h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #333;
            font-weight: 600;
            font-size: 14px;
        }
        .form-group input, .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            font-family: Arial, sans-serif;
        }
        .form-group textarea {
            min-height: 80px;
            resize: vertical;
        }
        .form-group input:focus, .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
        }
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
        }
        .btn-delete {
            background: #ff6b6b;
            padding: 8px 12px;
            font-size: 12px;
        }
        .btn-delete:hover {
            background: #ff5252;
            box-shadow: 0 5px 20px rgba(255, 107, 107, 0.4);
        }
        .alert {
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .alert-error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        .alert-success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .categories-list {
            background: white;
        }
        .categories-list h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 20px;
        }
        .category-item {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .category-info {
            flex: 1;
        }
        .category-name {
            color: #333;
            font-weight: 600;
            margin-bottom: 5px;
        }
        .category-desc {
            color: #999;
            font-size: 12px;
        }
        .category-actions {
            display: flex;
            gap: 10px;
        }
        .btn-edit {
            background: #667eea;
            padding: 8px 12px;
            font-size: 12px;
        }
        .btn-edit:hover {
            background: #5568d3;
        }
        @media (max-width: 768px) {
            .section {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📂 Manage Categories</h1>
            <div class="user-info">
                <p><strong><?php echo htmlspecialchars($user['garage_name'] ?? 'Garage'); ?></strong></p>
                <p><?php echo htmlspecialchars($user['username'] ?? 'User'); ?></p>
                <form method="POST" style="display: inline;">
                    <input type="hidden" name="action" value="logout">
                    <button type="submit" class="logout-btn">Logout</button>
                </form>
            </div>
        </div>

        <div class="nav-menu">
            <a href="<?php echo BASE_URL; ?>admin-dashboard.php">Dashboard</a>
            <a href="<?php echo BASE_URL; ?>manage-categories.php" class="active">Categories</a>
            <a href="<?php echo BASE_URL; ?>manage-forms.php">Forms</a>
            <a href="<?php echo BASE_URL; ?>customers.php">Customers</a>
        </div>

        <div class="content">
            <?php if ($error): ?>
                <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
            <?php endif; ?>

            <div class="section">
                <!-- Add/Edit Form -->
                <div class="form-section">
                    <h2>➕ Add New Category</h2>
                    <form method="POST">
                        <input type="hidden" name="action" value="save_category">
                        <input type="hidden" name="category_id" value="">

                        <div class="form-group">
                            <label for="category_name">Category Name *</label>
                            <input type="text" id="category_name" name="category_name" required placeholder="e.g., Service Records">
                        </div>

                        <div class="form-group">
                            <label for="category_description">Description</label>
                            <textarea id="category_description" name="category_description" placeholder="Brief description of this category"></textarea>
                        </div>

                        <div class="form-group">
                            <label for="display_order">Display Order</label>
                            <input type="number" id="display_order" name="display_order" value="0" min="0">
                        </div>

                        <button type="submit" class="btn">Create Category</button>
                    </form>
                </div>

                <!-- Categories List -->
                <div class="categories-list">
                    <h2>📋 All Categories (<?php echo count($categories); ?>)</h2>
                    <div>
                        <?php foreach ($categories as $cat): ?>
                            <div class="category-item">
                                <div class="category-info">
                                    <div class="category-name"><?php echo htmlspecialchars($cat['name']); ?></div>
                                    <div class="category-desc"><?php echo htmlspecialchars($cat['description'] ?? 'No description'); ?></div>
                                </div>
                                <div class="category-actions">
                                    <button class="btn btn-edit" onclick="editCategory(<?php echo $cat['id']; ?>, '<?php echo htmlspecialchars($cat['name']); ?>', '<?php echo htmlspecialchars($cat['description'] ?? ''); ?>', <?php echo $cat['display_order']; ?>)">Edit</button>
                                    <form method="POST" style="display: inline;" onsubmit="return confirm('Delete this category? Forms in it will also be deleted.');">
                                        <input type="hidden" name="action" value="delete_category">
                                        <input type="hidden" name="category_id" value="<?php echo $cat['id']; ?>">
                                        <button type="submit" class="btn btn-delete">Delete</button>
                                    </form>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        function editCategory(id, name, desc, order) {
            document.querySelector('input[name="category_id"]').value = id;
            document.querySelector('#category_name').value = name;
            document.querySelector('#category_description').value = desc;
            document.querySelector('#display_order').value = order;
            document.querySelector('h2').textContent = '✏️ Edit Category';
            document.querySelector('button[type="submit"]').textContent = 'Update Category';
            window.scrollTo(0, 0);
        }
    </script>
</body>
</html>
