<?php
/**
 * ============================================================================
 * learning/varieties.php - Crop Varieties Information
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Crop Varieties';
$userId = getUserId();

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

// Get filter parameter
$crop_filter = isset($_GET['crop']) ? $_GET['crop'] : 'all';

// Build query
$sql = "SELECT * FROM crop_varieties WHERE is_published = 1";
if ($crop_filter != 'all') {
    $sql .= " AND crop_type = ?";
    $params = [$crop_filter];
} else {
    $params = [];
}
$sql .= " ORDER BY crop_type, variety_name";

try {
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $varieties = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $varieties = [];
    error_log("Error fetching varieties: " . $e->getMessage());
}

// Get available crop types
try {
    $crops_sql = "SELECT DISTINCT crop_type FROM crop_varieties WHERE is_published = 1 ORDER BY crop_type";
    $crops_stmt = $db->query($crops_sql);
    $available_crops = $crops_stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (PDOException $e) {
    $available_crops = [];
}

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 flex-wrap gap-3">
                <div>
                    <h2 class="mb-1">
                        <i class="bi bi-tree text-success"></i> Crop Varieties
                    </h2>
                    <p class="text-muted mb-0">Choose the best varieties for your farm</p>
                </div>
                <a href="<?php echo APP_URL; ?>/learning/" class="btn btn-outline-primary">
                    <i class="bi bi-arrow-left"></i> Back to Learning
                </a>
            </div>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="row mb-4">
        <div class="col-md-4 mb-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center">
                    <div class="text-success mb-2">
                        <i class="bi bi-tree" style="font-size: 2.5rem;"></i>
                    </div>
                    <h3 class="mb-0"><?php echo count($varieties); ?></h3>
                    <small class="text-muted">Total Varieties</small>
                </div>
            </div>
        </div>
        <div class="col-md-4 mb-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center">
                    <div class="text-primary mb-2">
                        <i class="bi bi-flower3" style="font-size: 2.5rem;"></i>
                    </div>
                    <h3 class="mb-0"><?php echo count($available_crops); ?></h3>
                    <small class="text-muted">Crop Types</small>
                </div>
            </div>
        </div>
        <div class="col-md-4 mb-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center">
                    <div class="text-warning mb-2">
                        <i class="bi bi-star" style="font-size: 2.5rem;"></i>
                    </div>
                    <h3 class="mb-0">
                        <?php 
                        $high_yield = array_filter($varieties, function($v) { 
                            return !empty($v['advantages']); 
                        });
                        echo count($high_yield);
                        ?>
                    </h3>
                    <small class="text-muted">Recommended</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Filter -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <form method="GET" action="" class="row g-3">
                        <div class="col-md-12">
                            <label class="form-label"><i class="bi bi-funnel"></i> Filter by Crop</label>
                            <select name="crop" class="form-select" onchange="this.form.submit()">
                                <option value="all" <?php echo $crop_filter == 'all' ? 'selected' : ''; ?>>All Crops</option>
                                <?php foreach ($available_crops as $crop): ?>
                                    <option value="<?php echo $crop; ?>" <?php echo $crop_filter == $crop ? 'selected' : ''; ?>>
                                        <?php echo ucwords(str_replace('_', ' ', $crop)); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Varieties Grid -->
    <div class="row">
        <?php if (!empty($varieties)): ?>
            <?php foreach ($varieties as $variety): ?>
                <div class="col-lg-6 col-xl-4 mb-4">
                    <div class="card border-0 shadow-sm h-100 variety-card">
                        <div class="card-header bg-success text-white">
                            <div class="d-flex justify-content-between align-items-center">
                                <h6 class="mb-0"><?php echo htmlspecialchars($variety['variety_name']); ?></h6>
                                <span class="badge bg-light text-dark">
                                    <?php echo ucwords(str_replace('_', ' ', $variety['crop_type'])); ?>
                                </span>
                            </div>
                            <?php if ($variety['scientific_name']): ?>
                                <small class="fst-italic"><?php echo htmlspecialchars($variety['scientific_name']); ?></small>
                            <?php endif; ?>
                        </div>
                        <div class="card-body">
                            <!-- Description -->
                            <p class="text-muted mb-3">
                                <?php echo truncate(strip_tags($variety['description']), 120); ?>
                            </p>

                            <!-- Key Info Grid -->
                            <div class="row g-2 mb-3">
                                <?php if ($variety['maturity_days']): ?>
                                    <div class="col-6">
                                        <div class="info-box">
                                            <i class="bi bi-calendar-check text-primary"></i>
                                            <div>
                                                <small class="text-muted d-block">Maturity</small>
                                                <strong><?php echo $variety['maturity_days']; ?> days</strong>
                                            </div>
                                        </div>
                                    </div>
                                <?php endif; ?>

                                <?php if ($variety['yield_per_acre']): ?>
                                    <div class="col-6">
                                        <div class="info-box">
                                            <i class="bi bi-graph-up text-success"></i>
                                            <div>
                                                <small class="text-muted d-block">Yield/Acre</small>
                                                <strong><?php echo htmlspecialchars($variety['yield_per_acre']); ?></strong>
                                            </div>
                                        </div>
                                    </div>
                                <?php endif; ?>

                                <?php if ($variety['spacing']): ?>
                                    <div class="col-6">
                                        <div class="info-box">
                                            <i class="bi bi-arrows-angle-expand text-info"></i>
                                            <div>
                                                <small class="text-muted d-block">Spacing</small>
                                                <strong><?php echo htmlspecialchars($variety['spacing']); ?></strong>
                                            </div>
                                        </div>
                                    </div>
                                <?php endif; ?>

                                <?php if ($variety['seed_rate']): ?>
                                    <div class="col-6">
                                        <div class="info-box">
                                            <i class="bi bi-droplet text-warning"></i>
                                            <div>
                                                <small class="text-muted d-block">Seed Rate</small>
                                                <strong><?php echo htmlspecialchars($variety['seed_rate']); ?></strong>
                                            </div>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <!-- Characteristics -->
                            <?php if ($variety['characteristics']): ?>
                                <div class="mb-3">
                                    <small class="text-muted">
                                        <i class="bi bi-info-circle"></i> 
                                        <?php echo truncate(strip_tags($variety['characteristics']), 80); ?>
                                    </small>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="card-footer bg-transparent">
                            <button class="btn btn-outline-success btn-sm w-100" onclick="viewVariety(<?php echo $variety['id']; ?>)">
                                <i class="bi bi-eye"></i> View Full Details
                            </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 varieties found for the selected crop.
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Comparison Section -->
    <?php if (count($varieties) > 1 && $crop_filter != 'all'): ?>
    <div class="row mt-5">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">
                        <i class="bi bi-bar-chart"></i> Quick Comparison
                    </h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Variety</th>
                                    <th>Maturity (days)</th>
                                    <th>Yield/Acre</th>
                                    <th>Spacing</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($varieties as $variety): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo htmlspecialchars($variety['variety_name']); ?></strong><br>
                                            <small class="text-muted"><?php echo htmlspecialchars($variety['scientific_name']); ?></small>
                                        </td>
                                        <td><?php echo $variety['maturity_days'] ?? '-'; ?></td>
                                        <td><?php echo htmlspecialchars($variety['yield_per_acre'] ?? '-'); ?></td>
                                        <td><?php echo htmlspecialchars($variety['spacing'] ?? '-'); ?></td>
                                        <td>
                                            <button class="btn btn-sm btn-outline-primary" onclick="viewVariety(<?php echo $variety['id']; ?>)">
                                                <i class="bi bi-eye"></i>
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Variety Details Modal -->
<div class="modal fade" id="varietyModal" tabindex="-1">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="varietyModalTitle">Loading...</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="varietyModalBody">
                <div class="text-center py-5">
                    <div class="spinner-border text-success" 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>
                <button type="button" class="btn btn-success" onclick="bookmarkVariety()">
                    <i class="bi bi-bookmark"></i> Bookmark
                </button>
            </div>
        </div>
    </div>
</div>

<style>
.variety-card {
    transition: all 0.3s ease;
}

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

.info-box {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 12px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.info-box i {
    font-size: 1.5rem;
}

.info-box small {
    font-size: 0.75rem;
}

.comparison-badge {
    font-size: 0.75rem;
    padding: 0.25rem 0.5rem;
}
</style>

<script>
let currentVarietyId = null;

function viewVariety(varietyId) {
    currentVarietyId = varietyId;
    const modal = new bootstrap.Modal(document.getElementById('varietyModal'));
    modal.show();
    
    $.get(APP_URL + '/ajax/get-variety.php', { id: varietyId }, function(response) {
        if (response.success) {
            const variety = response.data;
            $('#varietyModalTitle').html(variety.variety_name);
            
            let html = `
                <div class="variety-details">
                    ${variety.scientific_name ? `<p class="fst-italic text-muted">${variety.scientific_name}</p>` : ''}
                    
                    <div class="mb-4">
                        <span class="badge bg-success">${variety.crop_type_formatted}</span>
                    </div>

                    <div class="row mb-4">
                        <div class="col-12">
                            <h6 class="text-primary"><i class="bi bi-info-circle"></i> Description</h6>
                            <p>${variety.description}</p>
                        </div>
                    </div>

                    <div class="row mb-4">
                        ${variety.maturity_days ? `
                            <div class="col-md-3 col-6 mb-3">
                                <div class="card bg-light">
                                    <div class="card-body text-center">
                                        <i class="bi bi-calendar-check text-primary fs-3"></i>
                                        <h5 class="mt-2 mb-0">${variety.maturity_days}</h5>
                                        <small class="text-muted">Days to Maturity</small>
                                    </div>
                                </div>
                            </div>
                        ` : ''}

                        ${variety.yield_per_acre ? `
                            <div class="col-md-3 col-6 mb-3">
                                <div class="card bg-light">
                                    <div class="card-body text-center">
                                        <i class="bi bi-graph-up text-success fs-3"></i>
                                        <h6 class="mt-2 mb-0">${variety.yield_per_acre}</h6>
                                        <small class="text-muted">Yield per Acre</small>
                                    </div>
                                </div>
                            </div>
                        ` : ''}

                        ${variety.spacing ? `
                            <div class="col-md-3 col-6 mb-3">
                                <div class="card bg-light">
                                    <div class="card-body text-center">
                                        <i class="bi bi-arrows-angle-expand text-info fs-3"></i>
                                        <h6 class="mt-2 mb-0">${variety.spacing}</h6>
                                        <small class="text-muted">Spacing</small>
                                    </div>
                                </div>
                            </div>
                        ` : ''}

                        ${variety.seed_rate ? `
                            <div class="col-md-3 col-6 mb-3">
                                <div class="card bg-light">
                                    <div class="card-body text-center">
                                        <i class="bi bi-droplet text-warning fs-3"></i>
                                        <h6 class="mt-2 mb-0">${variety.seed_rate}</h6>
                                        <small class="text-muted">Seed Rate</small>
                                    </div>
                                </div>
                            </div>
                        ` : ''}
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            ${variety.advantages ? `
                                <div class="mb-4">
                                    <h6 class="text-success"><i class="bi bi-check-circle"></i> Advantages</h6>
                                    <div class="alert alert-success">${variety.advantages.replace(/\n/g, '<br>')}</div>
                                </div>
                            ` : ''}

                            ${variety.characteristics ? `
                                <div class="mb-4">
                                    <h6 class="text-info"><i class="bi bi-star"></i> Characteristics</h6>
                                    <p>${variety.characteristics}</p>
                                </div>
                            ` : ''}

                            ${variety.soil_requirements ? `
                                <div class="mb-4">
                                    <h6 class="text-warning"><i class="bi bi-droplet-half"></i> Soil Requirements</h6>
                                    <p>${variety.soil_requirements}</p>
                                </div>
                            ` : ''}
                        </div>

                        <div class="col-md-6">
                            ${variety.disadvantages ? `
                                <div class="mb-4">
                                    <h6 class="text-danger"><i class="bi bi-x-circle"></i> Disadvantages</h6>
                                    <div class="alert alert-warning">${variety.disadvantages.replace(/\n/g, '<br>')}</div>
                                </div>
                            ` : ''}

                            ${variety.climate_requirements ? `
                                <div class="mb-4">
                                    <h6 class="text-primary"><i class="bi bi-cloud-sun"></i> Climate Requirements</h6>
                                    <p>${variety.climate_requirements}</p>
                                </div>
                            ` : ''}

                            ${variety.water_requirements ? `
                                <div class="mb-4">
                                    <h6 class="text-info"><i class="bi bi-water"></i> Water Requirements</h6>
                                    <p>${variety.water_requirements}</p>
                                </div>
                            ` : ''}
                        </div>
                    </div>
                </div>
            `;
            
            $('#varietyModalBody').html(html);
        }
    }).fail(function() {
        $('#varietyModalBody').html('<div class="alert alert-danger">Failed to load variety details.</div>');
    });
}

function bookmarkVariety() {
    if (!currentVarietyId) return;
    
    $.post(APP_URL + '/ajax/bookmark-content.php', {
        content_type: 'variety',
        content_id: currentVarietyId
    }, function(response) {
        if (response.success) {
            Toastify({
                text: "Variety bookmarked successfully!",
                backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
                duration: 3000
            }).showToast();
        }
    });
}
</script>

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