<?php
/**
 * ============================================================================
 * extension/create-tip.php
 * Create/Edit Agricultural Tips (National Level Only)
 * ============================================================================
 */

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

// Check permission
if (!in_array($userLevel, ['national']) && !$isAdmin) {
    redirectTo('/extension/tips.php', 'You do not have permission to create tips', 'error');
}

// Check if editing
$tipId = $_GET['id'] ?? null;
$tip = null;

if ($tipId) {
    $sql = "SELECT * FROM agricultural_tips WHERE id = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute([$tipId]);
    $tip = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$tip) {
        redirectTo('/extension/tips.php', 'Tip not found', 'error');
    }
}

$pageTitle = ($tipId ? 'Edit' : 'Create') . ' Agricultural Tip - AIMS Extension';
$breadcrumbs = [
    ['title' => 'Agricultural Tips', 'url' => APP_URL . '/extension/tips.php'],
    ['title' => $tipId ? 'Edit Tip' : 'Create Tip', 'url' => '']
];

renderExtensionHeader($pageTitle, $breadcrumbs);
?>

<div class="container-fluid py-4">
    <div class="row justify-content-center">
        <div class="col-xl-10">
            <!-- Header -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center">
                        <a href="<?php echo APP_URL; ?>/extension/tips.php" class="btn btn-outline-secondary me-3">
                            <i class="bi bi-arrow-left"></i>
                        </a>
                        <div>
                            <h4 class="mb-1 fw-bold">
                                <i class="bi bi-lightbulb text-warning me-2"></i>
                                <?php echo $tipId ? 'Edit' : 'Create'; ?> Agricultural Tip
                            </h4>
                            <p class="text-muted mb-0">Share knowledge with farmers across the country</p>
                        </div>
                    </div>
                </div>
            </div>

            <form id="tipForm" method="POST" enctype="multipart/form-data">
                <input type="hidden" name="tip_id" value="<?php echo $tipId ?? ''; ?>">
                
                <!-- Basic Information -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-white py-3">
                        <h6 class="mb-0 fw-bold">
                            <i class="bi bi-info-circle text-primary me-2"></i>Basic Information
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-8 mb-3">
                                <label class="form-label fw-semibold">
                                    Tip Title <span class="text-danger">*</span>
                                </label>
                                <input type="text" name="title" class="form-control form-control-lg" 
                                       value="<?php echo $tip['title'] ?? ''; ?>"
                                       placeholder="e.g., Best Time to Plant Maize" required>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label fw-semibold">Language</label>
                                <select name="language" class="form-select form-select-lg" required>
                                    <option value="en" <?php echo ($tip['language'] ?? 'en') === 'en' ? 'selected' : ''; ?>>English</option>
                                    <option value="lusoga" <?php echo ($tip['language'] ?? '') === 'lusoga' ? 'selected' : ''; ?>>Lusoga</option>
                                </select>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label fw-semibold">Category</label>
                                <select name="category" class="form-select form-select-lg" required>
                                    <option value="crop_management" <?php echo ($tip['category'] ?? '') === 'crop_management' ? 'selected' : ''; ?>>Crop Management</option>
                                    <option value="pest_control" <?php echo ($tip['category'] ?? '') === 'pest_control' ? 'selected' : ''; ?>>Pest Control</option>
                                    <option value="soil_health" <?php echo ($tip['category'] ?? '') === 'soil_health' ? 'selected' : ''; ?>>Soil Health</option>
                                    <option value="irrigation" <?php echo ($tip['category'] ?? '') === 'irrigation' ? 'selected' : ''; ?>>Irrigation</option>
                                    <option value="harvesting" <?php echo ($tip['category'] ?? '') === 'harvesting' ? 'selected' : ''; ?>>Harvesting</option>
                                    <option value="storage" <?php echo ($tip['category'] ?? '') === 'storage' ? 'selected' : ''; ?>>Storage</option>
                                    <option value="general" <?php echo ($tip['category'] ?? '') === 'general' ? 'selected' : ''; ?>>General</option>
                                </select>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label fw-semibold">Crop Type (Optional)</label>
                                <select name="crop_type" class="form-select form-select-lg">
                                    <option value="">All Crops</option>
                                    <option value="maize" <?php echo ($tip['crop_type'] ?? '') === 'maize' ? 'selected' : ''; ?>>Maize</option>
                                    <option value="beans" <?php echo ($tip['crop_type'] ?? '') === 'beans' ? 'selected' : ''; ?>>Beans</option>
                                    <option value="coffee" <?php echo ($tip['crop_type'] ?? '') === 'coffee' ? 'selected' : ''; ?>>Coffee</option>
                                    <option value="cassava" <?php echo ($tip['crop_type'] ?? '') === 'cassava' ? 'selected' : ''; ?>>Cassava</option>
                                    <option value="bananas" <?php echo ($tip['crop_type'] ?? '') === 'bananas' ? 'selected' : ''; ?>>Bananas</option>
                                    <option value="vegetables" <?php echo ($tip['crop_type'] ?? '') === 'vegetables' ? 'selected' : ''; ?>>Vegetables</option>
                                    <option value="rice" <?php echo ($tip['crop_type'] ?? '') === 'rice' ? 'selected' : ''; ?>>Rice</option>
                                </select>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label fw-semibold">Season (Optional)</label>
                                <select name="season" class="form-select form-select-lg">
                                    <option value="">All Seasons</option>
                                    <option value="first_season" <?php echo ($tip['season'] ?? '') === 'first_season' ? 'selected' : ''; ?>>First Season (Mar-Jun)</option>
                                    <option value="second_season" <?php echo ($tip['season'] ?? '') === 'second_season' ? 'selected' : ''; ?>>Second Season (Sep-Dec)</option>
                                    <option value="dry_season" <?php echo ($tip['season'] ?? '') === 'dry_season' ? 'selected' : ''; ?>>Dry Season</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Content -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-white py-3">
                        <h6 class="mb-0 fw-bold">
                            <i class="bi bi-file-text text-success me-2"></i>Tip Content
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label fw-semibold">
                                Detailed Content <span class="text-danger">*</span>
                            </label>
                            <textarea name="content" id="tipContent" class="form-control" rows="12" required><?php echo $tip['content'] ?? ''; ?></textarea>
                            <small class="text-muted">
                                <i class="bi bi-info-circle me-1"></i>
                                Provide clear, actionable advice. Use simple language that farmers can understand.
                            </small>
                        </div>
                    </div>
                </div>

                <!-- Media -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-white py-3">
                        <h6 class="mb-0 fw-bold">
                            <i class="bi bi-image text-info me-2"></i>Media (Optional)
                        </h6>
                    </div>
                    <div class="card-body">
                        <?php if ($tip && $tip['media_url']): ?>
                        <div class="mb-3">
                            <p class="fw-semibold">Current Image:</p>
                            <img src="<?php echo APP_URL . '/' . e($tip['media_url']); ?>" 
                                 class="img-thumbnail" style="max-height: 200px;">
                            <div class="form-check mt-2">
                                <input type="checkbox" name="remove_media" class="form-check-input" id="removeMedia">
                                <label class="form-check-label" for="removeMedia">Remove current image</label>
                            </div>
                        </div>
                        <?php endif; ?>

                        <div class="mb-3">
                            <label class="form-label fw-semibold">Upload Image/Video</label>
                            <input type="file" name="media" class="form-control" accept="image/*,video/*" 
                                   onchange="previewMedia(this)">
                            <small class="text-muted">Max 10MB. JPG, PNG, or MP4</small>
                        </div>

                        <div id="mediaPreview"></div>
                    </div>
                </div>

                <!-- Publishing -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-white py-3">
                        <h6 class="mb-0 fw-bold">
                            <i class="bi bi-globe text-primary me-2"></i>Publishing Options
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="form-check form-switch">
                            <input type="checkbox" name="is_published" class="form-check-input" 
                                   id="isPublished" value="1" 
                                   <?php echo ($tip['is_published'] ?? 1) ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="isPublished">
                                <strong>Publish immediately</strong>
                                <small class="d-block text-muted">Make this tip visible to all farmers</small>
                            </label>
                        </div>
                    </div>
                </div>

                <!-- Submit -->
                <div class="card border-0 shadow-sm">
                    <div class="card-body">
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary btn-lg flex-fill">
                                <i class="bi bi-save me-2"></i>
                                <?php echo $tipId ? 'Update' : 'Create'; ?> Tip
                            </button>
                            <a href="<?php echo APP_URL; ?>/extension/tips.php" class="btn btn-outline-secondary btn-lg">
                                Cancel
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/6/tinymce.min.js"></script>
<script>
// Initialize rich text editor
tinymce.init({
    selector: '#tipContent',
    height: 400,
    menubar: false,
    plugins: 'lists link image code',
    toolbar: 'undo redo | formatselect | bold italic | alignleft aligncenter alignright | bullist numlist | link image | code',
    content_style: 'body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; font-size: 14px }'
});

