<?php
/**
 * Job Applications - View applications for a specific job
 * GHAMECC Job Portal
 */

require_once '../config/database.php';
require_once '../includes/auth.php';

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

$userId = $_SESSION['user_id'];
$jobId = isset($_GET['job_id']) ? (int)$_GET['job_id'] : 0;

if (!$jobId) {
    header('Location: my-jobs.php');
    exit();
}

// Get job details and verify ownership
$job = fetchRow("
    SELECT j.*, jc.name as category_name
    FROM jobs j
    LEFT JOIN job_categories jc ON j.category_id = jc.id
    WHERE j.id = ? AND j.posted_by_user_id = ?
", [$jobId, $userId]);

if (!$job) {
    header('Location: my-jobs.php');
    exit();
}

// Get applications for this job
$applications = fetchRows("
    SELECT ja.*, 
           jpu.full_name, jpu.email, jpu.phone, jpu.user_type,
           m.first_name, m.last_name, m.profession, m.contact_number as member_phone,
           (SELECT COUNT(*) FROM application_media am WHERE am.application_id = ja.id) as media_count
    FROM job_applications ja
    JOIN job_portal_users jpu ON ja.job_portal_user_id = jpu.id
    LEFT JOIN members m ON ja.member_id = m.id
    WHERE ja.job_id = ?
    ORDER BY ja.created_at DESC
", [$jobId]);

// Handle status updates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $applicationId = (int)$_POST['application_id'];
    $newStatus = $_POST['status'];
    
    if (in_array($newStatus, ['pending', 'shortlisted', 'rejected', 'selected'])) {
        $result = executeQuery("
            UPDATE job_applications 
            SET status = ? 
            WHERE id = ? AND job_id = ?
        ", [$newStatus, $applicationId, $jobId]);
        
        if ($result) {
            header("Location: job-applications.php?job_id=$jobId&updated=1");
            exit();
        }
    }
}

$pageTitle = "Applications for: " . $job['title'];
?>

<!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; ?> - GHAMECC Job Portal</title>
    
    <?php include '../includes/favicon.php'; ?>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .application-card {
            transition: transform 0.2s;
        }
        .application-card:hover {
            transform: translateY(-2px);
        }
        .status-badge {
            font-size: 0.8rem;
        }
        .status-pending { background-color: #ffc107; }
        .status-shortlisted { background-color: #17a2b8; }
        .status-rejected { background-color: #dc3545; }
        .status-selected { background-color: #28a745; }
        .job-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 30px;
        }
    </style>
</head>
<body>
    <?php include 'includes/job-portal-navbar.php'; ?>

    <div class="container mt-4">
        <!-- Success Message -->
        <?php if (isset($_GET['updated'])): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle me-2"></i>Application status updated successfully!
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Job Header -->
        <div class="job-header">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <h2><i class="fas fa-briefcase me-2"></i><?php echo htmlspecialchars($job['title']); ?></h2>
                    <p class="mb-2">
                        <i class="fas fa-building me-2"></i><?php echo htmlspecialchars($job['company_name']); ?>
                        <span class="ms-3"><i class="fas fa-map-marker-alt me-2"></i><?php echo htmlspecialchars($job['location']); ?></span>
                    </p>
                    <p class="mb-0">
                        <i class="fas fa-calendar me-2"></i>Deadline: <?php echo date('M j, Y', strtotime($job['deadline'])); ?>
                        <span class="ms-3"><i class="fas fa-users me-2"></i><?php echo count($applications); ?> Applications</span>
                    </p>
                </div>
                <div>
                    <a href="my-jobs.php" class="btn btn-light">
                        <i class="fas fa-arrow-left me-2"></i>Back to My Jobs
                    </a>
                </div>
            </div>
        </div>

        <!-- Applications -->
        <div class="row">
            <div class="col-12">
                <h3 class="mb-4">Applications (<?php echo count($applications); ?>)</h3>

                <?php if (empty($applications)): ?>
                    <div class="text-center py-5">
                        <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                        <h4 class="text-muted">No Applications Yet</h4>
                        <p class="text-muted">Applications will appear here when candidates apply for this job.</p>
                    </div>
                <?php else: ?>
                    <div class="row">
                        <?php foreach ($applications as $application): ?>
                            <div class="col-md-6 col-lg-4 mb-4">
                                <div class="card application-card h-100">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-start mb-3">
                                            <h5 class="card-title mb-0">
                                                <?php if ($application['member_id']): ?>
                                                    <?php echo htmlspecialchars($application['first_name'] . ' ' . $application['last_name']); ?>
                                                <?php else: ?>
                                                    <?php echo htmlspecialchars($application['full_name']); ?>
                                                <?php endif; ?>
                                            </h5>
                                            <span class="badge status-badge status-<?php echo $application['status']; ?>">
                                                <?php echo ucfirst($application['status']); ?>
                                            </span>
                                        </div>

                                        <div class="mb-2">
                                            <small class="text-muted">
                                                <i class="fas fa-envelope me-1"></i>
                                                <?php echo htmlspecialchars($application['email']); ?>
                                            </small>
                                        </div>

                                        <div class="mb-2">
                                            <small class="text-muted">
                                                <i class="fas fa-phone me-1"></i>
                                                <?php echo htmlspecialchars($application['phone'] ?: $application['member_phone']); ?>
                                            </small>
                                        </div>

                                        <?php if ($application['profession']): ?>
                                            <div class="mb-2">
                                                <small class="text-muted">
                                                    <i class="fas fa-briefcase me-1"></i>
                                                    <?php echo htmlspecialchars($application['profession']); ?>
                                                </small>
                                            </div>
                                        <?php endif; ?>

                                        <div class="mb-3">
                                            <small class="text-muted">
                                                <i class="fas fa-user-tag me-1"></i>
                                                <?php echo ucfirst($application['user_type']); ?>
                                                <span class="ms-2">
                                                    <i class="fas fa-calendar me-1"></i>
                                                    Applied: <?php echo date('M j, Y', strtotime($application['created_at'])); ?>
                                                </span>
                                            </small>
                                        </div>

                                        <?php if ($application['cover_letter']): ?>
                                            <div class="mb-3">
                                                <h6>Cover Letter:</h6>
                                                <div class="text-muted small" style="max-height: 100px; overflow-y: auto;">
                                                    <?php echo $application['cover_letter']; ?>
                                                </div>
                                            </div>
                                        <?php endif; ?>

                                        <?php if ($application['media_count'] > 0): ?>
                                            <div class="mb-3">
                                                <small class="text-info">
                                                    <i class="fas fa-paperclip me-1"></i>
                                                    <?php echo $application['media_count']; ?> attachment(s)
                                                </small>
                                            </div>
                                        <?php endif; ?>
                                    </div>

                                    <div class="card-footer bg-transparent">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div class="btn-group" role="group">
                                                <button type="button" class="btn btn-sm btn-outline-primary" 
                                                        onclick="viewApplication(<?php echo $application['id']; ?>)">
                                                    <i class="fas fa-eye me-1"></i>View
                                                </button>
                                                <?php if ($application['media_count'] > 0): ?>
                                                    <button type="button" class="btn btn-sm btn-outline-info"
                                                            onclick="viewAttachments(<?php echo $application['id']; ?>)">
                                                        <i class="fas fa-paperclip me-1"></i>Files
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                            <div class="dropdown">
                                                <button class="btn btn-sm btn-outline-secondary dropdown-toggle" 
                                                        type="button" data-bs-toggle="dropdown">
                                                    Status
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <li><a class="dropdown-item" href="#" 
                                                           onclick="updateStatus(<?php echo $application['id']; ?>, 'pending')">
                                                        <i class="fas fa-clock me-2 text-warning"></i>Pending
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="#" 
                                                           onclick="updateStatus(<?php echo $application['id']; ?>, 'shortlisted')">
                                                        <i class="fas fa-star me-2 text-info"></i>Shortlisted
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="#" 
                                                           onclick="updateStatus(<?php echo $application['id']; ?>, 'selected')">
                                                        <i class="fas fa-check me-2 text-success"></i>Selected
                                                    </a></li>
                                                    <li><hr class="dropdown-divider"></li>
                                                    <li><a class="dropdown-item" href="#" 
                                                           onclick="updateStatus(<?php echo $application['id']; ?>, 'rejected')">
                                                        <i class="fas fa-times me-2 text-danger"></i>Rejected
                                                    </a></li>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Summary Stats -->
                    <div class="row mt-4">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <h5>Application Summary</h5>
                                    <div class="row text-center">
                                        <?php
                                        $stats = ['pending' => 0, 'shortlisted' => 0, 'selected' => 0, 'rejected' => 0];
                                        foreach ($applications as $app) {
                                            $stats[$app['status']]++;
                                        }
                                        ?>
                                        <div class="col-3">
                                            <div class="text-warning">
                                                <i class="fas fa-clock fa-2x"></i>
                                                <h4><?php echo $stats['pending']; ?></h4>
                                                <small>Pending</small>
                                            </div>
                                        </div>
                                        <div class="col-3">
                                            <div class="text-info">
                                                <i class="fas fa-star fa-2x"></i>
                                                <h4><?php echo $stats['shortlisted']; ?></h4>
                                                <small>Shortlisted</small>
                                            </div>
                                        </div>
                                        <div class="col-3">
                                            <div class="text-success">
                                                <i class="fas fa-check fa-2x"></i>
                                                <h4><?php echo $stats['selected']; ?></h4>
                                                <small>Selected</small>
                                            </div>
                                        </div>
                                        <div class="col-3">
                                            <div class="text-danger">
                                                <i class="fas fa-times fa-2x"></i>
                                                <h4><?php echo $stats['rejected']; ?></h4>
                                                <small>Rejected</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Hidden form for status updates -->
    <form id="statusForm" method="POST" style="display: none;">
        <input type="hidden" name="action" value="update_status">
        <input type="hidden" name="application_id" id="statusApplicationId">
        <input type="hidden" name="status" id="statusValue">
    </form>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function updateStatus(applicationId, status) {
            if (confirm('Are you sure you want to update this application status to ' + status + '?')) {
                document.getElementById('statusApplicationId').value = applicationId;
                document.getElementById('statusValue').value = status;
                document.getElementById('statusForm').submit();
            }
        }

        function viewApplication(applicationId) {
            // Fetch application details via AJAX
            fetch('ajax/get_application_details.php?id=' + applicationId)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Populate modal with application details
                        document.getElementById('modalApplicantName').textContent = data.application.applicant_name;
                        document.getElementById('modalApplicantEmail').textContent = data.application.email;
                        document.getElementById('modalApplicantPhone').textContent = data.application.phone;
                        document.getElementById('modalApplicantType').textContent = data.application.user_type;
                        document.getElementById('modalApplicationDate').textContent = data.application.application_date;
                        document.getElementById('modalApplicationStatus').textContent = data.application.status;
                        document.getElementById('modalApplicationStatus').className = 'badge status-' + data.application.status;
                        
                        // Set cover letter
                        document.getElementById('modalCoverLetter').innerHTML = data.application.cover_letter || '<em class="text-muted">No cover letter provided</em>';
                        
                        // Set profession if available
                        const professionElement = document.getElementById('modalProfession');
                        if (data.application.profession) {
                            professionElement.textContent = data.application.profession;
                            professionElement.parentElement.style.display = 'block';
                        } else {
                            professionElement.parentElement.style.display = 'none';
                        }
                        
                        // Show modal
                        new bootstrap.Modal(document.getElementById('applicationDetailsModal')).show();
                    } else {
                        alert('Error loading application details: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error loading application details');
                });
        }

        function viewAttachments(applicationId) {
            // Fetch attachments via AJAX
            fetch('ajax/get_application_attachments.php?id=' + applicationId)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const attachmentsList = document.getElementById('attachmentsList');
                        attachmentsList.innerHTML = '';
                        
                        if (data.attachments.length === 0) {
                            attachmentsList.innerHTML = '<p class="text-muted">No attachments found</p>';
                        } else {
                            data.attachments.forEach(attachment => {
                                const attachmentItem = document.createElement('div');
                                attachmentItem.className = 'attachment-item mb-3 p-3 border rounded';
                                
                                const icon = getFileIcon(attachment.media_type);
                                const fileSize = formatFileSize(attachment.file_size);
                                
                                attachmentItem.innerHTML = `
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <i class="${icon} me-2"></i>
                                            <strong>${attachment.file_name}</strong>
                                            <br>
                                            <small class="text-muted">
                                                ${attachment.media_type} • ${fileSize} • 
                                                Uploaded: ${new Date(attachment.created_at).toLocaleDateString()}
                                            </small>
                                        </div>
                                        <div>
                                            <a href="../${attachment.file_path}" target="_blank" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-download me-1"></i>Download
                                            </a>
                                        </div>
                                    </div>
                                `;
                                
                                attachmentsList.appendChild(attachmentItem);
                            });
                        }
                        
                        // Show modal
                        new bootstrap.Modal(document.getElementById('attachmentsModal')).show();
                    } else {
                        alert('Error loading attachments: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error loading attachments');
                });
        }
        
        function getFileIcon(mediaType) {
            switch(mediaType) {
                case 'image': return 'fas fa-image text-success';
                case 'video': return 'fas fa-video text-info';
                case 'document': return 'fas fa-file-alt text-primary';
                case 'portfolio': return 'fas fa-briefcase text-warning';
                default: return 'fas fa-file text-secondary';
            }
        }
        
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
    </script>

    <!-- Application Details Modal -->
    <div class="modal fade" id="applicationDetailsModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Application Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h6>Applicant Information</h6>
                            <table class="table table-borderless table-sm">
                                <tr>
                                    <td><strong>Name:</strong></td>
                                    <td id="modalApplicantName">-</td>
                                </tr>
                                <tr>
                                    <td><strong>Email:</strong></td>
                                    <td id="modalApplicantEmail">-</td>
                                </tr>
                                <tr>
                                    <td><strong>Phone:</strong></td>
                                    <td id="modalApplicantPhone">-</td>
                                </tr>
                                <tr>
                                    <td><strong>Type:</strong></td>
                                    <td id="modalApplicantType">-</td>
                                </tr>
                                <tr style="display: none;">
                                    <td><strong>Profession:</strong></td>
                                    <td id="modalProfession">-</td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <h6>Application Information</h6>
                            <table class="table table-borderless table-sm">
                                <tr>
                                    <td><strong>Applied:</strong></td>
                                    <td id="modalApplicationDate">-</td>
                                </tr>
                                <tr>
                                    <td><strong>Status:</strong></td>
                                    <td><span id="modalApplicationStatus" class="badge">-</span></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    
                    <hr>
                    
                    <h6>Cover Letter</h6>
                    <div id="modalCoverLetter" class="border p-3 rounded bg-light" style="max-height: 300px; overflow-y: auto;">
                        Loading...
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Attachments Modal -->
    <div class="modal fade" id="attachmentsModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Application Attachments</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="attachmentsList">
                        Loading attachments...
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
