<?php
/**
 * Statistics Management
 */

session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/security.php';
require_once __DIR__ . '/includes/auth.php';

checkAdminAuth();

$pdo = getDBConnection();
$message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'create';
    $id = intval($_POST['id'] ?? 0);
    
    $value = intval($_POST['value'] ?? 0);
    $suffix = sanitizeInput($_POST['suffix'] ?? '');
    $label = sanitizeInput($_POST['label'] ?? '');
    $iconClass = sanitizeInput($_POST['icon_class'] ?? '');
    $color = sanitizeInput($_POST['color'] ?? '#00B4D8');
    $displayOrder = intval($_POST['display_order'] ?? 0);
    $status = sanitizeInput($_POST['status'] ?? 'active');
    
    if (empty($label)) {
        $message = 'Label is required.';
    } else {
        if ($action === 'create') {
            $stmt = $pdo->prepare("
                INSERT INTO statistics (value, suffix, label, icon_class, color, display_order, status) 
                VALUES (:value, :suffix, :label, :icon, :color, :order, :status)
            ");
            $stmt->execute([
                ':value' => $value,
                ':suffix' => $suffix,
                ':label' => $label,
                ':icon' => $iconClass,
                ':color' => $color,
                ':order' => $displayOrder,
                ':status' => $status
            ]);
            $message = 'Statistic created successfully!';
        } else {
            $stmt = $pdo->prepare("
                UPDATE statistics SET value = :value, suffix = :suffix, label = :label, 
                icon_class = :icon, color = :color, display_order = :order, status = :status 
                WHERE id = :id
            ");
            $stmt->execute([
                ':value' => $value,
                ':suffix' => $suffix,
                ':label' => $label,
                ':icon' => $iconClass,
                ':color' => $color,
                ':order' => $displayOrder,
                ':status' => $status,
                ':id' => $id
            ]);
            $message = 'Statistic updated successfully!';
        }
    }
}

// Handle delete
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $pdo->prepare("DELETE FROM statistics WHERE id = :id")->execute([':id' => $id]);
    $message = 'Statistic deleted successfully!';
}