function previewMedia(input) {
    const preview = $('#mediaPreview');
    preview.html('');
    
    if (input.files && input.files[0]) {
        const file = input.files[0];
        const reader = new FileReader();
        
        reader.onload = function(e) {
            if (file.type.startsWith('image/')) {
                preview.html('<img src="' + e.target.result + '" class="img-thumbnail" style="max-height: 200px;">');
            } else if (file.type.startsWith('video/')) {
                preview.html('<video src="' + e.target.result + '" class="img-thumbnail" style="max-height: 200px;" controls></video>');
            }
        }
        
        reader.readAsDataURL(file);
    }
}

$('#tipForm').on('submit', function(e) {
    e.preventDefault();
    
    // Get TinyMCE content
    tinymce.triggerSave();
    
    const formData = new FormData(this);
    formData.append('action', '<?php echo $tipId ? "update_tip" : "create_tip"; ?>');
    
    showLoading();
    
    $.ajax({
        url: '<?php echo APP_URL; ?>/api/extension.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            hideLoading();
            if (response.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    text: response.message,
                    confirmButtonColor: '#059669'
                }).then(() => {
                    window.location.href = '<?php echo APP_URL; ?>/extension/tips.php';
                });
            } else {
                showToast(response.message, 'error');
            }
        },
        error: function() {
            hideLoading();
            showToast('Failed to save tip', 'error');
        }
    });
});
</script>

<?php renderExtensionFooter(); ?>