<?php
/**
 * Enterprise HRM ERP System - View Leave Application
 */

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

$pageTitle = 'View Leave Application';
$currentModule = 'leave';

$siteId = getCurrentSiteId();
$leaveId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($leaveId <= 0) {
    redirect(BASE_URL . '/modules/leave/list.php', 'Invalid leave application ID.', 'error');
}

try {
    $db = getDB();
    $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 la.leave_application_id = ? AND la.site_id = ?
    ");
    $stmt->execute([$leaveId, $siteId]);
    $leave = $stmt->fetch();
    
    if (!$leave) {
        redirect(BASE_URL . '/modules/leave/list.php', 'Leave application not found.', 'error');
    }
    
} catch (Exception $e) {
    error_log("Error loading leave: " . $e->getMessage());
    redirect(BASE_URL . '/modules/leave/list.php', 'Error loading leave application.', 'error');
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Leave Application Details</h2>
        <a href="<?php echo BASE_URL; ?>/modules/leave/list.php" class="btn btn-secondary">Back to List</a>
    </div>
    
    <!-- Pending Status Alert with Action Buttons -->
    <?php if ($leave['application_status'] === 'pending' && (isSuperAdmin() || isHRAdmin())): ?>
    <div class="pending-action-card">
        <div class="pending-action-icon">⏳</div>
        <div class="pending-action-content">
            <div class="pending-action-title">This leave application is awaiting your approval</div>
            <div class="pending-action-subtitle">
                <strong><?php echo htmlspecialchars($leave['employee_name']); ?></strong> has requested 
                <strong><?php echo number_format($leave['total_days'], 1); ?> days</strong> of 
                <strong><?php echo htmlspecialchars($leave['leave_type_name'] ?? 'leave'); ?></strong>
            </div>
        </div>
        <div class="pending-action-buttons">
            <button type="button" class="btn btn-approve" onclick="approveLeave(<?php echo $leaveId; ?>)">
                ✓ Approve Leave
            </button>
            <button type="button" class="btn btn-reject" onclick="showRejectModal()">
                ✕ Reject Leave
            </button>
        </div>
    </div>
    <?php endif; ?>
    
    <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 30px;">
        <div>
            <h3 style="margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid var(--border-color);">Application Information</h3>
            
            <table style="width: 100%; border-collapse: collapse;">
                <tr>
                    <td style="padding: 8px 0; font-weight: 600; width: 40%;">Employee:</td>
                    <td style="padding: 8px 0;">
                        <strong><?php echo htmlspecialchars($leave['employee_code']); ?></strong><br>
                        <small><?php echo htmlspecialchars($leave['employee_name']); ?></small>
                    </td>
                </tr>
                <tr>
                    <td style="padding: 8px 0; font-weight: 600;">Leave Type:</td>
                    <td style="padding: 8px 0;"><?php echo htmlspecialchars($leave['leave_type_name'] ?? 'N/A'); ?></td>
                </tr>
                <tr>
                    <td style="padding: 8px 0; font-weight: 600;">Start Date:</td>
                    <td style="padding: 8px 0;"><?php echo formatDate($leave['start_date']); ?></td>
                </tr>
                <tr>
                    <td style="padding: 8px 0; font-weight: 600;">End Date:</td>
                    <td style="padding: 8px 0;"><?php echo formatDate($leave['end_date']); ?></td>
                </tr>
                <tr>
                    <td style="padding: 8px 0; font-weight: 600;">Total Days:</td>
                    <td style="padding: 8px 0;"><?php echo number_format($leave['total_days'], 1); ?> days</td>
                </tr>
                <tr>
                    <td style="padding: 8px 0; font-weight: 600;">Status:</td>
                    <td style="padding: 8px 0;">
                        <span class="status-badge status-<?php echo htmlspecialchars($leave['application_status']); ?>">
                            <?php echo ucfirst($leave['application_status']); ?>
                        </span>
                    </td>
                </tr>
            </table>
        </div>
        
        <div>
            <h3 style="margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid var(--border-color);">Additional Information</h3>
            
            <table style="width: 100%; border-collapse: collapse;">
                <tr>
                    <td style="padding: 8px 0; font-weight: 600; width: 40%;">Applied Date:</td>
                    <td style="padding: 8px 0;"><?php echo formatDateTime($leave['applied_at']); ?></td>
                </tr>
                <?php if ($leave['approved_by']): ?>
                <tr>
                    <td style="padding: 8px 0; font-weight: 600;">Approved By:</td>
                    <td style="padding: 8px 0;"><?php echo htmlspecialchars($leave['approved_by_name']); ?></td>
                </tr>
                <tr>
                    <td style="padding: 8px 0; font-weight: 600;">Approved Date:</td>
                    <td style="padding: 8px 0;"><?php echo formatDateTime($leave['approved_at']); ?></td>
                </tr>
                <?php endif; ?>
                <?php if ($leave['reason']): ?>
                <tr>
                    <td style="padding: 8px 0; font-weight: 600; vertical-align: top;">Reason:</td>
                    <td style="padding: 8px 0;"><?php echo nl2br(htmlspecialchars($leave['reason'])); ?></td>
                </tr>
                <?php endif; ?>
                <?php if ($leave['rejection_reason']): ?>
                <tr>
                    <td style="padding: 8px 0; font-weight: 600; vertical-align: top;">Rejection Reason:</td>
                    <td style="padding: 8px 0; color: var(--error-color);"><?php echo nl2br(htmlspecialchars($leave['rejection_reason'])); ?></td>
                </tr>
                <?php endif; ?>
            </table>
        </div>
    </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>Please provide a reason for rejecting this leave application:</p>
            <textarea id="rejectionReason" rows="4" placeholder="Enter rejection reason..." 
                      style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px;"></textarea>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" onclick="closeRejectModal()">Cancel</button>
            <button type="button" class="btn btn-reject" onclick="rejectLeave(<?php echo $leaveId; ?>)">Reject Leave</button>
        </div>
    </div>
</div>

<style>
/* Pending Action Card */
.pending-action-card {
    display: flex;
    align-items: center;
    gap: 20px;
    padding: 20px;
    margin-bottom: 25px;
    background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
    border: 2px solid #ff9800;
    border-radius: 12px;
    animation: pulse-border 2s ease-in-out infinite;
}

@keyframes pulse-border {
    0%, 100% { border-color: #ff9800; box-shadow: 0 0 10px rgba(255, 152, 0, 0.3); }
    50% { border-color: #f57c00; box-shadow: 0 0 20px rgba(255, 152, 0, 0.5); }
}

.pending-action-icon {
    font-size: 48px;
    animation: bounce 1s ease-in-out infinite;
}

@keyframes bounce {
    0%, 100% { transform: translateY(0); }
    50% { transform: translateY(-5px); }
}

.pending-action-content {
    flex: 1;
}

.pending-action-title {
    font-size: 18px;
    font-weight: 700;
    color: #e65100;
    margin-bottom: 5px;
}

.pending-action-subtitle {
    font-size: 14px;
    color: #bf360c;
}

.pending-action-buttons {
    display: flex;
    gap: 10px;
}

/* Approve/Reject Buttons */
.btn-approve {
    background: linear-gradient(135deg, #00b894 0%, #00a38d 100%);
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 8px;
    font-weight: 700;
    cursor: pointer;
    transition: all 0.3s;
}

.btn-approve:hover {
    background: linear-gradient(135deg, #00a38d 0%, #008f7a 100%);
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(0, 184, 148, 0.4);
}

.btn-reject {
    background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 8px;
    font-weight: 700;
    cursor: pointer;
    transition: all 0.3s;
}

.btn-reject:hover {
    background: linear-gradient(135deg, #ee5a24 0%, #d63031 100%);
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(238, 90, 36, 0.4);
}

/* Status Badge Styles */
.status-badge {
    display: inline-block;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
}

.status-pending {
    background: #fff3e0;
    color: #e65100;
}

.status-approved {
    background: #e8f5e9;
    color: #2e7d32;
}

.status-rejected {
    background: #ffebee;
    color: #c62828;
}

.status-cancelled {
    background: #f5f5f5;
    color: #616161;
}

/* Modal Styles */
.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 10px 40px rgba(0, 0, 0, 0.3);
    animation: modal-slide-in 0.3s ease-out;
}

@keyframes modal-slide-in {
    from {
        opacity: 0;
        transform: translateY(-20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

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

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

.modal-close {
    background: none;
    border: none;
    font-size: 28px;
    cursor: pointer;
    color: #999;
    padding: 0;
    line-height: 1;
}

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

.modal-body {
    padding: 20px;
}

.modal-body p {
    margin-bottom: 15px;
    color: #666;
}

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

/* Responsive */
@media (max-width: 768px) {
    .pending-action-card {
        flex-direction: column;
        text-align: center;
    }
    
    .pending-action-buttons {
        width: 100%;
        flex-direction: column;
    }
    
    .pending-action-buttons .btn {
        width: 100%;
    }
}
</style>

<script>
// Approve Leave
function approveLeave(leaveId) {
    if (confirm('Are you sure you want to APPROVE this leave application?')) {
        processLeaveAction(leaveId, 'approve');
    }
}

// Show Reject Modal
function showRejectModal() {
    document.getElementById('rejectModal').style.display = 'flex';
    document.getElementById('rejectionReason').focus();
}

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

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

// Process Leave Action
function processLeaveAction(leaveId, action, reason = '') {
    // Disable buttons
    const buttons = document.querySelectorAll('.btn-approve, .btn-reject');
    buttons.forEach(btn => {
        btn.disabled = true;
        btn.style.opacity = '0.5';
        btn.innerText = 'Processing...';
    });
    
    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();
            // Reload the page to show updated status
            window.location.reload();
        } else {
            alert('Error: ' + data.message);
            // Re-enable buttons
            buttons.forEach(btn => {
                btn.disabled = false;
                btn.style.opacity = '1';
            });
            // Restore button text
            document.querySelector('.btn-approve').innerText = '✓ Approve Leave';
            document.querySelectorAll('.btn-reject').forEach(btn => {
                btn.innerText = '✕ Reject Leave';
            });
        }
    })
    .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 key
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'; ?>

