<?php
require_once __DIR__ . '/includes/base.php';
$breadcrumbs = [['title' => 'Agricultural Tips', 'url' => '']];

// Fetch tips
try {
    $sql = "SELECT t.*, u.full_name as author FROM agricultural_tips t 
            LEFT JOIN users u ON t.created_by = u.id ORDER BY t.created_at DESC";
    $tips = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $tips = [];
}

renderAdminHeader('Agricultural Tips', $breadcrumbs);
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold">Agricultural Tips</h2>
        <p class="text-muted mb-0">Manage farming advice and best practices</p>
    </div>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addModal">
        <i class="bi bi-plus-circle me-2"></i>Add Tip
    </button>
</div>

<div class="card shadow-sm border-0">
    <div class="card-body p-0">
        <table class="table table-hover mb-0" id="tipsTable">
            <thead class="table-light">
                <tr>
                    <th>Title</th>
                    <th>Category</th>
                    <th>Crop Type</th>
                    <th>Language</th>
                    <th>Author</th>
                    <th>Status</th>
                    <th>Created</th>
                    <th class="text-end">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($tips as $tip): ?>
                <tr>
                    <td class="fw-semibold"><?php echo htmlspecialchars($tip['title']); ?></td>
                    <td><span class="badge bg-info"><?php echo ucfirst(str_replace('_', ' ', $tip['category'])); ?></span></td>
                    <td><?php echo htmlspecialchars($tip['crop_type'] ?? 'General'); ?></td>
                    <td><?php echo strtoupper($tip['language']); ?></td>
                    <td><small><?php echo htmlspecialchars($tip['author'] ?? 'System'); ?></small></td>
                    <td>
                        <span class="badge bg-<?php echo $tip['is_published'] ? 'success' : 'warning'; ?>">
                            <?php echo $tip['is_published'] ? 'Published' : 'Draft'; ?>
                        </span>
                    </td>
                    <td><small class="text-muted"><?php echo date('M d, Y', strtotime($tip['created_at'])); ?></small></td>
                    <td class="text-end">
                        <div class="btn-group btn-group-sm">
                            <button class="btn btn-outline-info" onclick='viewTip(<?php echo json_encode($tip); ?>)'>
                                <i class="bi bi-eye"></i>
                            </button>
                            <button class="btn btn-outline-primary" onclick='editTip(<?php echo json_encode($tip); ?>)'>
                                <i class="bi bi-pencil"></i>
                            </button>
                            <button class="btn btn-outline-danger" onclick="deleteTip(<?php echo $tip['id']; ?>)">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Add/Edit Modal -->
<div class="modal fade" id="addModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">Add Agricultural Tip</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="tipForm">
                <div class="modal-body">
                    <input type="hidden" name="id" id="tipId">
                    
                    <div class="mb-3">
                        <label>Title *</label>
                        <input type="text" class="form-control" name="title" required>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label>Category *</label>
                            <select class="form-select" name="category" required>
                                <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="storage">Storage</option>
                                <option value="general">General</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Crop Type</label>
                            <input type="text" class="form-control" name="crop_type" placeholder="Optional">
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label>Content *</label>
                        <textarea class="form-control" name="content" rows="6" required></textarea>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label>Language</label>
                            <select class="form-select" name="language">
                                <option value="en">English</option>
                                <option value="lusoga">Lusoga</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Status</label>
                            <select class="form-select" name="is_published">
                                <option value="1">Publish</option>
                                <option value="0">Save as Draft</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Tip</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- View Modal -->
<div class="modal fade" id="viewModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-lightbulb me-2"></i>Tip Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="tipContent"></div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#tipsTable').DataTable({pageLength: 25});
});

$('#tipForm').submit(function(e) {
    e.preventDefault();
    const action = $('#tipId').val() ? 'edit_tip' : 'add_tip';
    const btn = $(this).find('button[type="submit"]');
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Saving...');
    
    $.post(APP_URL + '/api/admin.php', $(this).serialize() + '&action=' + action)
    .done(function(r) {
        if (r.success) {
            showToast(r.message, 'success');
            $('#addModal').modal('hide');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast(r.message, 'error');
            btn.prop('disabled', false).text('Save Tip');
        }
    });
});

function viewTip(tip) {
    $('#tipContent').html(`
        <h4>${tip.title}</h4>
        <div class="mb-3">
            <span class="badge bg-info">${tip.category}</span>
            ${tip.crop_type ? `<span class="badge bg-success">${tip.crop_type}</span>` : ''}
            <span class="badge bg-secondary">${tip.language.toUpperCase()}</span>
        </div>
        <p class="lead">${tip.content}</p>
        <hr>
        <small class="text-muted">Created: ${new Date(tip.created_at).toLocaleDateString()}</small>
    `);
    new bootstrap.Modal(document.getElementById('viewModal')).show();
}

function editTip(tip) {
    $('#modalTitle').text('Edit Tip');
    $('#tipId').val(tip.id);
    $('input[name="title"]').val(tip.title);
    $('select[name="category"]').val(tip.category);
    $('input[name="crop_type"]').val(tip.crop_type);
    $('textarea[name="content"]').val(tip.content);
    $('select[name="language"]').val(tip.language);
    $('select[name="is_published"]').val(tip.is_published);
    $('#addModal').modal('show');
}

function deleteTip(id) {
    Swal.fire({
        title: 'Delete Tip?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444'
    }).then((result) => {
        if (result.isConfirmed) {
            $.post(APP_URL + '/api/admin.php', {action: 'delete_tip', id: id})
            .done(function(r) {
                if (r.success) {
                    showToast(r.message, 'success');
                    setTimeout(() => location.reload(), 1000);
                }
            });
        }
    });
}
</script>

<?php renderAdminFooter(); ?>