<?php
/**
 * ============================================================================
 * extension/schedule-service.php
 * Schedule Extension Service - Using Dashboard Layout
 * ============================================================================
 */

if (!defined('AIMS_ACCESS')) {
    define('AIMS_ACCESS', true);
}

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

// Get officer profile for location info
$sql = "SELECT eo.*, u.district_id, u.subcounty_id, u.parish_id, u.village_id,
        d.district_name, s.subcounty_name, p.parish_name, v.village_name
        FROM extension_officer_profiles eo
        JOIN users u ON eo.user_id = u.id
        LEFT JOIN districts d ON u.district_id = d.id
        LEFT JOIN subcounties s ON u.subcounty_id = s.id
        LEFT JOIN parishes p ON u.parish_id = p.id
        LEFT JOIN villages v ON u.village_id = v.id
        WHERE eo.user_id = ?";
$stmt = $db->prepare($sql);
$stmt->execute([$currentUserId]);
$profile = $stmt->fetch();

$pageTitle = 'Schedule Service - AIMS Extension';
$breadcrumbs = [
    ['title' => 'Services', 'url' => APP_URL . '/extension/services.php'],
    ['title' => 'Schedule Service', 'url' => '']
];

renderExtensionHeader($pageTitle, $breadcrumbs);
?>

<style>
    .form-card {
        border-radius: 15px;
        transition: all 0.3s ease;
    }
    
    .form-card:hover {
        box-shadow: 0 10px 25px rgba(0,0,0,0.1);
    }
    
    .service-type-card {
        border: 2px solid #e5e7eb;
        border-radius: 12px;
        padding: 20px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s ease;
        background: white;
    }
    
    .service-type-card:hover {
        border-color: var(--primary-color);
        background: #f0fdf4;
        transform: translateY(-3px);
    }
    
    .service-type-card.selected {
        border-color: var(--primary-color);
        background: #f0fdf4;
        box-shadow: 0 0 0 3px rgba(5, 150, 105, 0.1);
    }
    
    .service-type-card .icon {
        width: 60px;
        height: 60px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 2rem;
        margin: 0 auto 15px;
        background: #f0fdf4;
        color: var(--primary-color);
    }
    
    .service-type-card.selected .icon {
        background: var(--primary-color);
        color: white;
    }
    
    .form-section {
        background: white;
        border-radius: 12px;
        padding: 25px;
        margin-bottom: 20px;
        border: 1px solid #e5e7eb;
    }
    
    .form-section-title {
        font-size: 1.1rem;
        font-weight: 600;
        color: #1f2937;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 2px solid #e5e7eb;
    }
    
    .form-section-title i {
        color: var(--primary-color);
        margin-right: 10px;
    }
    
    .info-alert {
        background: #eff6ff;
        border-left: 4px solid #3b82f6;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 20px;
    }
</style>

