<?php
/**
 * ============================================================================
 * extension/dashboard.php
 * Hierarchical Extension Officer Dashboard
 * ============================================================================
 */

// Variables should already be available from index.php:
// $db, $extensionSystem, $currentUserId

// Load base layout (will use existing $extensionSystem if available)
require_once __DIR__ . '/includes/base.php';
// Get dashboard statistics
$stats = $extensionSystem->getDashboardStats();

// Get upcoming services
$sql = "SELECT es.*, COUNT(sp.id) as participants_count
        FROM extension_services es
        LEFT JOIN service_participants sp ON es.id = sp.service_id
        WHERE es.officer_id = ? AND es.status = 'scheduled' AND es.scheduled_date >= CURDATE()
        GROUP BY es.id
        ORDER BY es.scheduled_date ASC
        LIMIT 5";
$stmt = $db->prepare($sql);
$stmt->execute([$currentUserId]);
$upcomingServices = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get recent feedback
$sql = "SELECT sp.feedback, sp.rating, es.title as service_title, u.full_name as farmer_name, sp.registered_at
        FROM service_participants sp
        JOIN extension_services es ON sp.service_id = es.id
        JOIN users u ON sp.user_id = u.id
        WHERE es.officer_id = ? AND sp.feedback IS NOT NULL
        ORDER BY sp.registered_at DESC
        LIMIT 5";
$stmt = $db->prepare($sql);
$stmt->execute([$currentUserId]);
$recentFeedback = $stmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Extension Dashboard - AIMS';
$breadcrumbs = [];

renderExtensionHeader($pageTitle, $breadcrumbs);
?>

<style>
.stat-card {
    border-radius: 15px;
    transition: all 0.3s ease;
    border: none;
    background: white;
}

.stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgba(0,0,0,0.1);
}

.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.8rem;
}

.service-card {
    border-left: 4px solid var(--primary-color);
    transition: all 0.3s ease;
}

.service-card:hover {
    background-color: #f9fafb;
}

