<?php
ob_start();
$pageTitle = 'Product Types';
require_once __DIR__ . '/includes/header.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'create' || $action === 'update') {
        $typeId      = $_POST['type_id'] ?? '';
        $name        = trim($_POST['name'] ?? '');
        $slug        = trim($_POST['slug'] ?? '') ?: slugify($name);
        $description = trim($_POST['description'] ?? '');
        $isActive    = isset($_POST['is_active']) ? 1 : 0;

        if (empty($name)) {
            setFlash('error', 'Product type name is required');
        } else {
            $data = ['name'=>$name,'slug'=>$slug,'description'=>$description,'is_active'=>$isActive];
            if ($action === 'update' && $typeId) {
                db()->update('product_types', $data, 'type_id = :id', ['id' => $typeId]);
                setFlash('success', 'Product type updated');
            } else {
                $data['type_id'] = generateId('pt_');
                db()->insert('product_types', $data);
                setFlash('success', 'Product type created');
            }
        }
        header('Location: /admin/product-types.php');
        exit;
    }

    if ($action === 'delete' && !empty($_POST['type_id'])) {
        db()->delete('product_types', 'type_id = :id', ['id' => $_POST['type_id']]);
        setFlash('success', 'Product type deleted');
        header('Location: /admin/product-types.php');
        exit;
    }
}

$types = db()->fetchAll(
    "SELECT pt.*, COUNT(p.product_id) AS product_count
     FROM product_types pt
     LEFT JOIN products p ON p.product_type_id = pt.type_id AND p.is_active = 1
     GROUP BY pt.type_id
     ORDER BY pt.name ASC"
);
?>

<div class="page-header">
    <h1 class="page-title">Product Types</h1>
    <button class="btn btn-primary" onclick="openTypeModal()">
        <i class="fas fa-plus"></i> Add Product Type
    </button>
</div>

<?php if (hasFlash('success')): ?>
    <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= getFlash('success') ?></div>
<?php endif; ?>
<?php if (hasFlash('error')): ?>
    <div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> <?= getFlash('error') ?></div>
<?php endif; ?>

<div class="admin-card">
    <div class="admin-card-body" style="padding: 0;">
        <table class="admin-table">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Slug</th>
                    <th>Description</th>
                    <th>Products</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($types)): ?>
                    <tr><td colspan="6" class="text-muted" style="text-align:center;padding:2rem">No product types yet. Create one above.</td></tr>
                <?php else: ?>
                    <?php foreach ($types as $t): ?>
                        <tr>
                            <td><strong><?= htmlspecialchars($t['name']) ?></strong></td>
                            <td class="text-muted"><?= htmlspecialchars($t['slug']) ?></td>
                            <td class="text-muted"><?= htmlspecialchars(substr($t['description'] ?? '', 0, 60)) ?></td>
                            <td>
                                <a href="/admin/products.php?type=<?= urlencode($t['type_id']) ?>" style="font-weight: 600;">
                                    <?= (int)$t['product_count'] ?>
                                </a>
                            </td>
                            <td>
                                <?php if ($t['is_active']): ?>
                                    <span class="badge badge-success">Active</span>
                                <?php else: ?>
                                    <span class="badge badge-error">Hidden</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-secondary" onclick='openTypeModal(<?= json_encode($t) ?>)'>
                                    <i class="fas fa-edit"></i>
                                </button>
                                <form method="POST" style="display: inline;">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="type_id" value="<?= htmlspecialchars($t['type_id']) ?>">
                                    <button type="submit" class="btn btn-sm btn-danger" data-confirm="Delete this product type?">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal-overlay" id="typeModal">
    <div class="modal">
        <div class="modal-header">
            <h3 class="modal-title" id="typeModalTitle">Add Product Type</h3>
            <button type="button" class="modal-close" onclick="Modal.close('typeModal')">&times;</button>
        </div>
        <form method="POST">
            <div class="modal-body">
                <input type="hidden" name="action" id="typeAction" value="create">
                <input type="hidden" name="type_id" id="typeId">

                <div class="form-group">
                    <label class="form-label">Product Type Name *</label>
                    <input type="text" name="name" id="typeName" class="form-input" required>
                </div>

                <div class="form-group">
                    <label class="form-label">Slug</label>
                    <input type="text" name="slug" id="typeSlug" class="form-input" placeholder="auto-generated if empty">
                </div>

                <div class="form-group">
                    <label class="form-label">Description</label>
                    <textarea name="description" id="typeDesc" class="form-textarea" rows="2"></textarea>
                </div>

                <div class="form-group mb-0">
                    <label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
                        <input type="checkbox" name="is_active" id="typeActive" checked>
                        Active (visible in product forms)
                    </label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="Modal.close('typeModal')">Cancel</button>
                <button type="submit" class="btn btn-primary" id="typeSubmitBtn">Add Product Type</button>
            </div>
        </form>
    </div>
</div>

<script>
function openTypeModal(type) {
    type = type || null;
    var isEdit = !!type;
    document.getElementById('typeModalTitle').textContent = isEdit ? 'Edit Product Type' : 'Add Product Type';
    document.getElementById('typeSubmitBtn').textContent  = isEdit ? 'Update Product Type' : 'Add Product Type';
    document.getElementById('typeAction').value           = isEdit ? 'update' : 'create';
    document.getElementById('typeId').value               = isEdit ? type.type_id : '';
    document.getElementById('typeName').value             = isEdit ? type.name : '';
    document.getElementById('typeSlug').value             = isEdit ? type.slug : '';
    document.getElementById('typeDesc').value             = isEdit ? (type.description || '') : '';
    document.getElementById('typeActive').checked         = isEdit ? type.is_active == 1 : true;
    Modal.open('typeModal');
}
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
