<?php
/**
 * Enterprise HRM ERP System - Leave Approvals Page
 * Dedicated page for Admin/HR to approve/reject leave applications
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();

// Only Admin and HR can access this page
if (!isSuperAdmin() && !isHRAdmin()) {
    redirect(BASE_URL . '/dashboard.php', 'You do not have permission to access this page.', 'error');
}

$pageTitle = 'Leave Approvals';
$currentModule = 'leave_approvals';

$siteId = getCurrentSiteId();

// Get filter parameters
$filterStatus = isset($_GET['status']) ? trim($_GET['status']) : 'pending';
$filterSearch = isset($_GET['search']) ? trim($_GET['search']) : '';

// Get pending leave applications count
try {
    $db = getDB();
    
    // Count pending leaves
    if (isSuperAdmin()) {
        $stmt = $db->prepare("SELECT COUNT(*) FROM leave_applications WHERE site_id = ? AND application_status = 'pending'");
        $stmt->execute([$siteId]);
    } else {
        $userId = getCurrentUserId();
        $stmt = $db->prepare("
            SELECT COUNT(*) FROM leave_applications la
            INNER JOIN employees e ON la.employee_id = e.employee_id
            WHERE la.site_id = ? AND la.application_status = 'pending'
            AND e.created_by = ?
        ");
        $stmt->execute([$siteId, $userId]);
    }
    $pendingCount = $stmt->fetchColumn();
    
    // Get leave applications based on filter
    $whereConditions = ["la.site_id = ?"];
    $params = [$siteId];
    
    if ($filterStatus && $filterStatus !== 'all') {
        $whereConditions[] = "la.application_status = ?";
        $params[] = $filterStatus;
    }
    
    if ($filterSearch) {
        $whereConditions[] = "(e.employee_code LIKE ? OR e.first_name LIKE ? OR e.last_name LIKE ? OR lt.leave_type_name LIKE ?)";
        $searchParam = "%{$filterSearch}%";
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
    }
    
    // HR Admin can only see their employees
    if (!isSuperAdmin()) {
        $userId = getCurrentUserId();
        $whereConditions[] = "e.created_by = ?";
        $params[] = $userId;
    }
    
    $whereSQL = implode(' AND ', $whereConditions);
    
    $stmt = $db->prepare("
        SELECT la.*, e.employee_code,
               CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) as employee_name,
               lt.leave_type_name,
               u.full_name as approved_by_name
        FROM leave_applications la
        INNER JOIN employees e ON la.employee_id = e.employee_id
        LEFT JOIN leave_types lt ON la.leave_type_id = lt.leave_type_id
        LEFT JOIN users u ON la.approved_by = u.user_id
        WHERE {$whereSQL}
        ORDER BY 
            CASE la.application_status 
                WHEN 'pending' THEN 1 
                WHEN 'approved' THEN 2 
                WHEN 'rejected' THEN 3 
                ELSE 4 
            END,
            la.applied_at DESC
    ");
    $stmt->execute($params);
    $leaveApplications = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Error loading leave approvals: " . $e->getMessage());
    $pendingCount = 0;
    $leaveApplications = [];
}

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

<style>
/* Page Header */
.approval-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
    flex-wrap: wrap;
    gap: 15px;
}

.approval-title {
    display: flex;
    align-items: center;
    gap: 15px;
}

.approval-title h2 {
    margin: 0;
    color: #1e40af;
}

.pending-badge {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
    color: white;
    padding: 8px 16px;
    border-radius: 25px;
    font-size: 14px;
    font-weight: 700;
    animation: pulse-glow 1.5s ease-in-out infinite;
}

@keyframes pulse-glow {
    0%, 100% { box-shadow: 0 0 10px rgba(238, 90, 36, 0.4); transform: scale(1); }
    50% { box-shadow: 0 0 25px rgba(238, 90, 36, 0.8); transform: scale(1.05); }
}