.welcome-banner {
    background: linear-gradient(135deg, #059669 0%, #10b981 100%);
    border-radius: 15px;
}

.rating-stars {
    color: #f59e0b;
}
</style>

<div class="container-fluid py-4">
    <!-- Welcome Banner -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm welcome-banner">
                <div class="card-body text-white p-4">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h3 class="mb-2 fw-bold">Welcome, <?php echo htmlspecialchars($userName); ?>! 🌱</h3>
                            <p class="mb-2 opacity-90">
                                <span class="badge bg-white bg-opacity-25 me-2">
                                    <?php echo htmlspecialchars($extensionSystem->getRoleInfo()['role_name']); ?>
                                </span>
                                <?php if ($coverageArea): ?>
                                    <i class="bi bi-geo-alt me-1"></i><?php echo htmlspecialchars($coverageArea); ?>
                                <?php endif; ?>
                            </p>
                            <small class="opacity-75">
                                <?php 
                                if ($stats['subordinates_count'] > 0) {
                                    echo "Managing {$stats['subordinates_count']} extension workers";
                                } else {
                                    echo "Serving {$stats['total_farmers']} farmers in your coverage area";
                                }
                                ?>
                            </small>
                        </div>
                        <div class="col-md-4 text-md-end mt-3 mt-md-0">
                            <p class="mb-1"><i class="bi bi-calendar3 me-2"></i><?php echo date('l, F j, Y'); ?></p>
                            <p class="mb-0"><i class="bi bi-clock me-2"></i><?php echo date('g:i A'); ?></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Statistics -->
    <div class="row mb-4">
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stat-card shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 small">Farmers in Coverage</p>
                            <h3 class="mb-0 fw-bold"><?php echo number_format($stats['total_farmers']); ?></h3>
                            <small class="text-muted"><?php echo ucfirst($userLevel); ?> level</small>
                        </div>
                        <div class="stat-icon bg-success bg-opacity-10 text-success">
                            <i class="bi bi-people"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stat-card shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 small">Services This Month</p>
                            <h3 class="mb-0 fw-bold"><?php echo $stats['services_this_month']; ?></h3>
                        </div>
                        <div class="stat-icon bg-primary bg-opacity-10 text-primary">
                            <i class="bi bi-calendar-event"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php if ($stats['subordinates_count'] > 0): ?>
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stat-card shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 small">Team Members</p>
                            <h3 class="mb-0 fw-bold"><?php echo $stats['subordinates_count']; ?></h3>
                            <small class="text-muted">Extension workers</small>
                        </div>
                        <div class="stat-icon bg-info bg-opacity-10 text-info">
                            <i class="bi bi-diagram-3"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stat-card shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 small">Pending Reports</p>
                            <h3 class="mb-0 fw-bold"><?php echo $stats['pending_reports']; ?></h3>
                        </div>
                        <div class="stat-icon bg-warning bg-opacity-10 text-warning">
                            <i class="bi bi-file-earmark-text"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Main Content -->
        <div class="col-lg-8">
            <!-- Quick Actions -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-0 py-3">
                    <h5 class="mb-0 fw-bold">
                        <i class="bi bi-lightning-charge text-warning me-2"></i>Quick Actions
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row g-3">
                        <?php if ($extensionSystem->hasPermission('conduct_visits') || $extensionSystem->hasPermission('conduct_training')): ?>
                        <div class="col-md-3 col-6">
                            <a href="<?php echo APP_URL; ?>/extension/schedule-service.php" class="btn btn-outline-primary w-100 py-3">
                                <i class="bi bi-calendar-plus fs-4 d-block mb-2"></i>
                                <span class="fw-semibold small">Schedule Service</span>
                            </a>
                        </div>
                        <?php endif; ?>

                        <div class="col-md-3 col-6">
                            <a href="<?php echo APP_URL; ?>/extension/services.php" class="btn btn-outline-success w-100 py-3">
                                <i class="bi bi-list-check fs-4 d-block mb-2"></i>
                                <span class="fw-semibold small">My Services</span>
                            </a>
                        </div>

                        <div class="col-md-3 col-6">
                            <a href="<?php echo APP_URL; ?>/extension/farmers.php" class="btn btn-outline-info w-100 py-3">
                                <i class="bi bi-people fs-4 d-block mb-2"></i>
                                <span class="fw-semibold small">Farmers</span>
                            </a>
                        </div>

                        <?php if ($extensionSystem->hasPermission('submit_reports')): ?>
                        <div class="col-md-3 col-6">
                            <a href="<?php echo APP_URL; ?>/extension/reports.php" class="btn btn-outline-warning w-100 py-3">
                                <i class="bi bi-file-earmark-text fs-4 d-block mb-2"></i>
                                <span class="fw-semibold small">Reports</span>
                            </a>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Upcoming Services -->
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-0 py-3 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 fw-bold">
                        <i class="bi bi-calendar-check text-primary me-2"></i>Upcoming Services
                    </h5>
                    <a href="<?php echo APP_URL; ?>/extension/services.php" class="btn btn-sm btn-outline-primary">
                        View All <i class="bi bi-arrow-right ms-1"></i>
                    </a>
                </div>
                <div class="card-body">
                    <?php if (empty($upcomingServices)): ?>
                        <div class="text-center py-5">
                            <i class="bi bi-calendar-x text-muted" style="font-size: 4rem;"></i>
                            <h6 class="mt-3 text-muted">No upcoming services</h6>
                            <p class="text-muted small">Schedule a service to support farmers</p>
                            <?php if ($extensionSystem->hasPermission('conduct_visits') || $extensionSystem->hasPermission('conduct_training')): ?>
                            <a href="<?php echo APP_URL; ?>/extension/schedule-service.php" class="btn btn-primary mt-2">
                                <i class="bi bi-calendar-plus me-2"></i>Schedule Service
                            </a>
                            <?php endif; ?>
                        </div>
                    <?php else: ?>
                        <div class="list-group list-group-flush">
                            <?php foreach ($upcomingServices as $service): ?>
                            <div class="list-group-item service-card px-3 py-3 mb-2 rounded">
                                <div class="row align-items-center">
                                    <div class="col-md-7">
                                        <h6 class="mb-1"><?php echo htmlspecialchars($service['title']); ?></h6>
                                        <p class="mb-1 small text-muted">
                                            <i class="bi bi-geo-alt me-1"></i><?php echo htmlspecialchars($service['location']); ?>
                                        </p>
                                        <span class="badge bg-<?php echo $service['service_type'] == 'training' ? 'primary' : 'success'; ?> me-1">
                                            <?php echo ucfirst(str_replace('_', ' ', $service['service_type'])); ?>
                                        </span>
                                    </div>
                                    <div class="col-md-3 mt-2 mt-md-0">
                                        <p class="mb-1 small">
                                            <i class="bi bi-calendar me-1"></i><?php echo date('M j, Y', strtotime($service['scheduled_date'])); ?>
                                        </p>
                                        <?php if ($service['scheduled_time']): ?>
                                            <p class="mb-1 small">
                                                <i class="bi bi-clock me-1"></i><?php echo date('g:i A', strtotime($service['scheduled_time'])); ?>
                                            </p>
                                        <?php endif; ?>
                                        <p class="mb-0 small">
                                            <i class="bi bi-people me-1"></i><?php echo $service['participants_count']; ?> registered
                                        </p>
                                    </div>
                                    <div class="col-md-2 text-md-end mt-2 mt-md-0">
                                        <a href="<?php echo APP_URL; ?>/extension/service-details.php?id=<?php echo $service['id']; ?>" class="btn btn-sm btn-outline-primary w-100">
                                            <i class="bi bi-eye"></i> View
                                        </a>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Sidebar -->
        <div class="col-lg-4">
            <!-- Recent Feedback -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-0 py-3">
                    <h5 class="mb-0 fw-bold">
                        <i class="bi bi-chat-left-text text-info me-2"></i>Recent Feedback
                    </h5>
                </div>
                <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                    <?php if (empty($recentFeedback)): ?>
                        <div class="text-center py-4">
                            <i class="bi bi-chat-left-text text-muted" style="font-size: 3rem;"></i>
                            <p class="text-muted small mb-0 mt-2">No feedback yet</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($recentFeedback as $feedback): ?>
                        <div class="mb-3 pb-3 border-bottom">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <h6 class="mb-0 small fw-semibold"><?php echo htmlspecialchars($feedback['farmer_name']); ?></h6>
                                <div class="rating-stars">
                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                        <i class="bi bi-star<?php echo $i <= $feedback['rating'] ? '-fill' : ''; ?>"></i>
                                    <?php endfor; ?>
                                </div>
                            </div>
                            <p class="mb-1 small text-muted"><?php echo htmlspecialchars($feedback['service_title']); ?></p>
                            <p class="mb-1 small"><?php echo htmlspecialchars($feedback['feedback']); ?></p>
                            <small class="text-muted">
                                <i class="bi bi-clock me-1"></i><?php echo timeAgo($feedback['registered_at']); ?>
                            </small>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Impact Summary -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-0 py-3">
                    <h5 class="mb-0 fw-bold">
                        <i class="bi bi-graph-up-arrow text-success me-2"></i>Your Impact
                    </h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <div class="d-flex justify-content-between mb-1">
                            <span class="small">Services This Month</span>
                            <span class="small fw-bold"><?php echo $stats['services_this_month']; ?></span>
                        </div>
                        <div class="progress" style="height: 8px;">
                            <div class="progress-bar bg-success" style="width: <?php echo min(100, ($stats['services_this_month'] / 10) * 100); ?>%"></div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <div class="d-flex justify-content-between mb-1">
                            <span class="small">Farmers in Coverage</span>
                            <span class="small fw-bold"><?php echo number_format($stats['total_farmers']); ?></span>
                        </div>
                    </div>

                    <?php if ($stats['subordinates_count'] > 0): ?>
                    <div class="mb-0">
                        <div class="d-flex justify-content-between mb-1">
                            <span class="small">Team Members</span>
                            <span class="small fw-bold">
                                <a href="<?php echo APP_URL; ?>/extension/subordinates.php">
                                    <?php echo $stats['subordinates_count']; ?> <i class="bi bi-arrow-right"></i>
                                </a>
                            </span>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Quick Links -->
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-0 py-3">
                    <h5 class="mb-0 fw-bold">
                        <i class="bi bi-link-45deg text-primary me-2"></i>Quick Links
                    </h5>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <a href="<?php echo APP_URL; ?>/extension/resources.php" class="btn btn-outline-primary btn-sm">
                            <i class="bi bi-book me-2"></i>Extension Resources
                        </a>
                        <a href="<?php echo APP_URL; ?>/learning/tips.php" class="btn btn-outline-success btn-sm">
                            <i class="bi bi-lightbulb me-2"></i>Agricultural Tips
                        </a>
                        <a href="<?php echo APP_URL; ?>/market/prices.php" class="btn btn-outline-info btn-sm">
                            <i class="bi bi-graph-up me-2"></i>Market Prices
                        </a>
                        <a href="<?php echo APP_URL; ?>/extension/help.php" class="btn btn-outline-secondary btn-sm">
                            <i class="bi bi-question-circle me-2"></i>Help & Guidelines
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php renderExtensionFooter(); ?>