<?php
/**
 * Job Approval Page - Main GHAMECC Portal
 * GHAMECC Choir Management Platform
 * 
 * This page allows society secretaries, choirmasters, and administrators to approve/reject job posts.
 */

// Include database connection and functions
require_once 'config/database.php';
require_once 'includes/functions.php';
require_once 'includes/auth.php';

// Check if user is logged in
if (!isLoggedIn()) {
    $_SESSION['redirect_after_login'] = 'ghameccapp/job-approval.php';
    header('Location: login.php');
    exit;
}

// Check if user has approval permissions
if (!hasRole(['admin', 'society_secretary', 'choirmaster', 'diocesan_secretary', 'diocese_chairman'])) {
    header('Location: index.php?error=access_denied');
    exit;
}

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

// Handle approval/rejection actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $jobId = (int)$_POST['job_id'];
    $action = $_POST['action'];
    $notes = isset($_POST['notes']) ? escapeString($_POST['notes']) : '';
    
    if (in_array($action, ['approve', 'reject'])) {
        $status = ($action === 'approve') ? 'open' : 'closed';
        $approvalStatus = ($action === 'approve') ? 'approved' : 'rejected';
        
        $updateQuery = "UPDATE jobs SET 
                        status = ?,
                        approval_status = ?, 
                        approved_by = ?, 
                        approval_date = NOW(), 
                        approval_notes = ? 
                        WHERE id = ?";
        
        $result = executeQuery($updateQuery, [$status, $approvalStatus, $userId, $notes, $jobId]);
        
        if ($result) {
            $message = "Job has been " . ($action === 'approve' ? 'approved' : 'rejected') . " successfully.";
            $messageType = 'success';
        } else {
            $message = "Failed to update job status. Please try again.";
            $messageType = 'error';
        }
    }
}

// Get pending jobs for approval - simplified query to avoid JOIN issues
$pendingJobsQuery = "SELECT j.id, j.title, j.description, j.requirements, j.location, 
                     j.salary_range, j.company_name, j.contact_email, j.contact_phone,
                     j.status, j.deadline, j.member_id, j.society_id, j.category_id,
                     j.approval_status, j.approved_by, j.approval_date, j.approval_notes,
                     j.created_at, j.updated_at
                     FROM jobs j
                     WHERE j.approval_status = 'pending'";

// Filter based on user permissions
if (!hasRole(['admin', 'diocesan_secretary', 'diocese_chairman'])) {
    if (isset($_SESSION['society_id']) && !empty($_SESSION['society_id'])) {
        $pendingJobsQuery .= " AND j.society_id = " . (int)$_SESSION['society_id'];
    } elseif (isset($_SESSION['circuit_id']) && !empty($_SESSION['circuit_id'])) {
        // For circuit filtering, we need to check societies in that circuit
        $pendingJobsQuery .= " AND j.society_id IN (SELECT id FROM societies WHERE circuit_id = " . (int)$_SESSION['circuit_id'] . ")";
    }
}

$pendingJobsQuery .= " ORDER BY j.created_at DESC";
$pendingJobs = fetchRows($pendingJobsQuery);