/* Filters */
.approval-filters {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
    align-items: center;
    padding: 20px;
    background: #f8fafc;
    border-radius: 10px;
    margin-bottom: 25px;
}

.filter-group {
    display: flex;
    flex-direction: column;
    gap: 5px;
}

.filter-group label {
    font-size: 12px;
    font-weight: 600;
    color: #64748b;
    text-transform: uppercase;
}

.filter-group select,
.filter-group input {
    padding: 10px 14px;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    font-size: 14px;
    min-width: 180px;
}

.filter-group select:focus,
.filter-group input:focus {
    outline: none;
    border-color: #1e40af;
    box-shadow: 0 0 0 3px rgba(30, 64, 175, 0.1);
}

.filter-buttons {
    display: flex;
    gap: 10px;
    margin-left: auto;
}

/* Status Tabs */
.status-tabs {
    display: flex;
    gap: 5px;
    margin-bottom: 20px;
    background: #f1f5f9;
    padding: 5px;
    border-radius: 10px;
    width: fit-content;
}

.status-tab {
    padding: 10px 20px;
    border-radius: 8px;
    text-decoration: none;
    font-weight: 600;
    font-size: 14px;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    gap: 8px;
}

.status-tab.active {
    background: white;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.status-tab.pending {
    color: #ea580c;
}

.status-tab.pending.active {
    background: linear-gradient(135deg, #fff7ed 0%, #ffedd5 100%);
}

.status-tab.approved {
    color: #16a34a;
}

.status-tab.approved.active {
    background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
}

.status-tab.rejected {
    color: #dc2626;
}

.status-tab.rejected.active {
    background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
}

.status-tab.all {
    color: #475569;
}

.status-tab.all.active {
    background: white;
}

.tab-count {
    background: currentColor;
    color: white;
    padding: 2px 8px;
    border-radius: 10px;
    font-size: 11px;
}

.status-tab.pending .tab-count {
    background: #ea580c;
    animation: blink-badge 1s ease-in-out infinite;
}

@keyframes blink-badge {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.5; }
}

/* Approval Cards */
.approval-cards {
    display: grid;
    gap: 20px;
}

.approval-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    overflow: hidden;
    transition: all 0.2s;
    border-left: 4px solid #e2e8f0;
}

.approval-card:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.12);
    transform: translateY(-2px);
}

.approval-card.status-pending {
    border-left-color: #f97316;
    animation: card-highlight 2s ease-in-out infinite;
}

@keyframes card-highlight {
    0%, 100% { background: white; }
    50% { background: #fffbf5; }
}

.approval-card.status-approved {
    border-left-color: #22c55e;
}

.approval-card.status-rejected {
    border-left-color: #ef4444;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 20px;
    background: #f8fafc;
    border-bottom: 1px solid #e2e8f0;
}

.employee-info h4 {
    margin: 0 0 5px 0;
    color: #1e293b;
    font-size: 16px;
}

.employee-info .emp-code {
    color: #64748b;
    font-size: 13px;
}

.status-badge {
    padding: 6px 14px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
}

.status-badge.pending {
    background: #fff7ed;
    color: #ea580c;
    animation: pulse-status 1.5s ease-in-out infinite;
}

@keyframes pulse-status {
    0%, 100% { transform: scale(1); }
    50% { transform: scale(1.05); }
}

.status-badge.approved {
    background: #f0fdf4;
    color: #16a34a;
}

.status-badge.rejected {
    background: #fef2f2;
    color: #dc2626;
}

.card-body {
    padding: 20px;
}

.leave-details {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 15px;
    margin-bottom: 15px;
}

.detail-item {
    display: flex;
    flex-direction: column;
    gap: 3px;
}

.detail-item label {
    font-size: 11px;
    color: #64748b;
    text-transform: uppercase;
    font-weight: 600;
}

.detail-item span {
    font-size: 14px;
    color: #1e293b;
    font-weight: 500;
}

.leave-reason {
    background: #f8fafc;
    padding: 12px;
    border-radius: 8px;
    margin-top: 15px;
}

.leave-reason label {
    font-size: 11px;
    color: #64748b;
    text-transform: uppercase;
    font-weight: 600;
    display: block;
    margin-bottom: 5px;
}

.leave-reason p {
    margin: 0;
    color: #475569;
    font-size: 14px;
}

.card-actions {
    display: flex;
    gap: 10px;
    padding: 15px 20px;
    background: #f8fafc;
    border-top: 1px solid #e2e8f0;
}

.btn-approve {
    background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 8px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    gap: 6px;
}

.btn-approve:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(34, 197, 94, 0.4);
}

