<?php
/**
 * ============================================================================
 * learning/schedules.php - Farming Calendar & Schedule Management
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Farming Calendar';
$userId = getUserId();

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

// Get filter parameters
$crop_filter = isset($_GET['crop']) ? $_GET['crop'] : 'all';
$activity_filter = isset($_GET['activity']) ? $_GET['activity'] : 'all';
$view_mode = isset($_GET['view']) ? $_GET['view'] : 'timeline';

// Build query for schedules
$sql = "SELECT * FROM farming_schedules WHERE is_published = 1";
$params = [];

if ($crop_filter != 'all') {
    $sql .= " AND crop_type = ?";
    $params[] = $crop_filter;
}

if ($activity_filter != 'all') {
    $sql .= " AND activity_type = ?";
    $params[] = $activity_filter;
}

$sql .= " ORDER BY crop_type, week_from_planting";

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

// Get user's reminders
try {
    $reminders_sql = "SELECT ufr.*, fs.title as schedule_title, fs.activity_type, e.enterprise_type 
                      FROM user_farming_reminders ufr 
                      LEFT JOIN farming_schedules fs ON ufr.schedule_id = fs.id
                      LEFT JOIN enterprises e ON ufr.enterprise_id = e.id
                      WHERE ufr.user_id = ? 
                      AND ufr.status = 'pending'
                      AND ufr.reminder_date >= CURDATE()
                      ORDER BY ufr.reminder_date, ufr.reminder_time
                      LIMIT 10";
    $reminders_stmt = $db->prepare($reminders_sql);
    $reminders_stmt->execute([$userId]);
    $user_reminders = $reminders_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $user_reminders = [];
}

// Get seasonal calendar
try {
    $seasons_sql = "SELECT * FROM seasonal_calendar WHERE region = 'Luuka' ORDER BY start_month";
    $seasons_stmt = $db->query($seasons_sql);
    $seasons = $seasons_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $seasons = [];
}

// Get current month to highlight current season
$current_month = date('n');

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-calendar-check text-success"></i> Farming Calendar
                    </h2>
                    <p class="text-muted mb-0">Plan and track your farming activities</p>
                </div>
                <div class="d-flex gap-2">
                    <a href="<?php echo APP_URL; ?>/learning/" class="btn btn-outline-primary">
                        <i class="bi bi-arrow-left"></i> Back
                    </a>
                    <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addReminderModal">
                        <i class="bi bi-plus-circle"></i> Add Reminder
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Seasonal Calendar -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-gradient text-white" style="background: linear-gradient(135deg, #059669 0%, #10b981 100%);">
                    <h5 class="mb-0">
                        <i class="bi bi-calendar4-range"></i> Seasonal Calendar - Luuka District
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <?php foreach ($seasons as $season): ?>
                            <?php
                            $is_current_season = ($current_month >= $season['start_month'] && $current_month <= $season['end_month']);
                            $season_colors = [
                                'first_season' => 'primary',
                                'second_season' => 'info',
                                'dry_season' => 'warning'
                            ];
                            $color = $season_colors[$season['season_type']] ?? 'secondary';
                            ?>
                            <div class="col-md-4 mb-3">
                                <div class="card h-100 border-<?php echo $color; ?> <?php echo $is_current_season ? 'shadow-lg' : ''; ?>">
                                    <div class="card-header bg-<?php echo $color; ?> text-white">
                                        <h6 class="mb-0">
                                            <?php echo htmlspecialchars($season['season_name']); ?>
                                            <?php if ($is_current_season): ?>
                                                <span class="badge bg-light text-dark float-end">Current</span>
                                            <?php endif; ?>
                                        </h6>
                                    </div>
                                    <div class="card-body">
                                        <p class="mb-2">
                                            <i class="bi bi-calendar3"></i> 
                                            <strong>Period:</strong> <?php echo date('F', mktime(0, 0, 0, $season['start_month'], 1)); ?> - 
                                            <?php echo date('F', mktime(0, 0, 0, $season['end_month'], 1)); ?>
                                        </p>
                                        <p class="mb-2 text-muted"><?php echo htmlspecialchars($season['description']); ?></p>
                                        
                                        <?php if ($season['recommended_crops']): ?>
                                            <div class="mb-2">
                                                <small class="text-muted"><i class="bi bi-flower3"></i> <strong>Recommended:</strong></small><br>
                                                <small><?php echo htmlspecialchars($season['recommended_crops']); ?></small>
                                            </div>
                                        <?php endif; ?>

                                        <?php if ($season['weather_pattern']): ?>
                                            <div class="alert alert-<?php echo $color; ?> alert-sm py-1 px-2 mb-0">
                                                <small><i class="bi bi-cloud-rain"></i> <?php echo htmlspecialchars($season['weather_pattern']); ?></small>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Upcoming Reminders -->
    <?php if (!empty($user_reminders)): ?>
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-warning text-dark">
                    <h5 class="mb-0">
                        <i class="bi bi-bell"></i> Your Upcoming Activities
                    </h5>
                </div>
                <div class="card-body">
                    <div class="list-group list-group-flush">
                        <?php foreach ($user_reminders as $reminder): ?>
                            <div class="list-group-item d-flex align-items-center">
                                <div class="flex-shrink-0 me-3">
                                    <div class="reminder-date text-center">
                                        <div class="bg-success text-white px-3 py-2 rounded">
                                            <div class="fw-bold"><?php echo date('d', strtotime($reminder['reminder_date'])); ?></div>
                                            <small><?php echo date('M', strtotime($reminder['reminder_date'])); ?></small>
                                        </div>
                                    </div>
                                </div>
                                <div class="flex-grow-1">
                                    <h6 class="mb-1"><?php echo htmlspecialchars($reminder['title']); ?></h6>
                                    <p class="text-muted mb-1 small">
                                        <?php echo htmlspecialchars($reminder['description'] ?? ''); ?>
                                    </p>
                                    <small class="text-muted">
                                        <i class="bi bi-clock"></i> <?php echo $reminder['reminder_time'] ? date('g:i A', strtotime($reminder['reminder_time'])) : 'All day'; ?>
                                        <?php if ($reminder['enterprise_type']): ?>
                                            | <i class="bi bi-tag"></i> <?php echo ucwords(str_replace('_', ' ', $reminder['enterprise_type'])); ?>
                                        <?php endif; ?>
                                    </small>
                                </div>
                                <div class="flex-shrink-0">
                                    <button class="btn btn-sm btn-success" onclick="completeReminder(<?php echo $reminder['id']; ?>)">
                                        <i class="bi bi-check-lg"></i>
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger" onclick="deleteReminder(<?php echo $reminder['id']; ?>)">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- View Mode Toggle -->
    <div class="row mb-3">
        <div class="col-12">
            <div class="btn-group" role="group">
                <a href="?view=timeline&crop=<?php echo $crop_filter; ?>&activity=<?php echo $activity_filter; ?>" 
                   class="btn btn-sm <?php echo $view_mode == 'timeline' ? 'btn-primary' : 'btn-outline-primary'; ?>">
                    <i class="bi bi-list-ol"></i> Timeline View
                </a>
                <a href="?view=cards&crop=<?php echo $crop_filter; ?>&activity=<?php echo $activity_filter; ?>" 
                   class="btn btn-sm <?php echo $view_mode == 'cards' ? 'btn-primary' : 'btn-outline-primary'; ?>">
                    <i class="bi bi-grid-3x3"></i> Card View
                </a>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <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">
                        <input type="hidden" name="view" value="<?php echo $view_mode; ?>">
                        
                        <div class="col-md-6">
                            <label class="form-label"><i class="bi bi-flower3"></i> Crop Type</label>
                            <select name="crop" class="form-select" onchange="this.form.submit()">
                                <option value="all" <?php echo $crop_filter == 'all' ? 'selected' : ''; ?>>All Crops</option>
                                <option value="maize" <?php echo $crop_filter == 'maize' ? 'selected' : ''; ?>>Maize</option>
                                <option value="beans" <?php echo $crop_filter == 'beans' ? 'selected' : ''; ?>>Beans</option>
                                <option value="cassava" <?php echo $crop_filter == 'cassava' ? 'selected' : ''; ?>>Cassava</option>
                                <option value="bananas" <?php echo $crop_filter == 'bananas' ? 'selected' : ''; ?>>Bananas</option>
                                <option value="vegetables" <?php echo $crop_filter == 'vegetables' ? 'selected' : ''; ?>>Vegetables</option>
                                <option value="sugar_cane" <?php echo $crop_filter == 'sugar_cane' ? 'selected' : ''; ?>>Sugar Cane</option>
                                <option value="coffee" <?php echo $crop_filter == 'coffee' ? 'selected' : ''; ?>>Coffee</option>
                            </select>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label"><i class="bi bi-tools"></i> Activity Type</label>
                            <select name="activity" class="form-select" onchange="this.form.submit()">
                                <option value="all" <?php echo $activity_filter == 'all' ? 'selected' : ''; ?>>All Activities</option>
                                <option value="land_preparation" <?php echo $activity_filter == 'land_preparation' ? 'selected' : ''; ?>>Land Preparation</option>
                                <option value="planting" <?php echo $activity_filter == 'planting' ? 'selected' : ''; ?>>Planting</option>
                                <option value="weeding" <?php echo $activity_filter == 'weeding' ? 'selected' : ''; ?>>Weeding</option>
                                <option value="fertilization" <?php echo $activity_filter == 'fertilization' ? 'selected' : ''; ?>>Fertilization</option>
                                <option value="pest_control" <?php echo $activity_filter == 'pest_control' ? 'selected' : ''; ?>>Pest Control</option>
                                <option value="irrigation" <?php echo $activity_filter == 'irrigation' ? 'selected' : ''; ?>>Irrigation</option>
                                <option value="harvesting" <?php echo $activity_filter == 'harvesting' ? 'selected' : ''; ?>>Harvesting</option>
                                <option value="post_harvest" <?php echo $activity_filter == 'post_harvest' ? 'selected' : ''; ?>>Post-Harvest</option>
                            </select>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Schedules Display -->
    <?php if ($view_mode == 'timeline'): ?>
        <!-- Timeline View -->
        <?php
        $grouped_schedules = [];
        foreach ($schedules as $schedule) {
            $grouped_schedules[$schedule['crop_type']][] = $schedule;
        }
        ?>

        <?php foreach ($grouped_schedules as $crop => $crop_schedules): ?>
            <div class="row mb-4">
                <div class="col-12">
                    <div class="card border-0 shadow-sm">
                        <div class="card-header bg-success text-white">
                            <h5 class="mb-0">
                                <i class="bi bi-flower3"></i> <?php echo ucwords(str_replace('_', ' ', $crop)); ?> - Farming Timeline
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="timeline">
                                <?php foreach ($crop_schedules as $index => $schedule): ?>
                                    <?php
                                    $activity_icons = [
                                        'land_preparation' => 'tools',
                                        'planting' => 'flower1',
                                        'weeding' => 'scissors',
                                        'fertilization' => 'droplet',
                                        'pest_control' => 'bug',
                                        'irrigation' => 'water',
                                        'harvesting' => 'basket',
                                        'post_harvest' => 'box-seam'
                                    ];
                                    $icon = $activity_icons[$schedule['activity_type']] ?? 'circle';
                                    ?>
                                    
                                    <div class="timeline-item <?php echo $index % 2 == 0 ? 'timeline-left' : 'timeline-right'; ?>">
                                        <div class="timeline-marker">
                                            <i class="bi bi-<?php echo $icon; ?>"></i>
                                        </div>
                                        <div class="timeline-content">
                                            <div class="card border-0 shadow-sm">
                                                <div class="card-body">
                                                    <div class="d-flex justify-content-between align-items-start mb-2">
                                                        <h6 class="mb-0"><?php echo htmlspecialchars($schedule['title']); ?></h6>
                                                        <span class="badge bg-primary">
                                                            <?php echo $schedule['timing'] ?? "Week {$schedule['week_from_planting']}"; ?>
                                                        </span>
                                                    </div>
                                                    
                                                    <p class="text-muted mb-2"><?php echo htmlspecialchars($schedule['description']); ?></p>
                                                    
                                                    <?php if ($schedule['materials_needed']): ?>
                                                        <div class="mb-2">
                                                            <small class="text-muted">
                                                                <i class="bi bi-tools"></i> <strong>Materials:</strong> 
                                                                <?php echo htmlspecialchars($schedule['materials_needed']); ?>
                                                            </small>
                                                        </div>
                                                    <?php endif; ?>
                                                    
                                                    <?php if ($schedule['estimated_cost']): ?>
                                                        <div class="mb-2">
                                                            <small class="text-success">
                                                                <i class="bi bi-currency-exchange"></i> <strong>Est. Cost:</strong> 
                                                                UGX <?php echo number_format($schedule['estimated_cost']); ?>
                                                            </small>
                                                        </div>
                                                    <?php endif; ?>
                                                    
                                                    <div class="d-flex gap-2 mt-3">
                                                        <button class="btn btn-sm btn-outline-primary" onclick="viewScheduleDetails(<?php echo $schedule['id']; ?>)">
                                                            <i class="bi bi-eye"></i> Details
                                                        </button>
                                                        <button class="btn btn-sm btn-success" onclick="createReminder(<?php echo $schedule['id']; ?>)">
                                                            <i class="bi bi-bell"></i> Set Reminder
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>

    <?php else: ?>
        <!-- Card View -->
        <div class="row">
            <?php foreach ($schedules as $schedule): ?>
                <?php
                $activity_colors = [
                    'land_preparation' => 'secondary',
                    'planting' => 'success',
                    'weeding' => 'warning',
                    'fertilization' => 'info',
                    'pest_control' => 'danger',
                    'irrigation' => 'primary',
                    'harvesting' => 'success',
                    'post_harvest' => 'dark'
                ];
                $color = $activity_colors[$schedule['activity_type']] ?? 'secondary';
                
                $priority_badges = [
                    'low' => 'secondary',
                    'medium' => 'primary',
                    'high' => 'warning',
                    'critical' => 'danger'
                ];
                $priority_color = $priority_badges[$schedule['priority']] ?? 'secondary';
                ?>
                
                <div class="col-lg-4 col-md-6 mb-4">
                    <div class="card border-0 shadow-sm h-100 schedule-card">
                        <div class="card-header bg-<?php echo $color; ?> text-white">
                            <div class="d-flex justify-content-between align-items-center">
                                <h6 class="mb-0">
                                    <i class="bi bi-<?php echo $activity_icons[$schedule['activity_type']] ?? 'circle'; ?>"></i>
                                    <?php echo ucwords(str_replace('_', ' ', $schedule['activity_type'])); ?>
                                </h6>
                                <span class="badge bg-<?php echo $priority_color; ?>">
                                    <?php echo ucfirst($schedule['priority']); ?>
                                </span>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="mb-2">
                                <span class="badge bg-light text-dark">
                                    <?php echo ucwords(str_replace('_', ' ', $schedule['crop_type'])); ?>
                                </span>
                                <span class="badge bg-primary">
                                    <?php echo $schedule['timing'] ?? "Week {$schedule['week_from_planting']}"; ?>
                                </span>
                            </div>
                            
                            <h6 class="card-title"><?php echo htmlspecialchars($schedule['title']); ?></h6>
                            <p class="text-muted small"><?php echo truncate(strip_tags($schedule['description']), 100); ?></p>
                            
                            <?php if ($schedule['estimated_cost']): ?>
                                <p class="text-success mb-2">
                                    <i class="bi bi-currency-exchange"></i> 
                                    UGX <?php echo number_format($schedule['estimated_cost']); ?>
                                </p>
                            <?php endif; ?>
                            
                            <?php if ($schedule['duration_days']): ?>
                                <p class="text-muted small mb-0">
                                    <i class="bi bi-clock"></i> Duration: <?php echo $schedule['duration_days']; ?> days
                                </p>
                            <?php endif; ?>
                        </div>
                        <div class="card-footer bg-transparent">
                            <div class="d-grid gap-2">
                                <button class="btn btn-sm btn-outline-primary" onclick="viewScheduleDetails(<?php echo $schedule['id']; ?>)">
                                    <i class="bi bi-eye"></i> View Details
                                </button>
                                <button class="btn btn-sm btn-success" onclick="createReminder(<?php echo $schedule['id']; ?>)">
                                    <i class="bi bi-bell"></i> Set Reminder
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <?php if (empty($schedules)): ?>
        <div class="row">
            <div class="col-12">
                <div class="alert alert-info">
                    <i class="bi bi-info-circle"></i> No schedules found matching your filters.
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<!-- Schedule Details Modal -->
<div class="modal fade" id="scheduleModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="scheduleModalTitle">Loading...</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="scheduleModalBody">
                <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="createReminderFromSchedule()">
                    <i class="bi bi-bell"></i> Set Reminder
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Add Reminder Modal -->
<div class="modal fade" id="addReminderModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-bell text-success"></i> Add Farming Reminder
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="addReminderForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Title *</label>
                        <input type="text" class="form-control" name="title" required placeholder="e.g., First Weeding">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea class="form-control" name="description" rows="3" placeholder="Additional notes..."></textarea>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Date *</label>
                            <input type="date" class="form-control" name="reminder_date" required min="<?php echo date('Y-m-d'); ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Time</label>
                            <input type="time" class="form-control" name="reminder_time">
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Activity Type</label>
                        <select class="form-select" name="activity_type">
                            <option value="custom">Custom</option>
                            <option value="land_preparation">Land Preparation</option>
                            <option value="planting">Planting</option>
                            <option value="weeding">Weeding</option>
                            <option value="fertilization">Fertilization</option>
                            <option value="pest_control">Pest Control</option>
                            <option value="irrigation">Irrigation</option>
                            <option value="harvesting">Harvesting</option>
                            <option value="post_harvest">Post-Harvest</option>
                        </select>
                    </div>

                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_recurring" id="isRecurring">
                        <label class="form-check-label" for="isRecurring">
                            Recurring reminder
                        </label>
                    </div>

                    <div id="recurrenceOptions" class="mt-3" style="display: none;">
                        <select class="form-select" name="recurrence_pattern">
                            <option value="daily">Daily</option>
                            <option value="weekly">Weekly</option>
                            <option value="monthly">Monthly</option>
                        </select>
                    </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-success">
                        <i class="bi bi-check-lg"></i> Add Reminder
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
.timeline {
    position: relative;
    padding: 20px 0;
}

.timeline::before {
    content: '';
    position: absolute;
    left: 50%;
    top: 0;
    bottom: 0;
    width: 4px;
    background: linear-gradient(to bottom, #059669, #10b981);
    transform: translateX(-50%);
}

.timeline-item {
    position: relative;
    margin-bottom: 40px;
    width: 45%;
}

.timeline-left {
    left: 0;
}

.timeline-right {
    left: 55%;
}

.timeline-marker {
    position: absolute;
    top: 0;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #059669;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.2rem;
    z-index: 10;
    border: 4px solid white;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
}

.timeline-left .timeline-marker {
    right: -65px;
}

.timeline-right .timeline-marker {
    left: -65px;
}

.timeline-content {
    position: relative;
}

.schedule-card {
    transition: all 0.3s ease;
}

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

.reminder-date {
    min-width: 70px;
}

@media (max-width: 768px) {
    .timeline::before {
        left: 20px;
    }
    
    .timeline-item {
        width: 100%;
        left: 0 !important;
        padding-left: 60px;
    }
    
    .timeline-left .timeline-marker,
    .timeline-right .timeline-marker {
        left: 0;
        right: auto;
    }
}
</style>

<script>
let currentScheduleId = null;

function viewScheduleDetails(scheduleId) {
    currentScheduleId = scheduleId;
    const modal = new bootstrap.Modal(document.getElementById('scheduleModal'));
    modal.show();
    
    $.get(APP_URL + '/ajax/get-schedule.php', { id: scheduleId }, function(response) {
        if (response.success) {
            const schedule = response.data;
            $('#scheduleModalTitle').html(schedule.title);
            
            let html = `
                <div class="schedule-details">
                    <div class="mb-4">
                        <span class="badge bg-primary">${schedule.crop_type_formatted}</span>
                        <span class="badge bg-info">${schedule.activity_type_formatted}</span>
                        <span class="badge bg-success">${schedule.timing || 'Week ' + schedule.week_from_planting}</span>
                    </div>

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

                    ${schedule.instructions ? `
                        <div class="mb-4">
                            <h6><i class="bi bi-list-check text-success"></i> Instructions</h6>
                            <div class="alert alert-light">${schedule.instructions.replace(/\n/g, '<br>')}</div>
                        </div>
                    ` : ''}

                    ${schedule.materials_needed ? `
                        <div class="mb-4">
                            <h6><i class="bi bi-tools text-warning"></i> Materials Needed</h6>
                            <p>${schedule.materials_needed}</p>
                        </div>
                    ` : ''}

                    <div class="row">
                        ${schedule.duration_days ? `
                            <div class="col-6 mb-3">
                                <div class="card bg-light">
                                    <div class="card-body text-center">
                                        <i class="bi bi-clock text-primary fs-3"></i>
                                        <h6 class="mt-2 mb-0">${schedule.duration_days} Days</h6>
                                        <small class="text-muted">Duration</small>
                                    </div>
                                </div>
                            </div>
                        ` : ''}

                        ${schedule.estimated_cost ? `
                            <div class="col-6 mb-3">
                                <div class="card bg-light">
                                    <div class="card-body text-center">
                                        <i class="bi bi-currency-exchange text-success fs-3"></i>
                                        <h6 class="mt-2 mb-0">UGX ${Number(schedule.estimated_cost).toLocaleString()}</h6>
                                        <small class="text-muted">Estimated Cost</small>
                                    </div>
                                </div>
                            </div>
                        ` : ''}
                    </div>
                </div>
            `;
            
            $('#scheduleModalBody').html(html);
        }
    });
}

function createReminder(scheduleId) {
    currentScheduleId = scheduleId;
    $('#addReminderModal').modal('show');
}

function createReminderFromSchedule() {
    if (currentScheduleId) {
        createReminder(currentScheduleId);
        $('#scheduleModal').modal('hide');
    }
}

function completeReminder(reminderId) {
    Swal.fire({
        title: 'Mark as Completed?',
        text: "This activity will be marked as completed",
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#059669',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Yes, complete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            $.post(APP_URL + '/ajax/complete-reminder.php', { id: reminderId }, function(response) {
                if (response.success) {
                    Toastify({
                        text: "Activity marked as completed!",
                        backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
                        duration: 3000
                    }).showToast();
                    setTimeout(() => location.reload(), 1000);
                }
            });
        }
    });
}

function deleteReminder(reminderId) {
    Swal.fire({
        title: 'Delete Reminder?',
        text: "This action cannot be undone",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc3545',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            $.post(APP_URL + '/ajax/delete-reminder.php', { id: reminderId }, function(response) {
                if (response.success) {
                    Toastify({
                        text: "Reminder deleted successfully",
                        backgroundColor: "linear-gradient(to right, #ff5f6d, #ffc371)",
                        duration: 3000
                    }).showToast();
                    setTimeout(() => location.reload(), 1000);
                }
            });
        }
    });
}

// Add Reminder Form
$('#addReminderForm').on('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    if (currentScheduleId) {
        formData.append('schedule_id', currentScheduleId);
    }
    
    $.ajax({
        url: APP_URL + '/ajax/add-reminder.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Reminder Added!',
                    text: 'You will be notified at the scheduled time.',
                    confirmButtonColor: '#059669'
                });
                $('#addReminderModal').modal('hide');
                $('#addReminderForm')[0].reset();
                setTimeout(() => location.reload(), 1500);
            }
        }
    });
});

// Toggle recurrence options
$('#isRecurring').on('change', function() {
    $('#recurrenceOptions').toggle(this.checked);
});
</script>

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