<?php
/**
 * ============================================================================
 * learning/index.php - Enhanced Learning Center Main Page
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Learning Center';
$userId = getUserId();
$userType = getUserType();

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

// Fetch stats
try {
    // Count agricultural tips
    $tips_count = $db->query("SELECT COUNT(*) FROM agricultural_tips WHERE is_published = 1")->fetchColumn();
    
    // Count diseases
    $diseases_count = $db->query("SELECT COUNT(*) FROM crop_diseases WHERE is_published = 1")->fetchColumn();
    
    // Count varieties
    $varieties_count = $db->query("SELECT COUNT(*) FROM crop_varieties WHERE is_published = 1")->fetchColumn();
    
    // Count schedules
    $schedules_count = $db->query("SELECT COUNT(*) FROM farming_schedules WHERE is_published = 1")->fetchColumn();
    
    // Count user's reminders
    $reminders_count = $db->query("SELECT COUNT(*) FROM user_farming_reminders WHERE user_id = {$userId} AND status = 'pending' AND reminder_date >= CURDATE()")->fetchColumn();
    
    // Get user's bookmarks
    $bookmarks_count = $db->query("SELECT COUNT(*) FROM learning_progress WHERE user_id = {$userId} AND status = 'bookmarked'")->fetchColumn();
} catch (PDOException $e) {
    $tips_count = $diseases_count = $varieties_count = $schedules_count = $reminders_count = $bookmarks_count = 0;
    error_log("Error fetching stats: " . $e->getMessage());
}

// Fetch latest agricultural tips
try {
    $sql = "SELECT * FROM agricultural_tips 
            WHERE is_published = 1 
            ORDER BY created_at DESC 
            LIMIT 6";
    $stmt = $db->query($sql);
    $tips = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $tips = [];
    error_log("Error fetching tips: " . $e->getMessage());
}

// Fetch latest diseases
try {
    $sql = "SELECT * FROM crop_diseases 
            WHERE is_published = 1 
            ORDER BY severity_level DESC, created_at DESC 
            LIMIT 3";
    $stmt = $db->query($sql);
    $latest_diseases = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $latest_diseases = [];
}

// Fetch upcoming reminders
try {
    $sql = "SELECT * FROM user_farming_reminders 
            WHERE user_id = ? 
            AND status = 'pending'
            AND reminder_date >= CURDATE()
            ORDER BY reminder_date, reminder_time
            LIMIT 3";
    $stmt = $db->prepare($sql);
    $stmt->execute([$userId]);
    $upcoming_reminders = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $upcoming_reminders = [];
}

// Include header
include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<div class="container-fluid py-4">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="text-center">
                <h1 class="mb-2">
                    <i class="bi bi-book text-primary"></i> Learning Center
                </h1>
                <p class="lead text-muted mb-0">Your complete guide to successful farming</p>
                <p class="text-muted">Access farming knowledge, schedules, and expert advice</p>
            </div>
        </div>
    </div>

    <!-- Stats Overview -->
    <div class="row mb-4">
        <div class="col-6 col-md-4 col-lg-2 mb-3">
            <div class="card border-0 shadow-sm h-100 stats-card">
                <div class="card-body text-center p-3">
                    <i class="bi bi-lightbulb text-warning" style="font-size: 2rem;"></i>
                    <h4 class="mb-0 mt-2"><?php echo $tips_count; ?></h4>
                    <small class="text-muted">Tips</small>
                </div>
            </div>
        </div>
        <div class="col-6 col-md-4 col-lg-2 mb-3">
            <div class="card border-0 shadow-sm h-100 stats-card">
                <div class="card-body text-center p-3">
                    <i class="bi bi-bug text-danger" style="font-size: 2rem;"></i>
                    <h4 class="mb-0 mt-2"><?php echo $diseases_count; ?></h4>
                    <small class="text-muted">Diseases</small>
                </div>
            </div>
        </div>
        <div class="col-6 col-md-4 col-lg-2 mb-3">
            <div class="card border-0 shadow-sm h-100 stats-card">
                <div class="card-body text-center p-3">
                    <i class="bi bi-tree text-success" style="font-size: 2rem;"></i>
                    <h4 class="mb-0 mt-2"><?php echo $varieties_count; ?></h4>
                    <small class="text-muted">Varieties</small>
                </div>
            </div>
        </div>
        <div class="col-6 col-md-4 col-lg-2 mb-3">
            <div class="card border-0 shadow-sm h-100 stats-card">
                <div class="card-body text-center p-3">
                    <i class="bi bi-calendar-check text-info" style="font-size: 2rem;"></i>
                    <h4 class="mb-0 mt-2"><?php echo $schedules_count; ?></h4>
                    <small class="text-muted">Schedules</small>
                </div>
            </div>
        </div>
        <div class="col-6 col-md-4 col-lg-2 mb-3">
            <div class="card border-0 shadow-sm h-100 stats-card">
                <div class="card-body text-center p-3">
                    <i class="bi bi-bell text-warning" style="font-size: 2rem;"></i>
                    <h4 class="mb-0 mt-2"><?php echo $reminders_count; ?></h4>
                    <small class="text-muted">Reminders</small>
                </div>
            </div>
        </div>
        <div class="col-6 col-md-4 col-lg-2 mb-3">
            <div class="card border-0 shadow-sm h-100 stats-card">
                <div class="card-body text-center p-3">
                    <i class="bi bi-bookmark text-primary" style="font-size: 2rem;"></i>
                    <h4 class="mb-0 mt-2"><?php echo $bookmarks_count; ?></h4>
                    <small class="text-muted">Bookmarks</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Learning Sections -->
    <div class="row mb-4">
        <div class="col-12">
            <h4 class="mb-3">
                <i class="bi bi-grid-3x3-gap"></i> Learning Sections
            </h4>
        </div>
    </div>

    <!-- Primary Learning Cards (Large) -->
    <div class="row mb-4">
        <div class="col-lg-4 col-md-6 mb-4">
            <div class="card border-0 shadow hover-lift h-100 section-card">
                <div class="card-header bg-danger text-white">
                    <h5 class="mb-0">
                        <i class="bi bi-bug"></i> Diseases & Pests
                    </h5>
                </div>
                <div class="card-body">
                    <p class="card-text">Identify, prevent, and treat crop diseases and pest infestations effectively.</p>
                    <ul class="list-unstyled mb-3">
                        <li><i class="bi bi-check-circle text-success"></i> <?php echo $diseases_count; ?> disease profiles</li>
                        <li><i class="bi bi-check-circle text-success"></i> Symptoms & treatments</li>
                        <li><i class="bi bi-check-circle text-success"></i> Prevention strategies</li>
                        <li><i class="bi bi-check-circle text-success"></i> Report outbreaks</li>
                    </ul>
                </div>
                <div class="card-footer bg-transparent border-0">
                    <a href="<?php echo APP_URL; ?>/learning/diseases.php" class="btn btn-danger w-100">
                        <i class="bi bi-arrow-right-circle"></i> Explore Diseases
                    </a>
                </div>
            </div>
        </div>

        <div class="col-lg-4 col-md-6 mb-4">
            <div class="card border-0 shadow hover-lift h-100 section-card">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0">
                        <i class="bi bi-calendar-check"></i> Farming Calendar
                    </h5>
                </div>
                <div class="card-body">
                    <p class="card-text">Plan your farming activities with seasonal guides and personalized reminders.</p>
                    <ul class="list-unstyled mb-3">
                        <li><i class="bi bi-check-circle text-success"></i> Seasonal calendar</li>
                        <li><i class="bi bi-check-circle text-success"></i> Activity schedules</li>
                        <li><i class="bi bi-check-circle text-success"></i> Cost estimates</li>
                        <li><i class="bi bi-check-circle text-success"></i> Personal reminders</li>
                    </ul>
                </div>
                <div class="card-footer bg-transparent border-0">
                    <a href="<?php echo APP_URL; ?>/learning/schedules.php" class="btn btn-success w-100">
                        <i class="bi bi-arrow-right-circle"></i> View Calendar
                    </a>
                </div>
            </div>
        </div>

        <div class="col-lg-4 col-md-6 mb-4">
            <div class="card border-0 shadow hover-lift h-100 section-card">
                <div class="card-header bg-info text-white">
                    <h5 class="mb-0">
                        <i class="bi bi-tree"></i> Crop Varieties
                    </h5>
                </div>
                <div class="card-body">
                    <p class="card-text">Compare and choose the best crop varieties for your farm and conditions.</p>
                    <ul class="list-unstyled mb-3">
                        <li><i class="bi bi-check-circle text-success"></i> <?php echo $varieties_count; ?> varieties</li>
                        <li><i class="bi bi-check-circle text-success"></i> Yield information</li>
                        <li><i class="bi bi-check-circle text-success"></i> Growing requirements</li>
                        <li><i class="bi bi-check-circle text-success"></i> Comparison tools</li>
                    </ul>
                </div>
                <div class="card-footer bg-transparent border-0">
                    <a href="<?php echo APP_URL; ?>/learning/varieties.php" class="btn btn-info w-100">
                        <i class="bi bi-arrow-right-circle"></i> Browse Varieties
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Secondary Learning Cards (Medium) -->
    <div class="row mb-4">
        <div class="col-md-4 mb-3">
            <div class="card h-100 border-0 shadow-sm hover-lift">
                <div class="card-body text-center p-4">
                    <div class="mb-3">
                        <i class="bi bi-camera-video text-danger" style="font-size: 3rem;"></i>
                    </div>
                    <h5 class="card-title">Video Tutorials</h5>
                    <p class="card-text text-muted">Watch step-by-step farming guides and demonstrations</p>
                    <a href="<?php echo APP_URL; ?>/learning/videos.php" class="btn btn-outline-danger">
                        Browse Videos <i class="bi bi-arrow-right"></i>
                    </a>
                </div>
            </div>
        </div>
        
        <div class="col-md-4 mb-3">
            <div class="card h-100 border-0 shadow-sm hover-lift">
                <div class="card-body text-center p-4">
                    <div class="mb-3">
                        <i class="bi bi-star-fill text-warning" style="font-size: 3rem;"></i>
                    </div>
                    <h5 class="card-title">Best Practices</h5>
                    <p class="card-text text-muted">Learn proven farming techniques for better yields</p>
                    <a href="<?php echo APP_URL; ?>/learning/best-practices.php" class="btn btn-outline-warning">
                        Read More <i class="bi bi-arrow-right"></i>
                    </a>
                </div>
            </div>
        </div>
        
        <div class="col-md-4 mb-3">
            <div class="card h-100 border-0 shadow-sm hover-lift">
                <div class="card-body text-center p-4">
                    <div class="mb-3">
                        <i class="bi bi-book text-primary" style="font-size: 3rem;"></i>
                    </div>
                    <h5 class="card-title">Resources</h5>
                    <p class="card-text text-muted">Download guides, manuals, and reference materials</p>
                    <a href="<?php echo APP_URL; ?>/learning/resources.php" class="btn btn-outline-primary">
                        View Resources <i class="bi bi-arrow-right"></i>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Upcoming Reminders Section -->
    <?php if (!empty($upcoming_reminders)): ?>
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-warning text-dark">
                    <h5 class="mb-0">
                        <i class="bi bi-bell"></i> Your Upcoming Activities
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <?php foreach ($upcoming_reminders as $reminder): ?>
                            <div class="col-md-4 mb-3">
                                <div class="alert alert-warning mb-0">
                                    <h6 class="mb-1">
                                        <i class="bi bi-calendar-event"></i> 
                                        <?php echo htmlspecialchars($reminder['title']); ?>
                                    </h6>
                                    <small class="text-muted d-block mb-2">
                                        <?php echo date('D, M j, Y', strtotime($reminder['reminder_date'])); ?>
                                        <?php if ($reminder['reminder_time']): ?>
                                            at <?php echo date('g:i A', strtotime($reminder['reminder_time'])); ?>
                                        <?php endif; ?>
                                    </small>
                                    <?php if ($reminder['description']): ?>
                                        <p class="mb-0 small"><?php echo htmlspecialchars($reminder['description']); ?></p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <div class="text-center mt-2">
                        <a href="<?php echo APP_URL; ?>/learning/schedules.php" class="btn btn-warning btn-sm">
                            View All Reminders <i class="bi bi-arrow-right"></i>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Latest Disease Alerts -->
    <?php if (!empty($latest_diseases)): ?>
    <div class="row mb-4">
        <div class="col-12">
            <h5 class="mb-3">
                <i class="bi bi-exclamation-triangle text-danger"></i> Recent Disease Information
            </h5>
        </div>
        <?php foreach ($latest_diseases as $disease): ?>
            <div class="col-md-4 mb-3">
                <div class="card border-danger border-2 h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <h6 class="card-title mb-0"><?php echo htmlspecialchars($disease['disease_name']); ?></h6>
                            <?php
                            $severity_colors = [
                                'low' => 'success',
                                'medium' => 'warning',
                                'high' => 'danger',
                                'critical' => 'dark'
                            ];
                            $badge_color = $severity_colors[$disease['severity_level']] ?? 'secondary';
                            ?>
                            <span class="badge bg-<?php echo $badge_color; ?>"><?php echo ucfirst($disease['severity_level']); ?></span>
                        </div>
                        <p class="small text-muted mb-2">
                            <i class="bi bi-flower3"></i> <?php echo ucwords(str_replace('_', ' ', $disease['crop_type'])); ?>
                        </p>
                        <p class="card-text small"><?php echo truncate(strip_tags($disease['symptoms']), 80); ?></p>
                        <a href="<?php echo APP_URL; ?>/learning/diseases.php?crop=<?php echo $disease['crop_type']; ?>" class="btn btn-sm btn-outline-danger">
                            Learn More <i class="bi bi-arrow-right"></i>
                        </a>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <!-- Latest Agricultural Tips -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0">
                    <i class="bi bi-lightbulb text-warning"></i> Latest Agricultural Tips
                </h5>
                <div class="btn-group btn-group-sm" role="group">
                    <button class="btn btn-sm btn-primary category-filter active" data-category="all">All</button>
                    <button class="btn btn-sm btn-outline-primary category-filter" data-category="crop_management">Crop</button>
                    <button class="btn btn-sm btn-outline-primary category-filter" data-category="pest_control">Pest</button>
                    <button class="btn btn-sm btn-outline-primary category-filter" data-category="soil_health">Soil</button>
                </div>
            </div>
        </div>
    </div>

    <div class="row" id="tipsContainer">
        <?php if (!empty($tips)): ?>
            <?php foreach ($tips as $tip): ?>
                <div class="col-md-6 col-lg-4 mb-4 tip-card" data-category="<?php echo htmlspecialchars($tip['category']); ?>">
                    <div class="card h-100 border-0 shadow-sm hover-lift">
                        <?php if (!empty($tip['media_url'])): ?>
                            <img src="<?php echo htmlspecialchars($tip['media_url']); ?>" 
                                 class="card-img-top" 
                                 alt="<?php echo htmlspecialchars($tip['title']); ?>"
                                 style="height: 200px; object-fit: cover;">
                        <?php else: ?>
                            <div class="bg-gradient text-white d-flex align-items-center justify-content-center" 
                                 style="height: 200px; background: linear-gradient(135deg, #059669 0%, #10b981 100%);">
                                <i class="bi bi-lightbulb" style="font-size: 4rem;"></i>
                            </div>
                        <?php endif; ?>
                        
                        <div class="card-body">
                            <div class="mb-2">
                                <span class="badge bg-primary">
                                    <?php echo ucwords(str_replace('_', ' ', $tip['category'])); ?>
                                </span>
                                <?php if (!empty($tip['crop_type'])): ?>
                                    <span class="badge bg-success"><?php echo htmlspecialchars($tip['crop_type']); ?></span>
                                <?php endif; ?>
                            </div>
                            
                            <h6 class="card-title"><?php echo htmlspecialchars($tip['title']); ?></h6>
                            <p class="card-text text-muted small">
                                <?php echo truncate(strip_tags($tip['content']), 100); ?>
                            </p>
                        </div>
                        
                        <div class="card-footer bg-transparent border-top-0">
                            <button class="btn btn-sm btn-outline-primary w-100" 
                                    onclick="viewTip(<?php echo $tip['id']; ?>)">
                                <i class="bi bi-eye"></i> Read More
                            </button>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="col-12">
                <div class="alert alert-info">
                    <i class="bi bi-info-circle"></i> No agricultural tips available at the moment.
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Call to Action -->
    <div class="row mt-5">
        <div class="col-12">
            <div class="card border-0 shadow text-center" style="background: linear-gradient(135deg, #059669 0%, #10b981 100%);">
                <div class="card-body p-5 text-white">
                    <h3 class="mb-3">Need Expert Advice?</h3>
                    <p class="mb-4">Connect with agricultural extension officers or chat with fellow farmers</p>
                    <div class="d-flex justify-content-center gap-3 flex-wrap">
                        <a href="<?php echo APP_URL; ?>/chat/" class="btn btn-light btn-lg">
                            <i class="bi bi-chat-dots"></i> Join Discussion Groups
                        </a>
                        <a href="<?php echo APP_URL; ?>/ai-assistant/" class="btn btn-outline-light btn-lg">
                            <i class="bi bi-robot"></i> AI Assistant
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Tip Details Modal -->
<div class="modal fade" id="tipModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="tipModalTitle">Loading...</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="tipModalBody">
                <div class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<style>
.hover-lift {
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.hover-lift:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgba(0,0,0,0.15) !important;
}

.stats-card {
    transition: all 0.3s ease;
}

.stats-card:hover {
    transform: scale(1.05);
}

.section-card {
    transition: all 0.3s ease;
    border-left: 4px solid transparent;
}

.section-card:hover {
    border-left-color: currentColor;
}

.category-filter {
    transition: all 0.2s ease;
}

.category-filter.active {
    background-color: #0d6efd !important;
    color: white !important;
    border-color: #0d6efd !important;
}

.tip-card {
    transition: opacity 0.3s ease;
}

.tip-card.hidden {
    display: none;
}
</style>

<script>
// View tip details
function viewTip(tipId) {
    const modal = new bootstrap.Modal(document.getElementById('tipModal'));
    modal.show();
    
    // Fetch tip details
    $.get(APP_URL + '/ajax/get-tip.php', { id: tipId }, function(response) {
        if (response.success) {
            const tip = response.data;
            $('#tipModalTitle').html(tip.title);
            
            let html = '';
            if (tip.media_url) {
                html += `<img src="${tip.media_url}" class="img-fluid rounded mb-3" alt="${tip.title}">`;
            }
            
            html += `
                <div class="mb-3">
                    <span class="badge bg-primary">${tip.category_name}</span>
                    ${tip.crop_type ? `<span class="badge bg-success">${tip.crop_type}</span>` : ''}
                </div>
                <div class="content">${tip.content}</div>
            `;
            
            $('#tipModalBody').html(html);
        } else {
            $('#tipModalBody').html('<div class="alert alert-danger">Failed to load tip details.</div>');
        }
    }).fail(function() {
        $('#tipModalBody').html('<div class="alert alert-danger">Connection error.</div>');
    });
}

// Category filtering
$(document).ready(function() {
    $('.category-filter').click(function() {
        const category = $(this).data('category');
        
        // Update active button
        $('.category-filter').removeClass('active');
        $(this).addClass('active');
        
        // Filter tips
        if (category === 'all') {
            $('.tip-card').removeClass('hidden');
        } else {
            $('.tip-card').each(function() {
                if ($(this).data('category') === category) {
                    $(this).removeClass('hidden');
                } else {
                    $(this).addClass('hidden');
                }
            });
        }
    });
});
</script>

<?php
// Include footer
include_once __DIR__ . '/../includes/footer.php';
include_once __DIR__ . '/../includes/bottom-nav.php';
?>