// Get edit item
$editItem = null;
if (isset($_GET['edit'])) {
    $id = intval($_GET['edit']);
    $stmt = $pdo->prepare("SELECT * FROM statistics WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $editItem = $stmt->fetch();
}

// Get all statistics
$statistics = $pdo->query("
    SELECT * FROM statistics ORDER BY display_order ASC, created_at DESC
")->fetchAll();

$pageTitle = 'Statistics';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - Admin Panel</title>
    <link rel="stylesheet" href="assets/admin-modern.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
    <?php 
    $GLOBALS['pdo'] = $pdo;
    include 'includes/sidebar.php'; 
    ?>
    
    <div class="admin-main">
        <?php include 'includes/header-new.php'; ?>
        
        <div class="admin-container">
            <?php if ($message): ?>
                <div class="message success"><?php echo htmlspecialchars($message); ?></div>
            <?php endif; ?>
            
            <!-- Add/Edit Form -->
            <div class="card slide-up">
                <div class="card-header">
                    <h3 class="card-title"><?php echo $editItem ? 'Edit Statistic' : 'Add New Statistic'; ?></h3>
                </div>
                <form method="POST" style="padding: 1.5rem;">
                    <input type="hidden" name="action" value="<?php echo $editItem ? 'update' : 'create'; ?>">
                    <?php if ($editItem): ?>
                        <input type="hidden" name="id" value="<?php echo $editItem['id']; ?>">
                    <?php endif; ?>
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 1rem;">
                        <div class="form-group">
                            <label class="form-label">Value *</label>
                            <input type="number" name="value" class="form-control" required
                                   value="<?php echo htmlspecialchars($editItem['value'] ?? 0); ?>" min="0">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Suffix</label>
                            <input type="text" name="suffix" class="form-control"
                                   value="<?php echo htmlspecialchars($editItem['suffix'] ?? ''); ?>"
                                   placeholder="e.g., %, +, hrs, M+">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Color</label>
                            <input type="color" name="color" class="form-control"
                                   value="<?php echo htmlspecialchars($editItem['color'] ?? '#00B4D8'); ?>"
                                   style="height: 40px;">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Label *</label>
                        <input type="text" name="label" class="form-control" required
                               value="<?php echo htmlspecialchars($editItem['label'] ?? ''); ?>"
                               placeholder="e.g., Average mobilization">
                    </div>
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                        <div class="form-group">
                            <label class="form-label">Icon Class (Font Awesome)</label>
                            <input type="text" name="icon_class" class="form-control"
                                   value="<?php echo htmlspecialchars($editItem['icon_class'] ?? ''); ?>"
                                   placeholder="e.g., fa-clock">
                            <small style="color: var(--text-secondary);">Use Font Awesome class names</small>
                        </div>
                        
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                            <div class="form-group">
                                <label class="form-label">Display Order</label>
                                <input type="number" name="display_order" class="form-control"
                                       value="<?php echo $editItem['display_order'] ?? 0; ?>">
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Status</label>
                                <select name="status" class="form-control">
                                    <option value="active" <?php echo ($editItem['status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Active</option>
                                    <option value="inactive" <?php echo ($editItem['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div style="margin-top: 1.5rem;">
                        <button type="submit" class="btn btn-primary">
                            <?php echo $editItem ? 'Update Statistic' : 'Create Statistic'; ?>
                        </button>
                        <?php if ($editItem): ?>
                            <a href="statistics.php" class="btn btn-secondary">Cancel</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
            
            <!-- Statistics List -->
            <div class="card slide-up" style="animation-delay: 0.1s; margin-top: 1.5rem;">
                <div class="card-header">
                    <h3 class="card-title">All Statistics (<?php echo count($statistics); ?>)</h3>
                </div>
                <div style="overflow-x: auto;">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Icon</th>
                                <th>Value</th>
                                <th>Label</th>
                                <th>Color</th>
                                <th>Order</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($statistics as $stat): ?>
                            <tr>
                                <td>
                                    <?php if ($stat['icon_class']): ?>
                                        <i class="<?php echo htmlspecialchars($stat['icon_class']); ?>" 
                                           style="font-size: 1.5rem; color: <?php echo htmlspecialchars($stat['color']); ?>;"></i>
                                    <?php else: ?>
                                        <span style="font-size: 1.5rem;">—</span>
                                    <?php endif; ?>
                                </td>
                                <td><strong><?php echo $stat['value']; ?><?php echo htmlspecialchars($stat['suffix']); ?></strong></td>
                                <td><?php echo htmlspecialchars($stat['label']); ?></td>
                                <td>
                                    <span style="display: inline-block; width: 30px; height: 30px; background: <?php echo htmlspecialchars($stat['color']); ?>; border-radius: 4px; border: 1px solid var(--border-color);"></span>
                                </td>
                                <td><?php echo $stat['display_order']; ?></td>
                                <td>
                                    <span class="badge badge-<?php echo $stat['status'] === 'active' ? 'success' : 'danger'; ?>">
                                        <?php echo ucfirst($stat['status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <div style="display: flex; gap: 0.5rem;">
                                        <a href="?edit=<?php echo $stat['id']; ?>" class="btn btn-primary" style="padding: 0.375rem 0.75rem; font-size: 0.875rem;">Edit</a>
                                        <a href="?delete=<?php echo $stat['id']; ?>" 
                                           class="btn" 
                                           style="padding: 0.375rem 0.75rem; font-size: 0.875rem; background: var(--danger-color, #EF4444); color: white;"
                                           onclick="return confirm('Are you sure you want to delete this statistic?')">Delete</a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <script src="assets/admin.js"></script>
</body>
</html>