.btn-reject {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 8px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    gap: 6px;
}

.btn-reject:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
}

.btn-view {
    background: #e2e8f0;
    color: #475569;
    border: none;
    padding: 10px 20px;
    border-radius: 8px;
    font-weight: 600;
    cursor: pointer;
    text-decoration: none;
    transition: all 0.2s;
}

.btn-view:hover {
    background: #cbd5e1;
}

.approved-info {
    display: flex;
    gap: 20px;
    padding: 15px 20px;
    background: #f0fdf4;
    border-top: 1px solid #dcfce7;
    font-size: 13px;
    color: #166534;
}

.rejected-info {
    padding: 15px 20px;
    background: #fef2f2;
    border-top: 1px solid #fee2e2;
    font-size: 13px;
    color: #991b1b;
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #64748b;
}

.empty-state .icon {
    font-size: 64px;
    margin-bottom: 20px;
    opacity: 0.5;
}

.empty-state h3 {
    margin: 0 0 10px 0;
    color: #475569;
}

.empty-state p {
    margin: 0;
}

/* Rejection Modal */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

.modal-content {
    background: white;
    border-radius: 12px;
    width: 100%;
    max-width: 500px;
    margin: 20px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #e2e8f0;
}

.modal-header h3 {
    margin: 0;
    color: #1e293b;
}

.modal-close {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #94a3b8;
    padding: 0;
}

.modal-close:hover {
    color: #475569;
}

.modal-body {
    padding: 20px;
}

.modal-body textarea {
    width: 100%;
    padding: 12px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    font-size: 14px;
    resize: vertical;
    min-height: 100px;
}

.modal-body textarea:focus {
    outline: none;
    border-color: #1e40af;
    box-shadow: 0 0 0 3px rgba(30, 64, 175, 0.1);
}

.modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding: 20px;
    border-top: 1px solid #e2e8f0;
}

