<?php
/**
 * Job Portal - Job Approval Page
 * GHAMECC Choir Management Platform
 * 
 * This page allows society secretaries 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'] = 'jobs/job-approval.php';
    header('Location: ../login.php');
    exit;
}

// Get current user information
$userId = $_SESSION['user_id'];
$userQuery = "SELECT u.*, r.role_key FROM users u JOIN roles r ON u.role_id = r.id WHERE u.id = ?";
$user = fetchRow($userQuery, [$userId]);

// Check if user has approval permissions (society secretary, choirmaster, or admin)
$canApprove = in_array($user['role_key'], ['admin', 'society_secretary', 'choirmaster']) || $user['role_id'] == 1;

if (!$canApprove) {
    header('Location: index.php?error=access_denied');
    exit;
}

// 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') ? 'approved' : 'rejected';
        $jobStatus = ($action === 'approve') ? 'open' : 'closed';
        
        $updateQuery = "UPDATE jobs SET 
                        approval_status = ?, 
                        status = ?,
                        approved_by = ?, 
                        approval_date = NOW(), 
                        approval_notes = ? 
                        WHERE id = ?";
        
        $result = executeQuery($updateQuery, [$status, $jobStatus, $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
$pendingJobsQuery = "SELECT j.*, jc.name as category_name, s.name as society_name, 
                     c.name as circuit_name, d.name as diocese_name,
                     m.first_name, m.last_name, u.full_name as poster_name
                     FROM jobs j
                     LEFT JOIN job_categories jc ON j.category_id = jc.id
                     LEFT JOIN societies s ON j.society_id = s.id
                     LEFT JOIN circuits c ON s.circuit_id = c.id
                     LEFT JOIN dioceses d ON c.diocese_id = d.id
                     LEFT JOIN members m ON j.member_id = m.id
                     LEFT JOIN users u ON m.id = u.member_id
                     WHERE j.approval_status = 'pending'";

// Filter based on user permissions
if ($user['role_key'] !== 'admin' && $user['role_id'] != 1) {
    if (!empty($user['society_id'])) {
        $pendingJobsQuery .= " AND j.society_id = " . (int)$user['society_id'];
    } elseif (!empty($user['circuit_id'])) {
        $pendingJobsQuery .= " AND s.circuit_id = " . (int)$user['circuit_id'];
    }
}

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

// 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);

$pageTitle = "Job Approval Dashboard";
?>
<!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">
    <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/job-portal-navbar.php'; ?>
    
    <div class="container py-5">
        <div class="row">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1><i class="fas fa-clipboard-check me-2"></i>Job Approval Dashboard</h1>
                    <div class="text-muted">
                        <small>Role: <?php echo htmlspecialchars($user['role_key']); ?></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']); ?></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']); ?></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['last_name'])); ?></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']); ?></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>
            </div>
        </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>
