<?php
/**
 * Notification System Test Script
 * GHAMECC Job Portal
 * 
 * This script tests the notification system by creating sample notifications
 * of different types for the current logged-in user.
 */

// Include required files
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
require_once '../includes/notifications-library.php';

// Check if user is logged in
if (!isLoggedIn()) {
    header('Location: ../login.php');
    exit;
}

// Get current user ID
$userId = $_SESSION['user_id'];

// Initialize results array
$results = [];

// Function to create a test notification and record result
function createTestNotification($function, $params, &$results) {
    try {
        $result = call_user_func_array($function, $params);
        $results[] = [
            'function' => $function,
            'params' => $params,
            'success' => $result !== false,
            'result' => $result
        ];
        return $result;
    } catch (Exception $e) {
        $results[] = [
            'function' => $function,
            'params' => $params,
            'success' => false,
            'error' => $e->getMessage()
        ];
        return false;
    }
}

// Process test action if submitted
$action = isset($_POST['action']) ? $_POST['action'] : '';
$testType = isset($_POST['test_type']) ? $_POST['test_type'] : '';

if ($action === 'run_test') {
    // Create sample data for tests
    $jobId = 1; // Sample job ID
    $applicationId = 1; // Sample application ID
    $ratingId = 1; // Sample rating ID
    $reviewId = 1; // Sample review ID
    $otherUserId = ($userId == 1) ? 2 : 1; // Just use a different user ID for testing
    
    switch ($testType) {
        case 'all':
            // Test all notification types
            createTestNotification('createNotification', [$userId, 'test', 'This is a general test notification', 'notifications.php'], $results);
            createTestNotification('createJobApplicationNotification', [$otherUserId, $jobId, $applicationId], $results);
            createTestNotification('createNewRatingNotification', [$otherUserId, $userId, $ratingId, 4], $results);
            createTestNotification('createNewReviewNotification', [$otherUserId, $userId, $reviewId, 'Great work!'], $results);
            createTestNotification('createApplicationStatusNotification', [$otherUserId, $jobId, $applicationId, 'shortlisted'], $results);
            createTestNotification('createJobMatchNotification', [$userId, $jobId, 'Web Developer', ['PHP', 'JavaScript']], $results);
            break;
            
        case 'job_application':
            createTestNotification('createJobApplicationNotification', [$otherUserId, $jobId, $applicationId], $results);
            break;
            
        case 'rating':
            createTestNotification('createNewRatingNotification', [$otherUserId, $userId, $ratingId, 4], $results);
            break;
            
        case 'review':
            createTestNotification('createNewReviewNotification', [$otherUserId, $userId, $reviewId, 'Great work!'], $results);
            break;
            
        case 'application_status':
            $statuses = ['pending', 'shortlisted', 'rejected', 'selected'];
            $status = $statuses[array_rand($statuses)];
            createTestNotification('createApplicationStatusNotification', [$otherUserId, $jobId, $applicationId, $status], $results);
            break;
            
        case 'job_match':
            $skills = ['PHP', 'JavaScript', 'HTML', 'CSS', 'MySQL', 'React', 'Node.js'];
            $randomSkills = array_rand(array_flip($skills), 3);
            createTestNotification('createJobMatchNotification', [$userId, $jobId, 'Web Developer', $randomSkills], $results);
            break;
            
        case 'general':
        default:
            createTestNotification('createNotification', [$userId, 'test', 'This is a general test notification', 'notifications.php'], $results);
            break;
    }
}

// Test notification badge and dropdown display
$badgeHtml = displayNotificationBadge();
$dropdownHtml = displayNotificationDropdownItems();
$unreadCount = countUnreadNotifications($userId);

// Page title
$pageTitle = "Test Notifications | GHAMECC Job Portal";