/* Responsive */
@media (max-width: 768px) {
    .approval-header {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .approval-filters {
        flex-direction: column;
        align-items: stretch;
    }
    
    .filter-group select,
    .filter-group input {
        width: 100%;
    }
    
    .filter-buttons {
        margin-left: 0;
        width: 100%;
    }
    
    .filter-buttons .btn {
        flex: 1;
    }
    
    .status-tabs {
        width: 100%;
        overflow-x: auto;
    }
    
    .leave-details {
        grid-template-columns: 1fr 1fr;
    }
    
    .card-actions {
        flex-direction: column;
    }
    
    .card-actions .btn {
        width: 100%;
        justify-content: center;
    }
}
</style>

<div class="card">
    <!-- Page Header -->
    <div class="approval-header">
        <div class="approval-title">
            <h2>🔔 Leave Approvals</h2>
            <?php if ($pendingCount > 0): ?>
            <span class="pending-badge">
                <?php echo $pendingCount; ?> Pending
            </span>
            <?php endif; ?>
        </div>
        <a href="<?php echo BASE_URL; ?>/modules/leave/list.php" class="btn btn-secondary">
            ← Back to Leave List
        </a>
    </div>
    
    <!-- Status Tabs -->
    <div class="status-tabs">
        <a href="?status=pending" class="status-tab pending <?php echo $filterStatus === 'pending' ? 'active' : ''; ?>">
            Pending
            <?php if ($pendingCount > 0): ?>
            <span class="tab-count"><?php echo $pendingCount; ?></span>
            <?php endif; ?>
        </a>
        <a href="?status=approved" class="status-tab approved <?php echo $filterStatus === 'approved' ? 'active' : ''; ?>">
            Approved
        </a>
        <a href="?status=rejected" class="status-tab rejected <?php echo $filterStatus === 'rejected' ? 'active' : ''; ?>">
            Rejected
        </a>
        <a href="?status=all" class="status-tab all <?php echo $filterStatus === 'all' ? 'active' : ''; ?>">
            All
        </a>
    </div>
    
    <!-- Filters -->
    <form method="GET" class="approval-filters">
        <input type="hidden" name="status" value="<?php echo htmlspecialchars($filterStatus); ?>">
        <div class="filter-group">
            <label>Search</label>
            <input type="text" name="search" placeholder="Employee name, code, or leave type..." 
                   value="<?php echo htmlspecialchars($filterSearch); ?>">
        </div>
        <div class="filter-buttons">
            <button type="submit" class="btn btn-primary">🔍 Search</button>
            <a href="?status=<?php echo htmlspecialchars($filterStatus); ?>" class="btn btn-secondary">Clear</a>
        </div>
    </form>
    
    <!-- Leave Applications -->
    <div class="approval-cards">
        <?php if (empty($leaveApplications)): ?>
        <div class="empty-state">
            <div class="icon">📋</div>
            <h3>No Leave Applications Found</h3>
            <p>
                <?php if ($filterStatus === 'pending'): ?>
                There are no pending leave applications to approve.
                <?php else: ?>
                No leave applications match your filters.
                <?php endif; ?>
            </p>
        </div>
        <?php else: ?>
        
        <?php foreach ($leaveApplications as $leave): ?>
        <div class="approval-card status-<?php echo htmlspecialchars($leave['application_status']); ?>">
            <div class="card-header">
                <div class="employee-info">
                    <h4><?php echo htmlspecialchars($leave['employee_name']); ?></h4>
                    <span class="emp-code"><?php echo htmlspecialchars($leave['employee_code']); ?></span>
                </div>
                <span class="status-badge <?php echo htmlspecialchars($leave['application_status']); ?>">
                    <?php echo ucfirst($leave['application_status']); ?>
                </span>
            </div>
            
            <div class="card-body">
                <div class="leave-details">
                    <div class="detail-item">
                        <label>Leave Type</label>
                        <span><?php echo htmlspecialchars($leave['leave_type_name'] ?? 'N/A'); ?></span>
                    </div>
                    <div class="detail-item">
                        <label>Start Date</label>
                        <span><?php echo formatDate($leave['start_date']); ?></span>
                    </div>
                    <div class="detail-item">
                        <label>End Date</label>
                        <span><?php echo formatDate($leave['end_date']); ?></span>
                    </div>
                    <div class="detail-item">
                        <label>Total Days</label>
                        <span><strong><?php echo number_format($leave['total_days'], 1); ?></strong> days</span>
                    </div>
                    <div class="detail-item">
                        <label>Applied On</label>
                        <span><?php echo formatDateTime($leave['applied_at']); ?></span>
                    </div>
                </div>
                
                <?php if (!empty($leave['reason'])): ?>
                <div class="leave-reason">
                    <label>Reason</label>
                    <p><?php echo nl2br(htmlspecialchars($leave['reason'])); ?></p>
                </div>
                <?php endif; ?>
            </div>
            
            <?php if ($leave['application_status'] === 'pending'): ?>
            <div class="card-actions">
                <button type="button" class="btn-approve" 
                        onclick="approveLeave(<?php echo $leave['leave_application_id']; ?>, '<?php echo htmlspecialchars(addslashes($leave['employee_name'])); ?>')">
                    ✓ Approve
                </button>
                <button type="button" class="btn-reject" 
                        onclick="showRejectModal(<?php echo $leave['leave_application_id']; ?>, '<?php echo htmlspecialchars(addslashes($leave['employee_name'])); ?>')">
                    ✕ Reject
                </button>
                <a href="<?php echo BASE_URL; ?>/modules/leave/view.php?id=<?php echo $leave['leave_application_id']; ?>" 
                   class="btn-view">View Details</a>
            </div>
            <?php elseif ($leave['application_status'] === 'approved'): ?>
            <div class="approved-info">
                <span><strong>Approved By:</strong> <?php echo htmlspecialchars($leave['approved_by_name'] ?? 'N/A'); ?></span>
                <span><strong>Approved On:</strong> <?php echo formatDateTime($leave['approved_at']); ?></span>
            </div>
            <?php elseif ($leave['application_status'] === 'rejected'): ?>
            <div class="rejected-info">
                <strong>Rejected By:</strong> <?php echo htmlspecialchars($leave['approved_by_name'] ?? 'N/A'); ?><br>
                <?php if (!empty($leave['rejection_reason'])): ?>
                <strong>Reason:</strong> <?php echo htmlspecialchars($leave['rejection_reason']); ?>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
        
        <?php endif; ?>
    </div>
</div>

<!-- Rejection Modal -->
<div id="rejectModal" class="modal-overlay" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Reject Leave Application</h3>
            <button type="button" class="modal-close" onclick="closeRejectModal()">&times;</button>
        </div>
        <div class="modal-body">
            <p id="rejectEmployeeName"></p>
            <textarea id="rejectionReason" placeholder="Enter reason for rejection..." rows="4"></textarea>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" onclick="closeRejectModal()">Cancel</button>
            <button type="button" class="btn-reject" onclick="submitReject()">Reject Leave</button>
        </div>
    </div>
</div>

<script>
let currentRejectLeaveId = null;

// Approve Leave
function approveLeave(leaveId, employeeName) {
    if (confirm('Are you sure you want to APPROVE the leave application for ' + employeeName + '?')) {
        processLeaveAction(leaveId, 'approve');
    }
}

// Show Reject Modal
function showRejectModal(leaveId, employeeName) {
    currentRejectLeaveId = leaveId;
    document.getElementById('rejectEmployeeName').innerHTML = 
        'Rejecting leave application for <strong>' + employeeName + '</strong>:';
    document.getElementById('rejectionReason').value = '';
    document.getElementById('rejectModal').style.display = 'flex';
    document.getElementById('rejectionReason').focus();
}

// Close Reject Modal
function closeRejectModal() {
    document.getElementById('rejectModal').style.display = 'none';
    currentRejectLeaveId = null;
}

// Submit Reject
function submitReject() {
    const reason = document.getElementById('rejectionReason').value.trim();
    if (!reason) {
        alert('Please enter a rejection reason.');
        document.getElementById('rejectionReason').focus();
        return;
    }
    processLeaveAction(currentRejectLeaveId, 'reject', reason);
}

// Process Leave Action
function processLeaveAction(leaveId, action, reason = '') {
    // Show loading
    const buttons = document.querySelectorAll('.btn-approve, .btn-reject');
    buttons.forEach(btn => {
        btn.disabled = true;
        btn.style.opacity = '0.5';
    });
    
    fetch('<?php echo BASE_URL; ?>/api/leave_action.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            leave_id: leaveId,
            action: action,
            reason: reason
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            closeRejectModal();
            window.location.reload();
        } else {
            alert('Error: ' + data.message);
            buttons.forEach(btn => {
                btn.disabled = false;
                btn.style.opacity = '1';
            });
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred. Please try again.');
        buttons.forEach(btn => {
            btn.disabled = false;
            btn.style.opacity = '1';
        });
    });
}

// Close modal on escape
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') closeRejectModal();
});

// Close modal on outside click
document.getElementById('rejectModal').addEventListener('click', function(e) {
    if (e.target === this) closeRejectModal();
});
</script>

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

