<?php
require_once '../config/config.php';

// Require admin login
requireRole('secretariat');

$db = getDB();
$activityId = get('id', 0);
$isEdit = $activityId > 0;
$pageTitle = $isEdit ? 'Edit Activity - Secretariat - PSAU GAD' : 'Create Activity - Secretariat - PSAU GAD';

// Get activity data if editing
$activity = null;
if ($isEdit) {
    $stmt = $db->prepare("SELECT * FROM activities WHERE activity_id = ?");
    $stmt->execute([$activityId]);
    $activity = $stmt->fetch();
    
    if (!$activity) {
        setFlashMessage('error', 'Activity not found');
        redirect('activities.php');
    }
}

// Handle form submission
if (isPost()) {
    $title = sanitize(post('title'));
    $description = sanitize(post('description'));
    $activityDate = post('activity_date');
    $startTime = post('start_time');
    $endTime = post('end_time');
    $venue = sanitize(post('venue'));
    $category = post('category');
    $targetParticipants = (int)post('target_participants');
    $budget = (float)post('budget');
    $year = (int)date('Y', strtotime($activityDate));
    $quarter = post('quarter', 'Q4');

    // Validation
    $errors = [];
    
    if (empty($title)) $errors[] = 'Title is required';
    if (empty($description)) $errors[] = 'Description is required';
    if (empty($activityDate)) $errors[] = 'Activity date is required';
    if (empty($startTime)) $errors[] = 'Start time is required';
    if (empty($endTime)) $errors[] = 'End time is required';
    if (empty($venue)) $errors[] = 'Venue is required';
    if ($targetParticipants <= 0) $errors[] = 'Target participants must be greater than 0';
    
    if (empty($errors)) {
        try {
            if ($isEdit) {
                // Update existing activity
                $stmt = $db->prepare("
                    UPDATE activities SET
                        title = ?,
                        description = ?,
                        activity_date = ?,
                        start_time = ?,
                        end_time = ?,
                        venue = ?,
                        category = ?,
                        target_participants = ?,
                        budget = ?,
                        year = ?,
                        quarter = ?
                    WHERE activity_id = ?
                ");
                $stmt->execute([
                    $title, $description, $activityDate, $startTime, $endTime,
                    $venue, $category, $targetParticipants, $budget,
                    $year, $quarter, $activityId
                ]);

                setFlashMessage('success', 'Activity updated successfully');
            } else {
                // Create new activity
                $stmt = $db->prepare("
                    INSERT INTO activities (
                        title, description, activity_date, start_time, end_time,
                        venue, category, target_participants, budget,
                        year, quarter, created_by
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $title, $description, $activityDate, $startTime, $endTime,
                    $venue, $category, $targetParticipants, $budget,
                    $year, $quarter, getCurrentUserId()
                ]);

                setFlashMessage('success', 'Activity created successfully');
            }
            
            redirect('activities.php');
        } catch (Exception $e) {
            $errors[] = 'Failed to save activity. Please try again.';
            logError('Activity save error: ' . $e->getMessage());
        }
    }
    
    if (!empty($errors)) {
        setFlashMessage('error', implode('<br>', $errors));
    }
}

$categories = ['Gender Sensitivity', 'Women Empowerment', 'LGBTQ+ Rights', 'Anti-VAWC', 'Other'];
$quarters = ['Q1', 'Q2', 'Q3', 'Q4'];

include '../includes/header.php';
include '../includes/navbar.php';
?>

<div class="min-h-screen bg-gray-50 py-8">
    <div class="container mx-auto px-4 max-w-4xl">
        <!-- Page Header -->
        <div class="mb-8">
            <div class="flex items-center mb-4">
                <a href="activities.php" class="text-secretariat hover:text-secretariat-dark mr-4">
                    <i class="fas fa-arrow-left"></i>
                </a>
                <h1 class="text-3xl font-bold text-gray-900">
                    <i class="fas fa-<?php echo $isEdit ? 'edit' : 'plus'; ?> text-secretariat mr-3"></i>
                    <?php echo $isEdit ? 'Edit Activity' : 'Create New Activity'; ?>
                </h1>
            </div>
            <p class="text-gray-600">Fill in the details below to <?php echo $isEdit ? 'update' : 'create'; ?> a GAD activity</p>
        </div>

        <?php displayFlashMessage(); ?>

        <!-- Activity Form -->
        <form method="POST" class="bg-white rounded-xl shadow-lg p-8">
            <!-- Basic Information -->
            <div class="mb-8">
                <h2 class="text-xl font-bold text-gray-900 mb-4 pb-2 border-b border-gray-200">
                    <i class="fas fa-info-circle text-secretariat mr-2"></i>
                    Basic Information
                </h2>

                <div class="space-y-4">
                    <!-- Title -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            Activity Title <span class="text-red-500">*</span>
                        </label>
                        <input type="text" 
                               name="title" 
                               value="<?php echo $activity ? htmlspecialchars($activity['title']) : ''; ?>"
                               required
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent"
                               placeholder="e.g., Gender Sensitivity Training">
                    </div>

                    <!-- Description -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            Description <span class="text-red-500">*</span>
                        </label>
                        <textarea name="description" 
                                  rows="4" 
                                  required
                                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent"
                                  placeholder="Provide a detailed description of the activity..."><?php echo $activity ? htmlspecialchars($activity['description']) : ''; ?></textarea>
                    </div>

                </div>
            </div>

            <!-- Schedule & Venue -->
            <div class="mb-8">
                <h2 class="text-xl font-bold text-gray-900 mb-4 pb-2 border-b border-gray-200">
                    <i class="fas fa-calendar-alt text-secretariat mr-2"></i>
                    Schedule & Venue
                </h2>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- Activity Date -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            Activity Date <span class="text-red-500">*</span>
                        </label>
                        <input type="date" 
                               name="activity_date" 
                               value="<?php echo $activity ? $activity['activity_date'] : ''; ?>"
                               required
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent">
                    </div>

                    <!-- Venue -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            Venue <span class="text-red-500">*</span>
                        </label>
                        <input type="text" 
                               name="venue" 
                               value="<?php echo $activity ? htmlspecialchars($activity['venue']) : ''; ?>"
                               required
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent"
                               placeholder="e.g., PSAU Auditorium">
                    </div>

                    <!-- Start Time -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            Start Time <span class="text-red-500">*</span>
                        </label>
                        <input type="time" 
                               name="start_time" 
                               value="<?php echo $activity ? substr($activity['start_time'], 0, 5) : ''; ?>"
                               required
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent">
                    </div>

                    <!-- End Time -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            End Time <span class="text-red-500">*</span>
                        </label>
                        <input type="time" 
                               name="end_time" 
                               value="<?php echo $activity ? substr($activity['end_time'], 0, 5) : ''; ?>"
                               required
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent">
                    </div>
                </div>
            </div>

            <!-- Target & Budget -->
            <div class="mb-8">
                <h2 class="text-xl font-bold text-gray-900 mb-4 pb-2 border-b border-gray-200">
                    <i class="fas fa-users text-secretariat mr-2"></i>
                    Target Participants & Budget
                </h2>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <!-- Category -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            Category <span class="text-red-500">*</span>
                        </label>
                        <select name="category"
                                required
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent">
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat; ?>"
                                        <?php echo ($activity && $activity['category'] === $cat) ? 'selected' : ''; ?>>
                                    <?php echo $cat; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- Target Participants -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            Target Participants <span class="text-red-500">*</span>
                        </label>
                        <input type="number" 
                               name="target_participants" 
                               value="<?php echo $activity ? $activity['target_participants'] : '50'; ?>"
                               min="1"
                               required
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent">
                    </div>

                    <!-- Budget -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            Budget (₱)
                        </label>
                        <input type="number"
                               name="budget"
                               value="<?php echo $activity ? $activity['budget'] : '0'; ?>"
                               min="0"
                               step="0.01"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent">
                    </div>

                    <!-- Quarter -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            Quarter
                        </label>
                        <select name="quarter"
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent">
                            <?php foreach ($quarters as $q): ?>
                                <option value="<?php echo $q; ?>"
                                        <?php echo ($activity && $activity['quarter'] === $q) ? 'selected' : ($q === 'Q4' ? 'selected' : ''); ?>>
                                    <?php echo $q; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            </div>

            <!-- Form Actions -->
            <div class="flex items-center justify-end space-x-4 pt-6 border-t border-gray-200">
                <a href="activities.php" class="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition">
                    <i class="fas fa-times mr-2"></i> Cancel
                </a>
                <button type="submit" class="px-6 py-2 bg-secretariat text-white rounded-lg hover:bg-secretariat-dark transition">
                    <i class="fas fa-save mr-2"></i> <?php echo $isEdit ? 'Update' : 'Create'; ?> Activity
                </button>
            </div>
        </form>
    </div>
</div>

<?php include '../includes/footer.php'; ?>

