<?php
/**
 * ============================================================================
 * extension/tips.php
 * Agricultural Tips Management (National Level Creates/Edits)
 * ============================================================================
 */

require_once __DIR__ . '/includes/base.php';

// Check permission - only national level can create/edit
$canManage = in_array($userLevel, ['national']) || $isAdmin;

// Get filters
$category = $_GET['category'] ?? 'all';
$language = $_GET['language'] ?? 'all';
$crop = $_GET['crop_type'] ?? 'all';

// Build query
$whereConditions = ["1=1"];
$params = [];

if ($category !== 'all') {
    $whereConditions[] = "category = ?";
    $params[] = $category;
}

if ($language !== 'all') {
    $whereConditions[] = "language = ?";
    $params[] = $language;
}

if ($crop !== 'all') {
    $whereConditions[] = "crop_type = ?";
    $params[] = $crop;
}

$sql = "SELECT at.*, u.full_name as created_by_name,
        (SELECT COUNT(*) FROM learning_progress WHERE content_type = 'tip' AND content_id = at.id) as view_count
        FROM agricultural_tips at
        LEFT JOIN users u ON at.created_by = u.id
        WHERE " . implode(' AND ', $whereConditions) . "
        ORDER BY at.created_at DESC";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$tips = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Statistics
$statsSql = "SELECT 
    COUNT(*) as total_tips,
    SUM(CASE WHEN is_published = 1 THEN 1 ELSE 0 END) as published_count,
    SUM(CASE WHEN language = 'en' THEN 1 ELSE 0 END) as english_count,
    SUM(CASE WHEN language = 'lusoga' THEN 1 ELSE 0 END) as lusoga_count
    FROM agricultural_tips";
$statsStmt = $db->prepare($statsSql);
$statsStmt->execute();
$stats = $statsStmt->fetch(PDO::FETCH_ASSOC);

$pageTitle = 'Agricultural Tips - AIMS Extension';
$breadcrumbs = [
    ['title' => 'Agricultural Tips', 'url' => '']
];

renderExtensionHeader($pageTitle, $breadcrumbs);
?>

