<?php
require_once '../config/config.php';
requireRole('secretariat');

$pageTitle = 'Monitoring Form - Secretariat - PSAU GAD';
$db = getDB();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_monitoring'])) {
    $activity_id = $_POST['activity_id'];
    $gpb_item = $_POST['gpb_item'];
    $actual_date = $_POST['actual_date'];
    $actual_budget = $_POST['actual_budget'];
    $actual_participants = $_POST['actual_participants'];
    $accomplishments = $_POST['accomplishments'];
    $challenges = $_POST['challenges'];
    $recommendations = $_POST['recommendations'];
    $submitted_by = getCurrentUserId();
    
    $stmt = $db->prepare("
        INSERT INTO monitoring_forms (activity_id, gpb_item, actual_date, actual_budget, actual_participants, accomplishments, challenges, recommendations, submitted_by)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    
    if ($stmt->execute([$activity_id, $gpb_item, $actual_date, $actual_budget, $actual_participants, $accomplishments, $challenges, $recommendations, $submitted_by])) {
        $success = "Monitoring form submitted successfully!";
    } else {
        $error = "Failed to submit monitoring form.";
    }
}

// Get activities for dropdown
$stmt = $db->query("
    SELECT activity_id, title, activity_date, budget, target_participants
    FROM activities
    WHERE is_active = 1
    ORDER BY activity_date DESC
");
$activities = $stmt->fetchAll();

// Get existing monitoring forms
$year_filter = $_GET['year'] ?? date('Y');
$stmt = $db->prepare("
    SELECT m.*, a.title as activity_title, a.activity_date, a.budget as planned_budget, a.target_participants as planned_participants, u.email as submitted_by_email
    FROM monitoring_forms m
    LEFT JOIN activities a ON m.activity_id = a.activity_id
    LEFT JOIN users u ON m.submitted_by = u.user_id
    WHERE YEAR(m.actual_date) = ?
    ORDER BY m.submitted_at DESC
");
$stmt->execute([$year_filter]);
$monitoring_forms = $stmt->fetchAll();

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

<div class="min-h-screen bg-gradient-to-br from-green-50 via-white to-teal-50 py-8">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        
        <!-- Header -->
        <div class="mb-8">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900">
                        <i class="fas fa-tasks text-secretariat mr-3"></i>
                        Monitoring Form
                    </h1>
                    <p class="text-gray-600 mt-2">Track and monitor GAD activity implementation</p>
                </div>
                <a href="reports.php" class="bg-gray-600 hover:bg-gray-700 text-white px-6 py-3 rounded-lg font-semibold transition btn-animate">
                    <i class="fas fa-arrow-left mr-2"></i>
                    Back to Reports
                </a>
            </div>
        </div>

        <?php if (isset($success)): ?>
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-lg mb-6">
                <i class="fas fa-check-circle mr-2"></i>
                <?php echo $success; ?>
            </div>
        <?php endif; ?>

        <?php if (isset($error)): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg mb-6">
                <i class="fas fa-exclamation-circle mr-2"></i>
                <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <!-- Create Monitoring Form -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
            <h2 class="text-xl font-bold text-gray-900 mb-6">
                <i class="fas fa-plus-circle text-secretariat mr-2"></i>
                Submit Monitoring Form
            </h2>
            <form method="POST" class="space-y-6" id="monitoringForm">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Activity -->
                    <div class="md:col-span-2">
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Select Activity *</label>
                        <select name="activity_id" id="activity_id" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent">
                            <option value="">Choose an activity...</option>
                            <?php foreach ($activities as $activity): ?>
                                <option value="<?php echo $activity['activity_id']; ?>" 
                                        data-date="<?php echo $activity['activity_date']; ?>"
                                        data-budget="<?php echo $activity['budget']; ?>"
                                        data-participants="<?php echo $activity['target_participants']; ?>">
                                    <?php echo htmlspecialchars($activity['title']); ?> - <?php echo date('M d, Y', strtotime($activity['activity_date'])); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- GPB Item Reference -->
                    <div class="md:col-span-2">
                        <label class="block text-sm font-semibold text-gray-700 mb-2">GPB Item Reference</label>
                        <input type="text" name="gpb_item" 
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent"
                               placeholder="Reference to GPB entry (optional)">
                    </div>

                    <!-- Actual Date -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Actual Date Conducted *</label>
                        <input type="date" name="actual_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>

                    <!-- Actual Budget -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Actual Budget (₱) *</label>
                        <input type="number" name="actual_budget" required step="0.01" min="0"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent"
                               placeholder="0.00">
                    </div>

                    <!-- Actual Participants -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Actual Participants *</label>
                        <input type="number" name="actual_participants" required min="0"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent"
                               placeholder="Number of participants">
                    </div>

                    <!-- Accomplishments -->
                    <div class="md:col-span-2">
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Accomplishments *</label>
                        <textarea name="accomplishments" required rows="4"
                                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent"
                                  placeholder="Describe what was accomplished during the activity"></textarea>
                    </div>

                    <!-- Challenges -->
                    <div class="md:col-span-2">
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Challenges Encountered</label>
                        <textarea name="challenges" rows="3"
                                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent"
                                  placeholder="Describe any challenges or issues encountered (optional)"></textarea>
                    </div>

                    <!-- Recommendations -->
                    <div class="md:col-span-2">
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Recommendations</label>
                        <textarea name="recommendations" rows="3"
                                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent"
                                  placeholder="Recommendations for future activities (optional)"></textarea>
                    </div>
                </div>

                <div class="flex justify-end gap-3">
                    <button type="reset" class="bg-gray-500 hover:bg-gray-600 text-white px-6 py-2 rounded-lg font-semibold transition">
                        <i class="fas fa-undo mr-2"></i>
                        Reset
                    </button>
                    <button type="submit" name="submit_monitoring" class="bg-secretariat hover:bg-secretariat-dark text-white px-6 py-2 rounded-lg font-semibold transition btn-animate">
                        <i class="fas fa-save mr-2"></i>
                        Submit Monitoring Form
                    </button>
                </div>
            </form>
        </div>

        <!-- Year Filter -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
            <form method="GET" class="flex gap-4 items-end">
                <div class="flex-1">
                    <label class="block text-sm font-semibold text-gray-700 mb-2">View Monitoring Forms for Year</label>
                    <select name="year" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent">
                        <?php for ($y = date('Y'); $y >= 2020; $y--): ?>
                            <option value="<?php echo $y; ?>" <?php echo $y == $year_filter ? 'selected' : ''; ?>><?php echo $y; ?></option>
                        <?php endfor; ?>
                    </select>
                </div>
                <button type="submit" class="bg-secretariat hover:bg-secretariat-dark text-white px-6 py-2 rounded-lg font-semibold transition btn-animate">
                    <i class="fas fa-filter mr-2"></i>
                    Filter
                </button>
            </form>
        </div>

        <!-- Monitoring Forms List -->
        <div class="bg-white rounded-xl shadow-lg p-6">
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-xl font-bold text-gray-900">
                    <i class="fas fa-table text-secretariat mr-2"></i>
                    Monitoring Forms for <?php echo $year_filter; ?>
                </h2>
                <a href="?year=<?php echo $year_filter; ?>&export=excel" class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg font-semibold transition btn-animate">
                    <i class="fas fa-file-excel mr-2"></i>
                    Export to Excel
                </a>
            </div>

            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Activity</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actual Date</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Budget</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Participants</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Accomplishments</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Submitted</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php if (empty($monitoring_forms)): ?>
                            <tr>
                                <td colspan="6" class="px-6 py-8 text-center text-gray-500">
                                    <i class="fas fa-inbox text-4xl mb-3"></i>
                                    <p>No monitoring forms found for <?php echo $year_filter; ?></p>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($monitoring_forms as $form): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-6 py-4">
                                        <div class="text-sm font-semibold text-gray-900"><?php echo htmlspecialchars($form['activity_title']); ?></div>
                                        <?php if ($form['gpb_item']): ?>
                                            <div class="text-xs text-gray-500">GPB: <?php echo htmlspecialchars($form['gpb_item']); ?></div>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
                                        <?php echo date('M d, Y', strtotime($form['actual_date'])); ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="text-sm font-semibold text-gray-900">₱<?php echo number_format($form['actual_budget'], 2); ?></div>
                                        <div class="text-xs text-gray-500">Planned: ₱<?php echo number_format($form['planned_budget'], 2); ?></div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="text-sm font-semibold text-gray-900"><?php echo $form['actual_participants']; ?></div>
                                        <div class="text-xs text-gray-500">Target: <?php echo $form['planned_participants']; ?></div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="text-sm text-gray-700"><?php echo htmlspecialchars(substr($form['accomplishments'], 0, 100)); ?>...</div>
                                        <?php if ($form['challenges']): ?>
                                            <div class="text-xs text-red-600 mt-1">⚠️ Challenges noted</div>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-xs text-gray-500">
                                        <?php echo date('M d, Y', strtotime($form['submitted_at'])); ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</div>

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

