<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../includes/functions.php';

requireLogin();

// Check if user is admin
$currentUser = getCurrentUser();
if ($currentUser['role'] !== 'admin') {
    header('Location: dashboard.php');
    exit;
}

$db = getDB();

// Get date range for analytics (default to last 30 days)
$startDate = $_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
$endDate = $_GET['end_date'] ?? date('Y-m-d');

// Get AI usage statistics
$stats = [
    'total_requests' => 0,
    'total_cost' => 0.00,
    'avg_response_time' => 0,
    'success_rate' => 0,
    'features_breakdown' => [],
    'daily_usage' => [],
    'top_users' => [],
    'cost_trends' => []
];

try {
    // Overall statistics
    $stmt = $db->prepare("
        SELECT
            COUNT(*) as total_requests,
            COALESCE(SUM(cost), 0) as total_cost,
            COALESCE(AVG(response_time_ms), 0) as avg_response_time,
            COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) / COUNT(*) * 100, 0) as success_rate
        FROM ai_usage_logs
        WHERE DATE(created_at) BETWEEN ? AND ?
    ");
    $stmt->execute([$startDate, $endDate]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    $stats = array_merge($stats, $result);

    // Feature breakdown
    $stmt = $db->prepare("
        SELECT
            feature,
            COUNT(*) as requests,
            COALESCE(SUM(cost), 0) as cost,
            COALESCE(AVG(response_time_ms), 0) as avg_time,
            COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) / COUNT(*) * 100, 0) as success_rate
        FROM ai_usage_logs
        WHERE DATE(created_at) BETWEEN ? AND ?
        GROUP BY feature
        ORDER BY requests DESC
    ");
    $stmt->execute([$startDate, $endDate]);
    $stats['features_breakdown'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Daily usage trends
    $stmt = $db->prepare("
        SELECT
            DATE(created_at) as date,
            COUNT(*) as requests,
            COALESCE(SUM(cost), 0) as cost,
            COALESCE(AVG(response_time_ms), 0) as avg_time
        FROM ai_usage_logs
        WHERE DATE(created_at) BETWEEN ? AND ?
        GROUP BY DATE(created_at)
        ORDER BY date
    ");
    $stmt->execute([$startDate, $endDate]);
    $stats['daily_usage'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Top users by usage
    $stmt = $db->prepare("
        SELECT
            u.username,
            u.email,
            COUNT(*) as requests,
            COALESCE(SUM(aul.cost), 0) as total_cost,
            MAX(aul.created_at) as last_used
        FROM ai_usage_logs aul
        JOIN users u ON aul.user_id = u.id
        WHERE DATE(aul.created_at) BETWEEN ? AND ?
        GROUP BY aul.user_id, u.username, u.email
        ORDER BY requests DESC
        LIMIT 10
    ");
    $stmt->execute([$startDate, $endDate]);
    $stats['top_users'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Cost trends by feature
    $stmt = $db->prepare("
        SELECT
            feature,
            DATE(created_at) as date,
            COALESCE(SUM(cost), 0) as daily_cost
        FROM ai_usage_logs
        WHERE DATE(created_at) BETWEEN ? AND ?
        GROUP BY feature, DATE(created_at)
        ORDER BY date, feature
    ");
    $stmt->execute([$startDate, $endDate]);
    $stats['cost_trends'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (Exception $e) {
    // Handle database errors gracefully
    error_log("AI Analytics Error: " . $e->getMessage());
}

$page_title = 'AI Analytics';
include 'includes/admin_header.php';
?>

<div class="analytics-container">
    <div class="analytics-header">
        <h2>AI Usage Analytics</h2>
        <div class="date-filters">
            <form method="GET" class="date-form">
                <div class="form-group">
                    <label for="start_date">Start Date:</label>
                    <input type="date" id="start_date" name="start_date" value="<?php echo htmlspecialchars($startDate); ?>" required>
                </div>
                <div class="form-group">
                    <label for="end_date">End Date:</label>
                    <input type="date" id="end_date" name="end_date" value="<?php echo htmlspecialchars($endDate); ?>" required>
                </div>
                <button type="submit" class="btn btn-primary">Update</button>
            </form>
        </div>
    </div>

    <!-- Key Metrics -->
    <div class="metrics-grid">
        <div class="metric-card">
            <div class="metric-value"><?php echo number_format($stats['total_requests']); ?></div>
            <div class="metric-label">Total AI Requests</div>
            <div class="metric-period"><?php echo htmlspecialchars($startDate); ?> to <?php echo htmlspecialchars($endDate); ?></div>
        </div>
        <div class="metric-card">
            <div class="metric-value">$<?php echo number_format($stats['total_cost'], 2); ?></div>
            <div class="metric-label">Total Cost</div>
            <div class="metric-period">AI API Costs</div>
        </div>
        <div class="metric-card">
            <div class="metric-value"><?php echo number_format($stats['avg_response_time'], 0); ?>ms</div>
            <div class="metric-label">Avg Response Time</div>
            <div class="metric-period">API Response Speed</div>
        </div>
        <div class="metric-card">
            <div class="metric-value"><?php echo number_format($stats['success_rate'], 1); ?>%</div>
            <div class="metric-label">Success Rate</div>
            <div class="metric-period">API Call Success</div>
        </div>
    </div>

    <!-- Feature Usage Breakdown -->
    <div class="analytics-card">
        <h3>AI Feature Usage Breakdown</h3>
        <div class="features-table-container">
            <table class="features-table">
                <thead>
                    <tr>
                        <th>Feature</th>
                        <th>Requests</th>
                        <th>Cost</th>
                        <th>Avg Response Time</th>
                        <th>Success Rate</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($stats['features_breakdown'] as $feature): ?>
                        <tr>
                            <td><?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $feature['feature']))); ?></td>
                            <td><?php echo number_format($feature['requests']); ?></td>
                            <td>$<?php echo number_format($feature['cost'], 2); ?></td>
                            <td><?php echo number_format($feature['avg_time'], 0); ?>ms</td>
                            <td><?php echo number_format($feature['success_rate'], 1); ?>%</td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Daily Usage Chart -->
    <div class="analytics-card">
        <h3>Daily Usage Trends</h3>
        <div class="chart-container">
            <canvas id="usageChart" width="400" height="200"></canvas>
        </div>
    </div>

    <!-- Top Users -->
    <div class="analytics-card">
        <h3>Top AI Users</h3>
        <div class="users-table-container">
            <table class="users-table">
                <thead>
                    <tr>
                        <th>User</th>
                        <th>Requests</th>
                        <th>Total Cost</th>
                        <th>Last Used</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($stats['top_users'] as $user): ?>
                        <tr>
                            <td>
                                <div class="user-info">
                                    <strong><?php echo htmlspecialchars($user['username']); ?></strong>
                                    <small><?php echo htmlspecialchars($user['email']); ?></small>
                                </div>
                            </td>
                            <td><?php echo number_format($user['requests']); ?></td>
                            <td>$<?php echo number_format($user['total_cost'], 2); ?></td>
                            <td><?php echo htmlspecialchars(date('M j, Y H:i', strtotime($user['last_used']))); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Cost Trends by Feature -->
    <div class="analytics-card">
        <h3>Cost Trends by Feature</h3>
        <div class="chart-container">
            <canvas id="costChart" width="400" height="200"></canvas>
        </div>
    </div>
</div>

<style>
.analytics-container {
    max-width: 1200px;
    margin: 0 auto;
}

.analytics-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2rem;
}

.analytics-header h2 {
    font-size: 1.875rem;
    font-weight: 700;
    color: #1f2937;
    margin: 0;
}

.date-filters {
    display: flex;
    gap: 1rem;
    align-items: end;
}

.date-form {
    display: flex;
    gap: 1rem;
    align-items: end;
}

.date-form .form-group {
    margin-bottom: 0;
}

.date-form .form-group label {
    display: block;
    font-weight: 500;
    color: #374151;
    margin-bottom: 0.5rem;
    font-size: 0.875rem;
}

.date-form input[type="date"] {
    padding: 0.5rem;
    border: 1px solid #d1d5db;
    border-radius: 0.375rem;
    font-size: 0.875rem;
}

/* Metrics Grid */
.metrics-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 1.5rem;
    margin-bottom: 2rem;
}

.metric-card {
    background: white;
    padding: 1.5rem;
    border-radius: 0.75rem;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    text-align: center;
}

.metric-value {
    font-size: 2.5rem;
    font-weight: 700;
    color: #1e293b;
    margin-bottom: 0.5rem;
}

.metric-label {
    font-size: 1rem;
    color: #64748b;
    font-weight: 500;
    margin-bottom: 0.25rem;
}

.metric-period {
    font-size: 0.75rem;
    color: #94a3b8;
}

/* Analytics Cards */
.analytics-card {
    background: white;
    padding: 2rem;
    border-radius: 0.75rem;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 2rem;
}

.analytics-card h3 {
    font-size: 1.25rem;
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 1.5rem;
}

/* Tables */
.features-table-container,
.users-table-container {
    overflow-x: auto;
}

.features-table,
.users-table {
    width: 100%;
    border-collapse: collapse;
}

.features-table th,
.features-table td,
.users-table th,
.users-table td {
    padding: 0.75rem;
    text-align: left;
    border-bottom: 1px solid #e5e7eb;
}

.features-table th,
.users-table th {
    background: #f8fafc;
    font-weight: 600;
    color: #374151;
    font-size: 0.875rem;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}

.features-table tbody tr:hover,
.users-table tbody tr:hover {
    background: #f8fafc;
}

.user-info strong {
    display: block;
    color: #1f2937;
    margin-bottom: 0.25rem;
}

.user-info small {
    color: #64748b;
    font-size: 0.75rem;
}

/* Charts */
.chart-container {
    position: relative;
    height: 300px;
    width: 100%;
}

.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 0.5rem 1rem;
    border-radius: 0.375rem;
    font-size: 0.875rem;
    font-weight: 500;
    text-decoration: none;
    border: none;
    cursor: pointer;
    transition: all 0.2s;
}

.btn-primary {
    background-color: #2563eb;
    color: white;
}

.btn-primary:hover {
    background-color: #1d4ed8;
}

.form-group {
    margin-bottom: 1rem;
}

.form-group label {
    display: block;
    font-weight: 500;
    color: #374151;
    margin-bottom: 0.5rem;
}

.form-group input {
    width: 100%;
    padding: 0.5rem;
    border: 1px solid #d1d5db;
    border-radius: 0.375rem;
    font-size: 0.875rem;
}
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Daily Usage Chart
const usageCtx = document.getElementById('usageChart').getContext('2d');
const usageData = <?php echo json_encode($stats['daily_usage']); ?>;

new Chart(usageCtx, {
    type: 'line',
    data: {
        labels: usageData.map(item => new Date(item.date).toLocaleDateString()),
        datasets: [{
            label: 'Requests',
            data: usageData.map(item => item.requests),
            borderColor: '#2563eb',
            backgroundColor: 'rgba(37, 99, 235, 0.1)',
            tension: 0.4
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});

// Cost Trends Chart
const costCtx = document.getElementById('costChart').getContext('2d');
const costData = <?php echo json_encode($stats['cost_trends']); ?>;

// Group cost data by feature
const costByFeature = {};
costData.forEach(item => {
    if (!costByFeature[item.feature]) {
        costByFeature[item.feature] = [];
    }
    costByFeature[item.feature].push(item);
});

const datasets = Object.keys(costByFeature).map(feature => ({
    label: feature.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase()),
    data: costByFeature[feature].map(item => item.daily_cost),
    borderColor: getRandomColor(),
    backgroundColor: 'transparent',
    tension: 0.4
}));

const uniqueDates = [...new Set(costData.map(item => item.date))].sort();

new Chart(costCtx, {
    type: 'line',
    data: {
        labels: uniqueDates.map(date => new Date(date).toLocaleDateString()),
        datasets: datasets
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    callback: function(value) {
                        return '$' + value.toFixed(2);
                    }
                }
            }
        }
    }
});

function getRandomColor() {
    const colors = ['#2563eb', '#dc2626', '#16a34a', '#ca8a04', '#9333ea', '#0891b2', '#be123c'];
    return colors[Math.floor(Math.random() * colors.length)];
}
</script>

<?php include 'includes/admin_footer.php'; ?>