<?php
/**
 * ============================================================================
 * dashboard/extension-dashboard.php
 * Extension Officer dashboard for managing services and farmers
 * ============================================================================
 */

if (!defined('AIMS_ACCESS')) {
    die('Direct access not permitted');
}

$userId = getUserId();
$userName = getUserName();

$database = new Database();
$db = $database->getConnection();

// Extension Officer Statistics
$stats = [];

// Total Services
$sql = "SELECT COUNT(*) as total FROM extension_services WHERE officer_id = ?";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$stats['total_services'] = $stmt->fetch()['total'] ?? 0;

// Scheduled Services
$sql = "SELECT COUNT(*) as total FROM extension_services 
        WHERE officer_id = ? AND status = 'scheduled' AND scheduled_date >= CURDATE()";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$stats['scheduled_services'] = $stmt->fetch()['total'] ?? 0;

// Completed Services
$sql = "SELECT COUNT(*) as total FROM extension_services 
        WHERE officer_id = ? AND status = 'completed'";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$stats['completed_services'] = $stmt->fetch()['total'] ?? 0;

// Total Farmers Reached
$sql = "SELECT COUNT(DISTINCT sp.user_id) as total 
        FROM service_participants sp
        JOIN extension_services es ON sp.service_id = es.id
        WHERE es.officer_id = ?";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$stats['farmers_reached'] = $stmt->fetch()['total'] ?? 0;

// Average Rating
$sql = "SELECT AVG(sp.rating) as avg_rating, COUNT(sp.rating) as total_ratings
        FROM service_participants sp
        JOIN extension_services es ON sp.service_id = es.id
        WHERE es.officer_id = ? AND sp.rating IS NOT NULL";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$ratingData = $stmt->fetch();
$stats['avg_rating'] = round($ratingData['avg_rating'] ?? 0, 1);
$stats['total_ratings'] = $ratingData['total_ratings'] ?? 0;

// 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([$userId]);
$upcomingServices = $stmt->fetchAll();

// 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([$userId]);
$recentFeedback = $stmt->fetchAll();

$pageTitle = 'Extension Officer Dashboard - AIMS';
require_once '../includes/meta.php';
?>

<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;
    }
    
    @media (max-width: 768px) {
        body {
            padding-bottom: 100px;
        }
    }
</style>
</head>
<body>

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

<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, Officer <?php echo htmlspecialchars($userName); ?>! 🌱</h3>
                            <p class="mb-0 opacity-90">Supporting farmers in Luuka District</p>
                        </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">Total Services</p>
                            <h3 class="mb-0 fw-bold"><?php echo $stats['total_services']; ?></h3>
                            <small class="text-muted"><?php echo $stats['completed_services']; ?> completed</small>
                        </div>
                        <div class="stat-icon bg-primary bg-opacity-10 text-primary">
                            <i class="bi bi-calendar-event"></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">Upcoming Services</p>
                            <h3 class="mb-0 fw-bold"><?php echo $stats['scheduled_services']; ?></h3>
                        </div>
                        <div class="stat-icon bg-warning bg-opacity-10 text-warning">
                            <i class="bi bi-clock"></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">Farmers Reached</p>
                            <h3 class="mb-0 fw-bold"><?php echo $stats['farmers_reached']; ?></h3>
                        </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">Average Rating</p>
                            <h3 class="mb-0 fw-bold">
                                <?php echo $stats['avg_rating']; ?> 
                                <i class="bi bi-star-fill rating-stars fs-6"></i>
                            </h3>
                            <small class="text-muted"><?php echo $stats['total_ratings']; ?> ratings</small>
                        </div>
                        <div class="stat-icon bg-info bg-opacity-10 text-info">
                            <i class="bi bi-award"></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">
                        <div class="col-md-3 col-6">
                            <a href="<?php echo APP_URL; ?>/extension/add-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>
                        <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>
                        <div class="col-md-3 col-6">
                            <a href="<?php echo APP_URL; ?>/learning/" class="btn btn-outline-warning w-100 py-3">
                                <i class="bi bi-book fs-4 d-block mb-2"></i>
                                <span class="fw-semibold small">Resources</span>
                            </a>
                        </div>
                    </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>
                            <a href="<?php echo APP_URL; ?>/extension/add-service.php" class="btn btn-primary mt-2">
                                <i class="bi bi-calendar-plus me-2"></i>Schedule Service
                            </a>
                        </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">
                                        <span class="badge bg-success"><?php echo ucfirst($service['status']); ?></span>
                                        <a href="<?php echo APP_URL; ?>/extension/service-details.php?id=<?php echo $service['id']; ?>" class="btn btn-sm btn-outline-primary mt-2 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 Completed</span>
                            <span class="small fw-bold"><?php echo $stats['completed_services']; ?>/<?php echo $stats['total_services']; ?></span>
                        </div>
                        <div class="progress" style="height: 8px;">
                            <?php 
                            $completion_rate = $stats['total_services'] > 0 ? ($stats['completed_services'] / $stats['total_services']) * 100 : 0;
                            ?>
                            <div class="progress-bar bg-success" style="width: <?php echo $completion_rate; ?>%"></div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="d-flex justify-content-between mb-1">
                            <span class="small">Farmers Reached</span>
                            <span class="small fw-bold"><?php echo $stats['farmers_reached']; ?></span>
                        </div>
                        <p class="mb-0 text-muted" style="font-size: 0.75rem;">
                            Keep up the great work supporting local farmers!
                        </p>
                    </div>
                </div>
            </div>

            <!-- Resources -->
            <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-book text-warning me-2"></i>Resources
                    </h5>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <a href="<?php echo APP_URL; ?>/learning/tips.php" class="btn btn-outline-primary btn-sm">
                            <i class="bi bi-lightbulb me-2"></i>Agricultural Tips
                        </a>
                        <a href="<?php echo APP_URL; ?>/extension/reports.php" class="btn btn-outline-success btn-sm">
                            <i class="bi bi-file-earmark-text me-2"></i>View Reports
                        </a>
                        <a href="<?php echo APP_URL; ?>/learning/training-materials.php" class="btn btn-outline-info btn-sm">
                            <i class="bi bi-collection me-2"></i>Training Materials
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php require_once '../includes/bottom-nav.php'; ?>
<?php require_once '../includes/footer.php'; ?>