// Define base path for job portal
$basePath = "/jobs";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?></title>
    
    <?php include '../includes/favicon.php'; ?>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Prism.js for code highlighting -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/themes/prism.min.css" rel="stylesheet">
    <style>
        .test-card {
            margin-bottom: 20px;
        }
        .result-success {
            color: #198754;
        }
        .result-error {
            color: #dc3545;
        }
        .notification-preview {
            border: 1px solid #dee2e6;
            border-radius: 0.25rem;
            padding: 15px;
            margin-top: 20px;
        }
        .code-block {
            background-color: #f8f9fa;
            border-radius: 0.25rem;
            padding: 15px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <?php 
    if (file_exists(__DIR__ . '/includes/job-portal-navbar.php')) {
        include __DIR__ . '/includes/job-portal-navbar.php';
    } else {
        include 'includes/job-portal-navbar.php';
    }
    ?>
    
    <div class="container py-5">
        <h1 class="mb-4">Notification System Test</h1>
        
        <div class="row">
            <div class="col-md-8">
                <!-- Test Form -->
                <div class="card test-card">
                    <div class="card-header">
                        <h5 class="mb-0">Create Test Notifications</h5>
                    </div>
                    <div class="card-body">
                        <form method="post" action="test_notifications.php">
                            <input type="hidden" name="action" value="run_test">
                            
                            <div class="mb-3">
                                <label for="test_type" class="form-label">Notification Type</label>
                                <select class="form-select" id="test_type" name="test_type">
                                    <option value="all">All Types</option>
                                    <option value="general">General Notification</option>
                                    <option value="job_application">Job Application</option>
                                    <option value="rating">New Rating</option>
                                    <option value="review">New Review</option>
                                    <option value="application_status">Application Status Update</option>
                                    <option value="job_match">Job Match</option>
                                </select>
                            </div>
                            
                            <button type="submit" class="btn btn-primary">Create Test Notification(s)</button>
                        </form>
                    </div>
                </div>
                
                <!-- Test Results -->
                <?php if (!empty($results)): ?>
                <div class="card test-card">
                    <div class="card-header">
                        <h5 class="mb-0">Test Results</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Function</th>
                                        <th>Parameters</th>
                                        <th>Result</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($results as $result): ?>
                                    <tr>
                                        <td><code><?php echo htmlspecialchars($result['function']); ?></code></td>
                                        <td><small><pre><?php echo htmlspecialchars(print_r($result['params'], true)); ?></pre></small></td>
                                        <td>
                                            <?php if ($result['success']): ?>
                                                <span class="result-success"><i class="fas fa-check-circle"></i> Success</span>
                                                <?php if (isset($result['result']) && is_numeric($result['result'])): ?>
                                                    <br><small>ID: <?php echo $result['result']; ?></small>
                                                <?php endif; ?>
                                            <?php else: ?>
                                                <span class="result-error"><i class="fas fa-times-circle"></i> Failed</span>
                                                <?php if (isset($result['error'])): ?>
                                                    <br><small class="text-danger"><?php echo htmlspecialchars($result['error']); ?></small>
                                                <?php endif; ?>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <div class="mt-3">
                            <a href="notifications.php" class="btn btn-primary">
                                <i class="fas fa-bell me-2"></i> View Notifications
                            </a>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Notification Functions -->
                <div class="card test-card">
                    <div class="card-header">
                        <h5 class="mb-0">Available Notification Functions</h5>
                    </div>
                    <div class="card-body">
                        <div class="code-block">
                            <pre><code class="language-php">// Create a general notification
createNotification($userId, $type, $message, $link = '', $relatedId = null);

// Create a job application notification
createJobApplicationNotification($employerId, $jobId, $applicationId);

// Create a new rating notification
createNewRatingNotification($ratedUserId, $raterUserId, $ratingId, $ratingValue);

// Create a new review notification
createNewReviewNotification($reviewedUserId, $reviewerUserId, $reviewId, $reviewText);

// Create an application status update notification
createApplicationStatusNotification($applicantId, $jobId, $applicationId, $status);

// Create a job match notification
createJobMatchNotification($userId, $jobId, $jobTitle, $matchedSkills);</code></pre>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4">
                <!-- Notification Stats -->
                <div class="card test-card">
                    <div class="card-header">
                        <h5 class="mb-0">Notification Stats</h5>
                    </div>
                    <div class="card-body">
                        <p><strong>Unread Notifications:</strong> <?php echo $unreadCount; ?></p>
                        
                        <h6 class="mt-4">Notification Badge Preview:</h6>
                        <div class="notification-preview text-center">
                            <div class="position-relative d-inline-block">
                                <i class="fas fa-bell fa-2x"></i>
                                <?php echo $badgeHtml; ?>
                            </div>
                        </div>
                        
                        <h6 class="mt-4">Notification Dropdown Preview:</h6>
                        <div class="notification-preview">
                            <div class="dropdown-menu d-block position-static notification-dropdown" style="width: 100%; max-height: 300px; overflow-y: auto;">
                                <div class="d-flex justify-content-between align-items-center p-3 border-bottom">
                                    <h6 class="mb-0">Notifications</h6>
                                    <a href="notifications.php" class="text-decoration-none small">View All</a>
                                </div>
                                <?php echo $dropdownHtml; ?>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Quick Links -->
                <div class="card test-card">
                    <div class="card-header">
                        <h5 class="mb-0">Quick Links</h5>
                    </div>
                    <div class="card-body">
                        <ul class="list-group">
                            <li class="list-group-item">
                                <a href="notifications.php" class="text-decoration-none">
                                    <i class="fas fa-bell me-2"></i> View All Notifications
                                </a>
                            </li>
                            <li class="list-group-item">
                                <a href="ajax/mark_all_notifications_read.php" class="text-decoration-none mark-all-read">
                                    <i class="fas fa-check-double me-2"></i> Mark All as Read
                                </a>
                            </li>
                            <li class="list-group-item">
                                <form method="post" action="test_notifications.php" class="d-inline">
                                    <input type="hidden" name="action" value="run_test">
                                    <input type="hidden" name="test_type" value="general">
                                    <button type="submit" class="btn btn-link text-decoration-none p-0">
                                        <i class="fas fa-plus-circle me-2"></i> Create Test Notification
                                    </button>
                                </form>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Footer -->
    <footer class="bg-dark text-white py-4 mt-5">
        <div class="container">
            <div class="row">
                <div class="col-md-4 mb-4 mb-md-0">
                    <h5>GHAMECC Job Portal</h5>
                    <p class="text-muted">Connecting talent with opportunities within the GHAMECC community.</p>
                </div>
                <div class="col-md-4 mb-4 mb-md-0">
                    <h5>Quick Links</h5>
                    <ul class="list-unstyled">
                        <li><a href="index.php" class="text-decoration-none text-muted">Home</a></li>
                        <li><a href="job-listings.php" class="text-decoration-none text-muted">Job Listings</a></li>
                        <li><a href="talent-showcase.php" class="text-decoration-none text-muted">Talent Showcase</a></li>
                        <li><a href="categories.php" class="text-decoration-none text-muted">Categories</a></li>
                    </ul>
                </div>
                <div class="col-md-4">
                    <h5>Contact</h5>
                    <address class="text-muted">
                        <i class="fas fa-map-marker-alt me-2"></i> GHAMECC Headquarters<br>
                        <i class="fas fa-phone me-2"></i> (123) 456-7890<br>
                        <i class="fas fa-envelope me-2"></i> jobs@ghamecc.org
                    </address>
                </div>
            </div>
            <hr class="my-4 bg-secondary">
            <div class="text-center text-muted">
                <small>&copy; <?php echo date('Y'); ?> GHAMECC Job Portal. All rights reserved.</small>
            </div>
        </div>
    </footer>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- Prism.js for code highlighting -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-core.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/plugins/autoloader/prism-autoloader.min.js"></script>
    
    <!-- JavaScript for notification interactions -->
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Mark all notifications as read
        document.querySelector('.mark-all-read')?.addEventListener('click', function(e) {
            e.preventDefault();
            
            fetch(this.getAttribute('href'), {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('All notifications marked as read');
                    location.reload();
                }
            })
            .catch(error => console.error('Error:', error));
        });
    });
    </script>
</body>
</html>