<div class="container-fluid py-4">
    <!-- Statistics -->
    <div class="row mb-4">
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stat-card border-0 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 Tips</p>
                            <h3 class="mb-0 fw-bold"><?php echo $stats['total_tips']; ?></h3>
                        </div>
                        <div class="stat-icon bg-primary bg-opacity-10 text-primary">
                            <i class="bi bi-lightbulb"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

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

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

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

    <!-- Filters & Actions -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body">
            <div class="row align-items-center">
                <div class="col-md-9">
                    <form method="GET" class="row g-3">
                        <div class="col-md-3">
                            <select name="category" class="form-select" onchange="this.form.submit()">
                                <option value="all">All Categories</option>
                                <option value="crop_management" <?php echo $category === 'crop_management' ? 'selected' : ''; ?>>Crop Management</option>
                                <option value="pest_control" <?php echo $category === 'pest_control' ? 'selected' : ''; ?>>Pest Control</option>
                                <option value="soil_health" <?php echo $category === 'soil_health' ? 'selected' : ''; ?>>Soil Health</option>
                                <option value="irrigation" <?php echo $category === 'irrigation' ? 'selected' : ''; ?>>Irrigation</option>
                                <option value="harvesting" <?php echo $category === 'harvesting' ? 'selected' : ''; ?>>Harvesting</option>
                                <option value="storage" <?php echo $category === 'storage' ? 'selected' : ''; ?>>Storage</option>
                                <option value="general" <?php echo $category === 'general' ? 'selected' : ''; ?>>General</option>
                            </select>
                        </div>

                        <div class="col-md-3">
                            <select name="language" class="form-select" onchange="this.form.submit()">
                                <option value="all">All Languages</option>
                                <option value="en" <?php echo $language === 'en' ? 'selected' : ''; ?>>English</option>
                                <option value="lusoga" <?php echo $language === 'lusoga' ? 'selected' : ''; ?>>Lusoga</option>
                            </select>
                        </div>

                        <div class="col-md-3">
                            <select name="crop_type" class="form-select" onchange="this.form.submit()">
                                <option value="all">All Crops</option>
                                <option value="maize">Maize</option>
                                <option value="beans">Beans</option>
                                <option value="coffee">Coffee</option>
                                <option value="cassava">Cassava</option>
                                <option value="bananas">Bananas</option>
                                <option value="vegetables">Vegetables</option>
                            </select>
                        </div>

                        <div class="col-md-3">
                            <a href="<?php echo APP_URL; ?>/extension/tips.php" class="btn btn-outline-secondary w-100">
                                <i class="bi bi-arrow-clockwise"></i> Reset
                            </a>
                        </div>
                    </form>
                </div>

                <div class="col-md-3 text-md-end mt-3 mt-md-0">
                    <?php if ($canManage): ?>
                    <a href="<?php echo APP_URL; ?>/extension/create-tip.php" class="btn btn-primary">
                        <i class="bi bi-plus-circle"></i> Create Tip
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Tips List -->
    <div class="row">
        <?php if (empty($tips)): ?>
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center py-5">
                    <i class="bi bi-lightbulb" style="font-size: 4rem; color: #d1d5db;"></i>
                    <h5 class="mt-3 text-muted">No tips found</h5>
                    <p class="text-muted">Change filters or create a new tip</p>
                </div>
            </div>
        </div>
        <?php else: ?>
        <?php foreach ($tips as $tip): ?>
        <div class="col-lg-4 col-md-6 mb-4">
            <div class="card h-100 border-0 shadow-sm hover-shadow">
                <?php if ($tip['media_url']): ?>
                <img src="<?php echo APP_URL . '/' . e($tip['media_url']); ?>" 
                     class="card-img-top" style="height: 200px; object-fit: cover;" 
                     alt="<?php echo e($tip['title']); ?>">
                <?php endif; ?>
                
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <span class="badge bg-primary">
                            <?php echo ucfirst(str_replace('_', ' ', $tip['category'])); ?>
                        </span>
                        <span class="badge bg-secondary">
                            <?php echo strtoupper($tip['language']); ?>
                        </span>
                    </div>

                    <h5 class="card-title fw-bold mb-2"><?php echo e($tip['title']); ?></h5>
                    
                    <?php if ($tip['crop_type']): ?>
                    <p class="text-muted small mb-2">
                        <i class="bi bi-tree"></i> <?php echo ucfirst($tip['crop_type']); ?>
                    </p>
                    <?php endif; ?>

                    <p class="card-text text-muted small">
                        <?php echo truncate(strip_tags($tip['content']), 150); ?>
                    </p>

                    <div class="d-flex justify-content-between align-items-center pt-3 border-top">
                        <small class="text-muted">
                            <i class="bi bi-eye"></i> <?php echo number_format($tip['view_count']); ?> views
                        </small>
                        <div>
                            <button class="btn btn-sm btn-outline-primary" onclick="viewTip(<?php echo $tip['id']; ?>)">
                                <i class="bi bi-eye"></i> View
                            </button>
                            <?php if ($canManage): ?>
                            <a href="<?php echo APP_URL; ?>/extension/create-tip.php?id=<?php echo $tip['id']; ?>" 
                               class="btn btn-sm btn-outline-secondary">
                                <i class="bi bi-pencil"></i>
                            </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <div class="card-footer bg-light">
                    <div class="d-flex justify-content-between align-items-center">
                        <small class="text-muted">
                            <?php echo timeAgo($tip['created_at']); ?>
                        </small>
                        <span class="badge bg-<?php echo $tip['is_published'] ? 'success' : 'warning'; ?>">
                            <?php echo $tip['is_published'] ? 'Published' : 'Draft'; ?>
                        </span>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<!-- View Tip Modal -->
<div class="modal fade" id="viewTipModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Agricultural Tip</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="tipContent">
                <!-- Loaded via AJAX -->
            </div>
        </div>
    </div>
</div>

<script>
function viewTip(tipId) {
    showLoading();
    $.get('<?php echo APP_URL; ?>/api/extension.php', {
        action: 'get_tip',
        tip_id: tipId
    }, function(response) {
        hideLoading();
        if (response.success) {
            $('#tipContent').html(response.html);
            new bootstrap.Modal('#viewTipModal').show();
        } else {
            showToast(response.message, 'error');
        }
    });
}
</script>

<?php renderExtensionFooter(); ?>