<?php
/**
 * Dashboard - Main Entry Point
 * Research Survey Management System
 */

define('PAGE_TITLE', 'Dashboard');
require_once __DIR__ . '/includes/functions.php';

// If not logged in, redirect to the public homepage
if (!isLoggedIn()) {
    header('Location: ' . BASE_URL . '/home.php');
    exit;
}

$pdo = getDBConnection();

// Get dashboard statistics
$stats = [];

// Total surveys
$stmt = $pdo->prepare("SELECT COUNT(*) FROM surveys");
$stmt->execute();
$stats['total_surveys'] = $stmt->fetchColumn();

// Active surveys
$stmt = $pdo->prepare("SELECT COUNT(*) FROM surveys WHERE status = 'active'");
$stmt->execute();
$stats['active_surveys'] = $stmt->fetchColumn();

// Total responses
$stmt = $pdo->prepare("SELECT COUNT(*) FROM survey_responses WHERE status = 'completed'");
$stmt->execute();
$stats['total_responses'] = $stmt->fetchColumn();

// Total projects
$stmt = $pdo->prepare("SELECT COUNT(*) FROM research_projects");
$stmt->execute();
$stats['total_projects'] = $stmt->fetchColumn();

// Active projects
$stmt = $pdo->prepare("SELECT COUNT(*) FROM research_projects WHERE status = 'active'");
$stmt->execute();
$stats['active_projects'] = $stmt->fetchColumn();

// Total users
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE is_active = 1");
$stmt->execute();
$stats['total_users'] = $stmt->fetchColumn();

