<?php
require_once __DIR__ . '/config.php';
requireAdmin();
$pdo = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_POST['delete_id'])) {
        $pdo->prepare("DELETE FROM stats_counters WHERE id = ?")->execute([(int)$_POST['delete_id']]);
    } elseif (isset($_POST['action']) && $_POST['action'] === 'add') {
        $pdo->prepare("INSERT INTO stats_counters (value, label, sort_order) VALUES (?, ?, ?)")->execute([
            trim($_POST['value'] ?? ''),
            trim($_POST['label'] ?? ''),
            (int)($_POST['sort_order'] ?? 0)
        ]);
    } elseif (isset($_POST['action']) && $_POST['action'] === 'save' && !empty($_POST['id'])) {
        $pdo->prepare("UPDATE stats_counters SET value=?, label=?, sort_order=?, is_active=? WHERE id=?")->execute([
            trim($_POST['value'] ?? ''),
            trim($_POST['label'] ?? ''),
            (int)($_POST['sort_order'] ?? 0),
            isset($_POST['is_active']) ? 1 : 0,
            (int)$_POST['id']
        ]);
    }
    header('Location: stats.php');
    exit;
}

try {
    $stats = $pdo->query("SELECT * FROM stats_counters ORDER BY sort_order, id")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $stats = [];
}
$pageTitle = 'Stats / Client section';
require_once __DIR__ . '/includes/header.php';
?>
<div class="admin-page">
    <h1>Stats counters <small style="font-weight:400;color:#666">(home client section)</small></h1>
    <?php if (empty($stats) && !isset($_GET['setup'])): ?>
    <p class="error">Table <code>stats_counters</code> missing. Import <code>database/client_footer.sql</code> in phpMyAdmin.</p>
    <?php endif; ?>
    <form method="post" class="admin-form inline-form" style="margin-bottom:20px;">
        <input type="hidden" name="action" value="add">
        <input type="text" name="value" placeholder="e.g. 6+" required>
        <input type="text" name="label" placeholder="e.g. Year of Excellence" required>
        <input type="number" name="sort_order" placeholder="Order" value="0">
        <button type="submit" class="btn">Add counter</button>
    </form>
    <table class="admin-table">
        <thead><tr><th>Order</th><th>Value</th><th>Label</th><th>Active</th><th>Actions</th></tr></thead>
        <tbody>
            <?php foreach ($stats as $s): ?>
            <tr>
                <td><?php echo (int)$s['sort_order']; ?></td>
                <td><?php echo htmlspecialchars($s['value']); ?></td>
                <td><?php echo htmlspecialchars($s['label']); ?></td>
                <td><?php echo $s['is_active'] ? 'Yes' : 'No'; ?></td>
                <td>
                    <form method="post" style="display:inline;" onsubmit="return confirm('Delete?');">
                        <input type="hidden" name="delete_id" value="<?php echo (int)$s['id']; ?>">
                        <button type="submit" class="link-btn">Delete</button>
                    </form>
                </td>
            </tr>
            <tr>
                <td colspan="5">
                    <form method="post" style="display:flex;flex-wrap:wrap;gap:8px;align-items:center;">
                        <input type="hidden" name="action" value="save">
                        <input type="hidden" name="id" value="<?php echo (int)$s['id']; ?>">
                        <input type="text" name="value" value="<?php echo htmlspecialchars($s['value']); ?>" style="width:80px;">
                        <input type="text" name="label" value="<?php echo htmlspecialchars($s['label']); ?>" style="width:200px;">
                        <input type="number" name="sort_order" value="<?php echo (int)$s['sort_order']; ?>" style="width:70px;">
                        <label><input type="checkbox" name="is_active" value="1" <?php echo $s['is_active'] ? 'checked' : ''; ?>> Active</label>
                        <button type="submit" class="btn">Save</button>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <p><a href="home-sections.php">Edit headline &amp; image</a></p>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
