<?php
/**
 * ============================================================================
 * learning/resources.php - Downloadable Resources Page
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Agricultural Resources';

// Sample resources (in production, fetch from database)
$resources = [
    [
        'id' => 1,
        'title' => 'Maize Production Guide for Uganda',
        'description' => 'Comprehensive guide on maize farming from land preparation to harvesting',
        'file_type' => 'PDF',
        'file_size' => '2.5 MB',
        'downloads' => 450,
        'category' => 'crop_management',
        'language' => 'English',
        'url' => '#'
    ],
    [
        'id' => 2,
        'title' => 'Organic Pest Control Methods',
        'description' => 'Natural ways to protect your crops from pests and diseases',
        'file_type' => 'PDF',
        'file_size' => '1.8 MB',
        'downloads' => 320,
        'category' => 'pest_control',
        'language' => 'English',
        'url' => '#'
    ],
    [
        'id' => 3,
        'title' => 'Poultry Farming Business Plan Template',
        'description' => 'Ready-to-use business plan template for starting a poultry farm',
        'file_type' => 'DOCX',
        'file_size' => '850 KB',
        'downloads' => 680,
        'category' => 'livestock',
        'language' => 'English',
        'url' => '#'
    ],
    [
        'id' => 4,
        'title' => 'Soil Testing Guide',
        'description' => 'How to test your soil and interpret results',
        'file_type' => 'PDF',
        'file_size' => '1.2 MB',
        'downloads' => 290,
        'category' => 'soil_health',
        'language' => 'English',
        'url' => '#'
    ],
    [
        'id' => 5,
        'title' => 'Drip Irrigation Installation Manual',
        'description' => 'Step-by-step guide to installing drip irrigation systems',
        'file_type' => 'PDF',
        'file_size' => '3.1 MB',
        'downloads' => 410,
        'category' => 'irrigation',
        'language' => 'English',
        'url' => '#'
    ],
    [
        'id' => 6,
        'title' => 'Post-Harvest Handling Guide',
        'description' => 'Reduce losses with proper post-harvest handling techniques',
        'file_type' => 'PDF',
        'file_size' => '2.0 MB',
        'downloads' => 370,
        'category' => 'harvesting',
        'language' => 'English',
        'url' => '#'
    ],
    [
        'id' => 7,
        'title' => 'Coffee Quality Standards',
        'description' => 'Understanding quality standards for coffee export',
        'file_type' => 'PDF',
        'file_size' => '1.5 MB',
        'downloads' => 220,
        'category' => 'crop_management',
        'language' => 'English',
        'url' => '#'
    ],
    [
        'id' => 8,
        'title' => 'Farm Record Keeping Template',
        'description' => 'Excel template for tracking farm activities and finances',
        'file_type' => 'XLSX',
        'file_size' => '650 KB',
        'downloads' => 890,
        'category' => 'general',
        'language' => 'English',
        'url' => '#'
    ]
];

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="d-flex justify-content-between align-items-center">
                <div>
                    <h2 class="mb-1">
                        <i class="bi bi-file-earmark-text text-success"></i> Agricultural Resources
                    </h2>
                    <p class="text-muted mb-0">Download guides, manuals, and templates to improve your farming</p>
                </div>
                <a href="<?php echo APP_URL; ?>/learning/" class="btn btn-outline-primary">
                    <i class="bi bi-arrow-left"></i> Back to Learning Center
                </a>
            </div>
        </div>
    </div>

    <!-- Search and Filter -->
    <div class="row mb-4">
        <div class="col-md-4 mb-3">
            <div class="input-group">
                <span class="input-group-text"><i class="bi bi-search"></i></span>
                <input type="text" class="form-control" id="resourceSearch" placeholder="Search resources...">
            </div>
        </div>
        <div class="col-md-4 mb-3">
            <select class="form-select" id="categoryFilter">
                <option value="">All Categories</option>
                <option value="crop_management">Crop Management</option>
                <option value="pest_control">Pest Control</option>
                <option value="soil_health">Soil Health</option>
                <option value="irrigation">Irrigation</option>
                <option value="harvesting">Harvesting</option>
                <option value="livestock">Livestock</option>
                <option value="general">General</option>
            </select>
        </div>
        <div class="col-md-4 mb-3">
            <select class="form-select" id="fileTypeFilter">
                <option value="">All File Types</option>
                <option value="PDF">PDF Documents</option>
                <option value="DOCX">Word Documents</option>
                <option value="XLSX">Excel Spreadsheets</option>
            </select>
        </div>
    </div>

    <!-- Resources List -->
    <div class="row" id="resourcesContainer">
        <?php foreach ($resources as $resource): ?>
            <div class="col-md-6 col-lg-4 mb-4 resource-card" 
                 data-category="<?php echo $resource['category']; ?>" 
                 data-filetype="<?php echo $resource['file_type']; ?>"
                 data-title="<?php echo strtolower($resource['title']); ?>">
                <div class="card h-100 border-0 shadow-sm hover-lift">
                    <div class="card-body">
                        <div class="d-flex align-items-start mb-3">
                            <div class="me-3">
                                <?php
                                $iconClass = '';
                                $iconColor = '';
                                switch($resource['file_type']) {
                                    case 'PDF':
                                        $iconClass = 'bi-file-pdf';
                                        $iconColor = 'text-danger';
                                        break;
                                    case 'DOCX':
                                        $iconClass = 'bi-file-word';
                                        $iconColor = 'text-primary';
                                        break;
                                    case 'XLSX':
                                        $iconClass = 'bi-file-excel';
                                        $iconColor = 'text-success';
                                        break;
                                    default:
                                        $iconClass = 'bi-file-earmark';
                                        $iconColor = 'text-secondary';
                                }
                                ?>
                                <i class="bi <?php echo $iconClass . ' ' . $iconColor; ?>" style="font-size: 3rem;"></i>
                            </div>
                            <div class="flex-grow-1">
                                <div class="mb-2">
                                    <span class="badge bg-primary">
                                        <?php echo ucwords(str_replace('_', ' ', $resource['category'])); ?>
                                    </span>
                                    <span class="badge bg-secondary"><?php echo $resource['file_type']; ?></span>
                                </div>
                                <h5 class="card-title mb-1"><?php echo htmlspecialchars($resource['title']); ?></h5>
                            </div>
                        </div>
                        
                        <p class="card-text text-muted small mb-3">
                            <?php echo htmlspecialchars($resource['description']); ?>
                        </p>
                        
                        <div class="d-flex justify-content-between align-items-center text-muted small mb-3">
                            <span>
                                <i class="bi bi-hdd"></i> <?php echo $resource['file_size']; ?>
                            </span>
                            <span>
                                <i class="bi bi-download"></i> <?php echo number_format($resource['downloads']); ?> downloads
                            </span>
                        </div>
                    </div>
                    
                    <div class="card-footer bg-transparent border-top-0">
                        <button class="btn btn-success w-100" onclick="downloadResource(<?php echo $resource['id']; ?>, '<?php echo addslashes($resource['title']); ?>')">
                            <i class="bi bi-download"></i> Download
                        </button>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <!-- No Results Message -->
    <div class="row d-none" id="noResults">
        <div class="col-12">
            <div class="alert alert-info text-center">
                <i class="bi bi-info-circle"></i> No resources found matching your criteria.
            </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;
}
</style>

<script>
// Download resource
function downloadResource(resourceId, resourceTitle) {
    // Show loading
    showLoading();
    
    // Track download
    $.post(APP_URL + '/ajax/track-download.php', {
        resource_id: resourceId
    }, function(response) {
        hideLoading();
        
        if (response.success) {
            showToast('Download started: ' + resourceTitle, 'success');
            // In production, redirect to actual file URL
            // window.location.href = response.download_url;
        } else {
            showToast('Download failed. Please try again.', 'error');
        }
    }).fail(function() {
        hideLoading();
        showToast('Connection error. Please try again.', 'error');
    });
}

// Search and filter functionality
$(document).ready(function() {
    function filterResources() {
        const searchTerm = $('#resourceSearch').val().toLowerCase();
        const category = $('#categoryFilter').val();
        const fileType = $('#fileTypeFilter').val();
        let visibleCount = 0;

        $('.resource-card').each(function() {
            const title = $(this).data('title');
            const resourceCategory = $(this).data('category');
            const resourceFileType = $(this).data('filetype');
            
            const matchesSearch = searchTerm === '' || title.includes(searchTerm);
            const matchesCategory = category === '' || resourceCategory === category;
            const matchesFileType = fileType === '' || resourceFileType === fileType;
            
            if (matchesSearch && matchesCategory && matchesFileType) {
                $(this).show();
                visibleCount++;
            } else {
                $(this).hide();
            }
        });

        if (visibleCount === 0) {
            $('#noResults').removeClass('d-none');
        } else {
            $('#noResults').addClass('d-none');
        }
    }

    $('#resourceSearch').on('keyup', filterResources);
    $('#categoryFilter').on('change', filterResources);
    $('#fileTypeFilter').on('change', filterResources);
});
</script>

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