// Now get additional data for each job separately to avoid JOIN issues
foreach ($pendingJobs as &$job) {
    // Get category name
    if ($job['category_id']) {
        $category = fetchRow("SELECT name FROM job_categories WHERE id = ?", [$job['category_id']]);
        $job['category_name'] = $category ? $category['name'] : 'Uncategorized';
    } else {
        $job['category_name'] = 'Uncategorized';
    }
    
    // Get society info
    if ($job['society_id']) {
        $society = fetchRow("SELECT s.name as society_name, c.name as circuit_name, d.name as diocese_name 
                            FROM societies s 
                            LEFT JOIN circuits c ON s.circuit_id = c.id 
                            LEFT JOIN dioceses d ON c.diocese_id = d.id 
                            WHERE s.id = ?", [$job['society_id']]);
        if ($society) {
            $job['society_name'] = $society['society_name'];
            $job['circuit_name'] = $society['circuit_name'];
            $job['diocese_name'] = $society['diocese_name'];
        } else {
            $job['society_name'] = 'Unknown Society';
            $job['circuit_name'] = 'Unknown Circuit';
            $job['diocese_name'] = 'Unknown Diocese';
        }
    } else {
        $job['society_name'] = 'No Society';
        $job['circuit_name'] = 'No Circuit';
        $job['diocese_name'] = 'No Diocese';
    }
    
    // Get member info
    if ($job['member_id']) {
        $member = fetchRow("SELECT first_name, surname FROM members WHERE id = ?", [$job['member_id']]);
        if ($member) {
            $job['first_name'] = $member['first_name'];
            $job['surname'] = $member['surname'];
        } else {
            $job['first_name'] = '';
            $job['surname'] = '';
        }
        
        // Try to get job portal user name
        $jobPortalUser = fetchRow("SELECT full_name FROM job_portal_users WHERE member_id = ?", [$job['member_id']]);
        $job['poster_name'] = $jobPortalUser ? $jobPortalUser['full_name'] : trim($job['first_name'] . ' ' . $job['surname']);
    } else {
        $job['first_name'] = '';
        $job['surname'] = '';
        $job['poster_name'] = 'Unknown User';
    }
}

// Get approved/rejected jobs for history
$historyQuery = str_replace("WHERE j.approval_status = 'pending'", "WHERE j.approval_status IN ('approved', 'rejected')", $pendingJobsQuery);
$historyQuery = str_replace("ORDER BY j.created_at DESC", "ORDER BY j.approval_date DESC LIMIT 20", $historyQuery);
$jobHistory = fetchRows($historyQuery);

// Now get additional data for each job separately to avoid JOIN issues
foreach ($jobHistory as &$job) {
    // Get category name
    if ($job['category_id']) {
        $category = fetchRow("SELECT name FROM job_categories WHERE id = ?", [$job['category_id']]);
        $job['category_name'] = $category ? $category['name'] : 'Uncategorized';
    } else {
        $job['category_name'] = 'Uncategorized';
    }
    
    // Get society info
    if ($job['society_id']) {
        $society = fetchRow("SELECT s.name as society_name, c.name as circuit_name, d.name as diocese_name 
                            FROM societies s 
                            LEFT JOIN circuits c ON s.circuit_id = c.id 
                            LEFT JOIN dioceses d ON c.diocese_id = d.id 
                            WHERE s.id = ?", [$job['society_id']]);
        if ($society) {
            $job['society_name'] = $society['society_name'];
            $job['circuit_name'] = $society['circuit_name'];
            $job['diocese_name'] = $society['diocese_name'];
        } else {
            $job['society_name'] = 'Unknown Society';
            $job['circuit_name'] = 'Unknown Circuit';
            $job['diocese_name'] = 'Unknown Diocese';
        }
    } else {
        $job['society_name'] = 'No Society';
        $job['circuit_name'] = 'No Circuit';
        $job['diocese_name'] = 'No Diocese';
    }
    
    // Get member info
    if ($job['member_id']) {
        $member = fetchRow("SELECT first_name, surname FROM members WHERE id = ?", [$job['member_id']]);
        if ($member) {
            $job['first_name'] = $member['first_name'];
            $job['surname'] = $member['surname'];
        } else {
            $job['first_name'] = '';
            $job['surname'] = '';
        }
        
        // Try to get job portal user name
        $jobPortalUser = fetchRow("SELECT full_name FROM job_portal_users WHERE member_id = ?", [$job['member_id']]);
        $job['poster_name'] = $jobPortalUser ? $jobPortalUser['full_name'] : trim($job['first_name'] . ' ' . $job['surname']);
    } else {
        $job['first_name'] = '';
        $job['surname'] = '';
        $job['poster_name'] = 'Unknown User';
    }
}

$pageTitle = "Job Approval Dashboard";
$basePath = '.';
?>
<!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</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">
    <style>
        .job-card {
            transition: transform 0.2s;
        }
        .job-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .status-badge {
            font-size: 0.8rem;
        }
        .approval-form {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-top: 15px;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <?php include 'includes/navbar.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <?php include 'includes/sidebar.php'; ?>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1><i class="fas fa-clipboard-check me-2"></i>Job Approval Dashboard</h1>
                    <div class="text-muted">
                        <small>Role: <?php echo htmlspecialchars($_SESSION['role'] ?? 'User'); ?></small>
                    </div>
                </div>
                
                <?php if (isset($message)): ?>
                    <div class="alert alert-<?php echo $messageType === 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show">
                        <i class="fas fa-<?php echo $messageType === 'success' ? 'check-circle' : 'exclamation-triangle'; ?> me-2"></i>
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                
                <!-- Pending Jobs Tab -->
                <ul class="nav nav-tabs" id="approvalTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="pending-tab" data-bs-toggle="tab" data-bs-target="#pending" type="button" role="tab">
                            <i class="fas fa-clock me-1"></i>Pending Approval 
                            <span class="badge bg-warning text-dark ms-1"><?php echo count($pendingJobs); ?></span>
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="history-tab" data-bs-toggle="tab" data-bs-target="#history" type="button" role="tab">
                            <i class="fas fa-history me-1"></i>Approval History
                        </button>
                    </li>
                </ul>
                
                <div class="tab-content" id="approvalTabsContent">
                    <!-- Pending Jobs -->
                    <div class="tab-pane fade show active" id="pending" role="tabpanel">
                        <div class="mt-4">
                            <?php if (empty($pendingJobs)): ?>
                                <div class="text-center py-5">
                                    <i class="fas fa-clipboard-check fa-4x text-muted mb-3"></i>
                                    <h4 class="text-muted">No Pending Jobs</h4>
                                    <p class="text-muted">All job posts have been reviewed.</p>
                                </div>
                            <?php else: ?>
                                <?php foreach ($pendingJobs as $job): ?>
                                    <div class="card job-card mb-4">
                                        <div class="card-header d-flex justify-content-between align-items-center">
                                            <h5 class="mb-0"><?php echo htmlspecialchars($job['title']); ?></h5>
                                            <span class="badge bg-warning status-badge">Pending Approval</span>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-md-8">
                                                    <p class="card-text"><?php echo nl2br(htmlspecialchars(substr($job['description'], 0, 300))); ?>...</p>
                                                    
                                                    <div class="row mb-3">
                                                        <div class="col-sm-6">
                                                            <small class="text-muted"><i class="fas fa-building me-1"></i> <?php echo htmlspecialchars($job['company_name']); ?></small>
                                                        </div>
                                                        <div class="col-sm-6">
                                                            <small class="text-muted"><i class="fas fa-map-marker-alt me-1"></i> <?php echo htmlspecialchars($job['location']); ?></small>
                                                        </div>
                                                        <div class="col-sm-6">
                                                            <small class="text-muted"><i class="fas fa-tag me-1"></i> <?php echo htmlspecialchars($job['category_name'] ?? 'N/A'); ?></small>
                                                        </div>
                                                        <div class="col-sm-6">
                                                            <small class="text-muted"><i class="fas fa-calendar me-1"></i> Deadline: <?php echo date('M d, Y', strtotime($job['deadline'])); ?></small>
                                                        </div>
                                                        <div class="col-sm-6">
                                                            <small class="text-muted"><i class="fas fa-church me-1"></i> <?php echo htmlspecialchars($job['society_name'] ?? 'N/A'); ?></small>
                                                        </div>
                                                        <div class="col-sm-6">
                                                            <small class="text-muted"><i class="fas fa-user me-1"></i> Posted by: <?php echo htmlspecialchars($job['poster_name'] ?? ($job['first_name'] . ' ' . $job['surname'])); ?></small>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="approval-form">
                                                        <form method="POST" class="approval-form-inner">
                                                            <input type="hidden" name="job_id" value="<?php echo $job['id']; ?>">
                                                            
                                                            <div class="mb-3">
                                                                <label for="notes_<?php echo $job['id']; ?>" class="form-label">Approval Notes</label>
                                                                <textarea class="form-control" id="notes_<?php echo $job['id']; ?>" name="notes" rows="3" placeholder="Optional notes about your decision..."></textarea>
                                                            </div>
                                                            
                                                            <div class="d-grid gap-2">
                                                                <button type="submit" name="action" value="approve" class="btn btn-success">
                                                                    <i class="fas fa-check me-1"></i> Approve Job
                                                                </button>
                                                                <button type="submit" name="action" value="reject" class="btn btn-danger">
                                                                    <i class="fas fa-times me-1"></i> Reject Job
                                                                </button>
                                                            </div>
                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <!-- Approval History -->
                    <div class="tab-pane fade" id="history" role="tabpanel">
                        <div class="mt-4">
                            <?php if (empty($jobHistory)): ?>
                                <div class="text-center py-5">
                                    <i class="fas fa-history fa-4x text-muted mb-3"></i>
                                    <h4 class="text-muted">No Approval History</h4>
                                    <p class="text-muted">No jobs have been approved or rejected yet.</p>
                                </div>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>Job Title</th>
                                                <th>Society</th>
                                                <th>Status</th>
                                                <th>Approval Date</th>
                                                <th>Notes</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($jobHistory as $job): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($job['title']); ?></td>
                                                    <td><?php echo htmlspecialchars($job['society_name'] ?? 'N/A'); ?></td>
                                                    <td>
                                                        <span class="badge bg-<?php echo $job['approval_status'] === 'approved' ? 'success' : 'danger'; ?>">
                                                            <?php echo ucfirst($job['approval_status']); ?>
                                                        </span>
                                                    </td>
                                                    <td><?php echo $job['approval_date'] ? date('M d, Y H:i', strtotime($job['approval_date'])) : '-'; ?></td>
                                                    <td><?php echo htmlspecialchars($job['approval_notes'] ?? '-'); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Confirmation for approval actions
        document.querySelectorAll('.approval-form-inner').forEach(form => {
            form.addEventListener('submit', function(e) {
                const action = e.submitter.value;
                const jobTitle = this.closest('.card').querySelector('h5').textContent;
                const message = `Are you sure you want to ${action} the job "${jobTitle}"?`;
                
                if (!confirm(message)) {
                    e.preventDefault();
                }
            });
        });
    </script>
</body>
</html>