// Recent surveys
$stmt = $pdo->prepare("
    SELECT s.*, u.full_name as creator_name,
           COUNT(DISTINCT sr.response_id) as response_count
    FROM surveys s
    JOIN users u ON s.created_by = u.user_id
    LEFT JOIN survey_responses sr ON s.survey_id = sr.survey_id
    GROUP BY s.survey_id
    ORDER BY s.created_at DESC
    LIMIT 5
");
$stmt->execute();
$recent_surveys = $stmt->fetchAll();

// Recent responses
$stmt = $pdo->prepare("
    SELECT sr.*, s.title as survey_title
    FROM survey_responses sr
    JOIN surveys s ON sr.survey_id = s.survey_id
    WHERE sr.status = 'completed'
    ORDER BY sr.completed_at DESC
    LIMIT 5
");
$stmt->execute();
$recent_responses = $stmt->fetchAll();

// Survey type distribution
$stmt = $pdo->prepare("
    SELECT survey_type, COUNT(*) as count 
    FROM surveys 
    GROUP BY survey_type
");
$stmt->execute();
$type_distribution = $stmt->fetchAll();

// Response rate over time (last 7 days)
$stmt = $pdo->prepare("
    SELECT DATE(completed_at) as date, COUNT(*) as count
    FROM survey_responses
    WHERE completed_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    AND status = 'completed'
    GROUP BY DATE(completed_at)
    ORDER BY date
");
$stmt->execute();
$response_trend = $stmt->fetchAll();

require_once __DIR__ . '/includes/header.php';
?>

<div class="dashboard-header">
    <div>
        <h1>
            <i class="fas fa-tachometer-alt me-2 text-primary"></i>Dashboard
        </h1>
        <p>Welcome back, <?php echo htmlspecialchars($_SESSION['user_name']); ?>!</p>
    </div>
    <div>
        <a href="<?php echo BASE_URL; ?>/pages/create_survey.php" class="btn btn-primary">
            <i class="fas fa-plus me-1"></i> New Survey
        </a>
    </div>
</div>

<!-- Statistics Cards - Matches LMS admin dashboard -->
<div class="row g-3 mb-4">
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-number text-primary"><?php echo $stats['total_surveys']; ?></div>
            <div class="stat-label">Total Surveys</div>
            <small class="text-muted"><?php echo $stats['active_surveys']; ?> active</small>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-number text-success"><?php echo $stats['total_responses']; ?></div>
            <div class="stat-label">Total Responses</div>
            <small class="text-muted">Completed responses</small>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-number" style="color: #6366f1;"><?php echo $stats['total_projects']; ?></div>
            <div class="stat-label">Projects</div>
            <small class="text-muted"><?php echo $stats['active_projects']; ?> active</small>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-number" style="color: #f59e0b;"><?php echo $stats['total_users']; ?></div>
            <div class="stat-label">Users</div>
            <small class="text-muted">Active accounts</small>
        </div>
    </div>
</div>

<div class="row g-3">
    <!-- Survey Type Distribution -->
    <div class="col-md-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white border-bottom-0">
                <h5 class="card-title mb-0"><i class="fas fa-chart-pie me-2 text-primary"></i>Survey Types</h5>
            </div>
            <div class="card-body">
                <canvas id="surveyTypeChart" height="200"></canvas>
                <div class="mt-3">
                    <?php foreach ($type_distribution as $type): ?>
                    <div class="d-flex justify-content-between mb-1">
                        <span class="text-capitalize"><?php echo $type['survey_type']; ?></span>
                        <span class="badge bg-primary rounded-pill"><?php echo $type['count']; ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Response Trend -->
    <div class="col-md-8">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white border-bottom-0">
                <h5 class="card-title mb-0"><i class="fas fa-chart-line me-2 text-success"></i>Response Trend (Last 7 Days)</h5>
            </div>
            <div class="card-body">
                <canvas id="responseTrendChart" height="100"></canvas>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mt-2">
    <!-- Recent Surveys -->
    <div class="col-md-6">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0"><i class="fas fa-clock me-2 text-primary"></i>Recent Surveys</h5>
                <a href="<?php echo BASE_URL; ?>/pages/surveys.php" class="btn btn-sm btn-outline-primary">View All</a>
            </div>
            <div class="card-body p-0">
                <div class="list-group list-group-flush">
                    <?php if (empty($recent_surveys)): ?>
                    <div class="list-group-item text-center text-muted py-4">
                        <i class="fas fa-inbox fa-2x mb-2 d-block"></i>
                        No surveys created yet
                    </div>
                    <?php else: ?>
                    <?php foreach ($recent_surveys as $survey): ?>
                    <div class="list-group-item">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <a href="<?php echo BASE_URL; ?>/pages/view_survey.php?id=<?php echo $survey['survey_id']; ?>" 
                                   class="text-decoration-none fw-medium">
                                    <?php echo htmlspecialchars($survey['title']); ?>
                                </a>
                                <br>
                                <small class="text-muted">
                                    <i class="fas fa-user me-1"></i><?php echo htmlspecialchars($survey['creator_name']); ?>
                                    <i class="fas fa-calendar ms-2 me-1"></i><?php echo formatDate($survey['created_at'], 'M d'); ?>
                                </small>
                            </div>
                            <div class="text-end">
                                <?php echo getStatusBadge($survey['status']); ?>
                                <br>
                                <small class="text-muted"><?php echo $survey['response_count']; ?> responses</small>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Recent Responses -->
    <div class="col-md-6">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0"><i class="fas fa-reply-all me-2 text-success"></i>Recent Responses</h5>
                <a href="<?php echo BASE_URL; ?>/pages/responses.php" class="btn btn-sm btn-outline-success">View All</a>
            </div>
            <div class="card-body p-0">
                <div class="list-group list-group-flush">
                    <?php if (empty($recent_responses)): ?>
                    <div class="list-group-item text-center text-muted py-4">
                        <i class="fas fa-inbox fa-2x mb-2 d-block"></i>
                        No responses recorded yet
                    </div>
                    <?php else: ?>
                    <?php foreach ($recent_responses as $response): ?>
                    <div class="list-group-item">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <strong><?php echo htmlspecialchars($response['survey_title']); ?></strong>
                                <br>
                                <small class="text-muted">
                                    <i class="fas fa-clock me-1"></i><?php echo formatDate($response['completed_at']); ?>
                                </small>
                            </div>
                            <small class="text-muted">
                                <?php echo $response['time_spent_seconds'] ? formatDuration($response['time_spent_seconds']) : 'N/A'; ?>
                            </small>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Survey Type Chart
    const typeCtx = document.getElementById('surveyTypeChart').getContext('2d');
    new Chart(typeCtx, {
        type: 'doughnut',
        data: {
            labels: <?php echo json_encode(array_column($type_distribution, 'survey_type')); ?>,
            datasets: [{
                data: <?php echo json_encode(array_column($type_distribution, 'count')); ?>,
                backgroundColor: ['#4e73df', '#1cc88a', '#f6c23e'],
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: { padding: 15 }
                }
            }
        }
    });
    
    // Response Trend Chart
    const trendCtx = document.getElementById('responseTrendChart').getContext('2d');
    new Chart(trendCtx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode(array_column($response_trend, 'date')); ?>,
            datasets: [{
                label: 'Responses',
                data: <?php echo json_encode(array_column($response_trend, 'count')); ?>,
                borderColor: '#1cc88a',
                backgroundColor: 'rgba(28, 200, 138, 0.1)',
                fill: true,
                tension: 0.4,
                pointBackgroundColor: '#1cc88a'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: { stepSize: 1 }
                }
            }
        }
    });
});
</script>

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