<div class="container-fluid py-4">
    <div class="row justify-content-center">
        <div class="col-xl-10">
            <!-- Page 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/" class="btn btn-outline-secondary me-3">
                            <i class="bi bi-arrow-left"></i>
                        </a>
                        <div class="flex-grow-1">
                            <h4 class="mb-1 fw-bold">
                                <i class="bi bi-calendar-plus text-primary me-2"></i>Schedule Extension Service
                            </h4>
                            <p class="text-muted mb-0">Create a new service for farmers in your coverage area</p>
                        </div>
                        <div class="text-end d-none d-md-block">
                            <span class="badge bg-success bg-opacity-10 text-success px-3 py-2">
                                <i class="bi bi-geo-alt me-1"></i><?php echo htmlspecialchars($coverageArea); ?>
                            </span>
                        </div>
                    </div>
                </div>
            </div>

            <form id="scheduleServiceForm" method="POST">
                <!-- Service Type Selection -->
                <div class="form-section">
                    <h5 class="form-section-title">
                        <i class="bi bi-clipboard-check"></i>Select Service Type
                    </h5>
                    
                    <div class="row g-3">
                        <div class="col-md-3 col-6">
                            <div class="service-type-card" data-type="farm_visit">
                                <div class="icon">
                                    <i class="bi bi-house-door"></i>
                                </div>
                                <h6 class="mb-1 fw-semibold">Farm Visit</h6>
                                <small class="text-muted">One-on-one farm assessment</small>
                            </div>
                        </div>
                        
                        <div class="col-md-3 col-6">
                            <div class="service-type-card" data-type="training">
                                <div class="icon">
                                    <i class="bi bi-book"></i>
                                </div>
                                <h6 class="mb-1 fw-semibold">Training</h6>
                                <small class="text-muted">Group training session</small>
                            </div>
                        </div>
                        
                        <div class="col-md-3 col-6">
                            <div class="service-type-card" data-type="consultation">
                                <div class="icon">
                                    <i class="bi bi-chat-dots"></i>
                                </div>
                                <h6 class="mb-1 fw-semibold">Consultation</h6>
                                <small class="text-muted">Expert advice session</small>
                            </div>
                        </div>
                        
                        <div class="col-md-3 col-6">
                            <div class="service-type-card" data-type="demonstration">
                                <div class="icon">
                                    <i class="bi bi-eye"></i>
                                </div>
                                <h6 class="mb-1 fw-semibold">Demonstration</h6>
                                <small class="text-muted">Practical demo</small>
                            </div>
                        </div>
                    </div>
                    
                    <input type="hidden" name="service_type" id="service_type" required>
                </div>

                <!-- Service Details -->
                <div class="form-section">
                    <h5 class="form-section-title">
                        <i class="bi bi-info-circle"></i>Service Details
                    </h5>
                    
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <label class="form-label fw-semibold">
                                Service Title <span class="text-danger">*</span>
                            </label>
                            <input type="text" class="form-control form-control-lg" name="title" 
                                   placeholder="e.g., Coffee Growing Best Practices Training" required>
                            <small class="text-muted">Give your service a clear, descriptive title</small>
                        </div>

                        <div class="col-md-12 mb-3">
                            <label class="form-label fw-semibold">Description</label>
                            <textarea class="form-control" name="description" rows="4" 
                                      placeholder="Describe what this service will cover and what farmers will learn..."></textarea>
                            <small class="text-muted">What will farmers learn or benefit from this service?</small>
                        </div>
                    </div>
                </div>

                <!-- Schedule & Location -->
                <div class="form-section">
                    <h5 class="form-section-title">
                        <i class="bi bi-calendar-event"></i>Schedule & Location
                    </h5>
                    
                    <div class="info-alert mb-3">
                        <i class="bi bi-info-circle me-2"></i>
                        <strong>Note:</strong> Choose a date and time that gives farmers enough notice to plan their attendance.
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold">
                                Date <span class="text-danger">*</span>
                            </label>
                            <input type="date" class="form-control form-control-lg" name="scheduled_date" 
                                   min="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold">Time</label>
                            <input type="time" class="form-control form-control-lg" name="scheduled_time" 
                                   value="10:00">
                            <small class="text-muted">Recommended: Morning hours (8 AM - 12 PM)</small>
                        </div>

                        <div class="col-md-12 mb-3">
                            <label class="form-label fw-semibold">
                                Location <span class="text-danger">*</span>
                            </label>
                            <input type="text" class="form-control form-control-lg" name="location" 
                                   value="<?php echo htmlspecialchars($profile['village_name'] ?? $profile['parish_name'] ?? $profile['subcounty_name'] ?? $profile['district_name'] ?? ''); ?>" 
                                   placeholder="Village, Parish, or specific landmark" required>
                            <small class="text-muted">
                                <i class="bi bi-geo-alt me-1"></i>Be specific to help farmers find the location easily
                            </small>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold">Duration (hours)</label>
                            <select class="form-select form-select-lg" name="duration_hours">
                                <option value="1">1 hour</option>
                                <option value="2" selected>2 hours</option>
                                <option value="3">3 hours</option>
                                <option value="4">4 hours (Half day)</option>
                                <option value="8">8 hours (Full day)</option>
                            </select>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold">Max Participants</label>
                            <input type="number" class="form-control form-control-lg" name="max_participants" 
                                   min="1" max="500" placeholder="Leave empty for unlimited">
                            <small class="text-muted">Optional: Set a maximum number of participants</small>
                        </div>
                    </div>
                </div>

                <!-- Action Buttons -->
                <div class="form-section">
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-success btn-lg flex-fill">
                            <i class="bi bi-calendar-check me-2"></i>Schedule Service
                        </button>
                        <a href="<?php echo APP_URL; ?>/extension/" class="btn btn-outline-secondary btn-lg">
                            <i class="bi bi-x-lg me-2"></i>Cancel
                        </a>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Service type selection
    $('.service-type-card').on('click', function() {
        $('.service-type-card').removeClass('selected');
        $(this).addClass('selected');
        $('#service_type').val($(this).data('type'));
    });
    
    // Form submission
    $('#scheduleServiceForm').on('submit', function(e) {
        e.preventDefault();
        
        // Validate service type selection
        if (!$('#service_type').val()) {
            showToast('Please select a service type', 'warning');
            $('html, body').animate({
                scrollTop: $('.service-type-card').first().offset().top - 100
            }, 500);
            return;
        }
        
        showLoading();
        
        $.ajax({
            url: '<?php echo APP_URL; ?>/api/extension.php',
            type: 'POST',
            data: $(this).serialize() + '&action=schedule_service',
            dataType: 'json',
            success: function(response) {
                hideLoading();
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Service Scheduled!',
                        text: response.message,
                        confirmButtonColor: '#059669',
                        confirmButtonText: 'View Service'
                    }).then(() => {
                        window.location.href = '<?php echo APP_URL; ?>/extension/service-details.php?id=' + response.service_id;
                    });
                } else {
                    showToast(response.message || 'Failed to schedule service', 'error');
                }
            },
            error: function(xhr) {
                hideLoading();
                console.error('Error:', xhr);
                showToast('Failed to schedule service. Please try again.', 'error');
            }
        });
    });
    
    // Auto-fill minimum date
    const today = new Date().toISOString().split('T')[0];
    $('input[name="scheduled_date"]').attr('min', today);
});
</script>

<?php renderExtensionFooter(); ?>