<?php
$message = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'create':
                $name = sanitize_input($_POST['name']);
                $description = sanitize_input($_POST['description']);
                $color = sanitize_input($_POST['color']);

                if ($category->create($name, $description, $color)) {
                    $message = __('category_created');
                } else {
                    $error = __('category_create_failed');
                }
                break;

            case 'update':
                $id = (int)$_POST['id'];
                $name = sanitize_input($_POST['name']);
                $description = sanitize_input($_POST['description']);
                $color = sanitize_input($_POST['color']);

                if ($category->update($id, $name, $description, $color)) {
                    $message = __('category_updated');
                } else {
                    $error = __('category_update_failed');
                }
                break;

            case 'delete':
                $id = (int)$_POST['id'];
                if ($category->delete($id)) {
                    $message = __('category_deleted');
                } else {
                    $error = __('category_delete_failed');
                }
                break;
        }
    }
}

$categories = $category->getAll();
$editCategory = null;

if (isset($_GET['edit'])) {
    $editCategory = $category->getById((int)$_GET['edit']);
}
?>

<div class="row">
    <div class="col-lg-8">
        <?php if ($message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle"></i> <?= htmlspecialchars($message) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">
                    <i class="fas fa-tags"></i> <?= __('categories') ?>
                </h5>
                <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#categoryModal">
                    <i class="fas fa-plus"></i> <?= __('add_category') ?>
                </button>
            </div>
            <div class="card-body">
                <?php if (empty($categories)): ?>
                    <div class="text-center py-4">
                        <i class="fas fa-tags fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted"><?= __('no_categories') ?></h5>
                        <p class="text-muted"><?= __('create_first_category') ?></p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover data-table">
                            <thead>
                                <tr>
                                    <th data-sortable><?= __('name') ?></th>
                                    <th data-sortable><?= __('description') ?></th>
                                    <th><?= __('color') ?></th>
                                    <th data-sortable><?= __('articles_count') ?></th>
                                    <th data-sortable><?= __('created_at') ?></th>
                                    <th width="120"><?= __('actions') ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($categories as $cat): ?>
                                    <tr>
                                        <td>
                                            <strong><?= htmlspecialchars($cat['name']) ?></strong>
                                        </td>
                                        <td>
                                            <span class="text-muted"><?= htmlspecialchars($cat['description']) ?></span>
                                        </td>
                                        <td>
                                            <span class="badge" style="background-color: <?= htmlspecialchars($cat['color']) ?>">
                                                <?= htmlspecialchars($cat['color']) ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge bg-secondary"><?= $article->getCount(null, $cat['id']) ?></span>
                                        </td>
                                        <td>
                                            <small class="text-muted"><?= date('Y-m-d', strtotime($cat['created_at'])) ?></small>
                                        </td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <button type="button" class="btn btn-outline-primary"
                                                        onclick="editCategory(<?= $cat['id'] ?>, '<?= htmlspecialchars($cat['name']) ?>', '<?= htmlspecialchars($cat['description']) ?>', '<?= htmlspecialchars($cat['color']) ?>')">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <form method="POST" class="d-inline" onsubmit="return confirm('<?= __('confirm_delete_category') ?>')">
                                                    <input type="hidden" name="action" value="delete">
                                                    <input type="hidden" name="id" value="<?= $cat['id'] ?>">
                                                    <button type="submit" class="btn btn-outline-danger">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-chart-pie"></i> <?= __('category_stats') ?>
                </h5>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <span><?= __('total_categories') ?>:</span>
                        <span class="badge bg-primary"><?= count($categories) ?></span>
                    </div>
                </div>

                <?php if (!empty($categories)): ?>
                    <div class="mt-3">
                        <h6><?= __('articles_by_category') ?></h6>
                        <?php foreach (array_slice($categories, 0, 5) as $cat): ?>
                            <?php $articleCount = $article->getCount(null, $cat['id']); ?>
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="small">
                                    <span class="badge me-1" style="background-color: <?= htmlspecialchars($cat['color']) ?>; width: 12px; height: 12px;"></span>
                                    <?= htmlspecialchars($cat['name']) ?>
                                </span>
                                <span class="badge bg-secondary"><?= $articleCount ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Category Modal -->
<div class="modal fade" id="categoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" id="categoryForm" data-validate>
                <div class="modal-header">
                    <h5 class="modal-title" id="categoryModalTitle">
                        <i class="fas fa-tag"></i> <?= __('add_category') ?>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="action" value="create" id="categoryAction">
                    <input type="hidden" name="id" id="categoryId">

                    <div class="mb-3">
                        <label for="categoryName" class="form-label"><?= __('category_name') ?></label>
                        <input type="text" class="form-control" id="categoryName" name="name" required>
                    </div>

                    <div class="mb-3">
                        <label for="categoryDescription" class="form-label"><?= __('description') ?></label>
                        <textarea class="form-control" id="categoryDescription" name="description" rows="3"></textarea>
                    </div>

                    <div class="mb-3">
                        <label for="categoryColor" class="form-label"><?= __('color') ?></label>
                        <div class="input-group">
                            <input type="color" class="form-control form-control-color" id="categoryColor" name="color" value="#007cba">
                            <input type="text" class="form-control" id="categoryColorText" readonly>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <?= __('cancel') ?>
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> <?= __('save') ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Color picker sync
document.getElementById('categoryColor').addEventListener('input', function() {
    document.getElementById('categoryColorText').value = this.value;
});

// Initialize color text
document.getElementById('categoryColorText').value = document.getElementById('categoryColor').value;

// Edit category function
function editCategory(id, name, description, color) {
    document.getElementById('categoryModalTitle').innerHTML = '<i class="fas fa-edit"></i> <?= __('edit_category') ?>';
    document.getElementById('categoryAction').value = 'update';
    document.getElementById('categoryId').value = id;
    document.getElementById('categoryName').value = name;
    document.getElementById('categoryDescription').value = description;
    document.getElementById('categoryColor').value = color;
    document.getElementById('categoryColorText').value = color;

    new bootstrap.Modal(document.getElementById('categoryModal')).show();
}

// Reset modal on close
document.getElementById('categoryModal').addEventListener('hidden.bs.modal', function() {
    document.getElementById('categoryModalTitle').innerHTML = '<i class="fas fa-tag"></i> <?= __('add_category') ?>';
    document.getElementById('categoryAction').value = 'create';
    document.getElementById('categoryForm').reset();
    document.getElementById('categoryColorText').value = '#007cba';
});
</script>