<?php
/**
 * Enterprise HRM ERP System - Leave Types Management
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/check_admin_access.php';

$pageTitle = 'Leave Types';
$currentModule = 'settings';

$siteId = getCurrentSiteId();

// Handle delete request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    $deleteId = isset($_POST['leave_type_id']) ? (int)$_POST['leave_type_id'] : 0;
    
    if ($deleteId > 0) {
        try {
            $db = getDB();
            
            // Check if leave type exists and belongs to current site
            $stmt = $db->prepare("SELECT leave_type_id, leave_type_name FROM leave_types WHERE leave_type_id = ? AND site_id = ?");
            $stmt->execute([$deleteId, $siteId]);
            $leaveType = $stmt->fetch();
            
            if ($leaveType) {
                // Check if there are any leave applications using this leave type
                $stmt = $db->prepare("SELECT COUNT(*) FROM leave_applications WHERE leave_type_id = ?");
                $stmt->execute([$deleteId]);
                $applicationCount = $stmt->fetchColumn();
                
                if ($applicationCount > 0) {
                    $_SESSION['error'] = "Cannot delete '{$leaveType['leave_type_name']}' - it has {$applicationCount} leave application(s) associated with it.";
                } else {
                    // Safe to delete
                    $stmt = $db->prepare("DELETE FROM leave_types WHERE leave_type_id = ? AND site_id = ?");
                    $stmt->execute([$deleteId, $siteId]);
                    
                    if ($stmt->rowCount() > 0) {
                        $_SESSION['success'] = "Leave type '{$leaveType['leave_type_name']}' deleted successfully.";
                    } else {
                        $_SESSION['error'] = "Failed to delete leave type.";
                    }
                }
            } else {
                $_SESSION['error'] = "Leave type not found.";
            }
        } catch (Exception $e) {
            error_log("Error deleting leave type: " . $e->getMessage());
            $_SESSION['error'] = "An error occurred while deleting the leave type.";
        }
    }
    
    // Redirect to prevent form resubmission
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT lt.*, 
               COUNT(DISTINCT la.leave_application_id) as application_count,
               SUM(CASE WHEN la.application_status = 'approved' THEN la.total_days ELSE 0 END) as total_days_used
        FROM leave_types lt
        LEFT JOIN leave_applications la ON lt.leave_type_id = la.leave_type_id
        WHERE lt.site_id = ?
        GROUP BY lt.leave_type_id
        ORDER BY lt.leave_type_name
    ");
    $stmt->execute([$siteId]);
    $leaveTypes = $stmt->fetchAll();
} catch (Exception $e) {
    error_log("Leave types error: " . $e->getMessage());
    $leaveTypes = [];
}

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

<div class="table-container">
    <div class="table-header">
        <h2 class="table-title">Leave Types Management</h2>
        <div class="table-actions">
            <a href="<?php echo BASE_URL; ?>/admin/leave_types_create.php" class="btn btn-primary">Add Leave Type</a>
        </div>
    </div>
    
    <?php if (count($leaveTypes) > 0): ?>
    
    <!-- Scroll Controls -->
    <div class="scroll-controls">
        <button type="button" class="scroll-btn scroll-left" onclick="scrollTableLeft()" title="Scroll Left">
            ◀
        </button>
        <span class="scroll-hint">← Swipe or use buttons to scroll →</span>
        <button type="button" class="scroll-btn scroll-right" onclick="scrollTableRight()" title="Scroll Right">
            ▶
        </button>
    </div>
    
    <!-- Scrollable Table Wrapper -->
    <div class="table-scroll-wrapper" id="tableScrollWrapper">
        <table class="data-table">
            <thead>
                <tr>
                    <th class="sortable">Leave Type Code</th>
                    <th class="sortable">Leave Type Name</th>
                    <th>Max Days/Year</th>
                    <th>Carry Forward</th>
                    <th>Applications</th>
                    <th>Days Used</th>
                    <th class="sortable">Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($leaveTypes as $type): ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($type['leave_type_code']); ?></strong></td>
                    <td><?php echo htmlspecialchars($type['leave_type_name']); ?></td>
                    <td><?php echo $type['max_days_per_year'] > 0 ? number_format($type['max_days_per_year']) : 'Unlimited'; ?></td>
                    <td><?php echo $type['carry_forward'] ? 'Yes' : 'No'; ?></td>
                    <td><?php echo number_format($type['application_count']); ?></td>
                    <td><?php echo number_format($type['total_days_used'], 1); ?></td>
                    <td>
                        <span class="status-badge status-<?php echo htmlspecialchars($type['leave_type_status']); ?>">
                            <?php echo ucfirst($type['leave_type_status']); ?>
                        </span>
                    </td>
                    <td class="table-actions-cell">
                        <div class="action-buttons">
                            <a href="<?php echo BASE_URL; ?>/admin/leave_types_edit.php?id=<?php echo $type['leave_type_id']; ?>" 
                               class="btn btn-sm btn-primary">Edit</a>
                            <?php if ($type['application_count'] > 0): ?>
                            <button type="button" class="btn btn-sm btn-danger" 
                                    onclick="alert('Cannot delete - this leave type has <?php echo $type['application_count']; ?> application(s) associated with it.')"
                                    title="Cannot Delete - Has Applications">
                                🗑️ Delete
                            </button>
                            <?php else: ?>
                            <form method="POST" style="display: inline;" onsubmit="return confirm('Are you sure you want to delete \'<?php echo htmlspecialchars(addslashes($type['leave_type_name'])); ?>\'? This action cannot be undone.');">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="leave_type_id" value="<?php echo $type['leave_type_id']; ?>">
                                <button type="submit" class="btn btn-sm btn-danger" title="Delete Leave Type">
                                    🗑️ Delete
                                </button>
                            </form>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    
    <?php else: ?>
    <div class="table-empty">
        <div class="table-empty-icon">📋</div>
        <div class="table-empty-message">No leave types found</div>
        <div class="table-empty-submessage">
            <a href="<?php echo BASE_URL; ?>/admin/leave_types_create.php" class="btn btn-primary">Add First Leave Type</a>
        </div>
    </div>
    <?php endif; ?>
</div>

<style>
.status-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 11px;
    font-weight: 500;
    text-transform: uppercase;
}

.status-active {
    background-color: #d1fae5;
    color: #065f46;
}

.status-inactive {
    background-color: #e5e7eb;
    color: #374151;
}

/* Action Buttons */
.action-buttons {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.btn-danger {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    color: white;
    border: none;
}

.btn-danger:hover {
    background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
    transform: translateY(-1px);
}

/* Scroll Controls */
.scroll-controls {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 15px;
    padding: 12px 15px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 8px;
    margin-bottom: 15px;
}

.scroll-btn {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    border: 2px solid white;
    background: rgba(255, 255, 255, 0.2);
    color: white;
    font-size: 16px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.scroll-btn:hover {
    background: white;
    color: #667eea;
    transform: scale(1.1);
}

.scroll-btn:active {
    transform: scale(0.95);
}

.scroll-hint {
    color: white;
    font-size: 13px;
    font-weight: 500;
    opacity: 0.9;
}

/* Scrollable Table Wrapper */
.table-scroll-wrapper {
    overflow-x: auto;
    overflow-y: visible;
    -webkit-overflow-scrolling: touch;
    scroll-behavior: smooth;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.table-scroll-wrapper::-webkit-scrollbar {
    height: 10px;
}

.table-scroll-wrapper::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 5px;
}

.table-scroll-wrapper::-webkit-scrollbar-thumb {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 5px;
}

.table-scroll-wrapper::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
}

.table-scroll-wrapper .data-table {
    min-width: 800px;
    margin-bottom: 0;
}

/* Mobile Responsive */
@media (max-width: 768px) {
    .scroll-controls {
        padding: 10px;
        gap: 10px;
    }
    
    .scroll-btn {
        width: 36px;
        height: 36px;
        font-size: 14px;
    }
    
    .scroll-hint {
        font-size: 11px;
    }
    
    .table-scroll-wrapper .data-table {
        min-width: 700px;
    }
}

@media (max-width: 480px) {
    .scroll-hint {
        display: none;
    }
    
    .scroll-controls {
        justify-content: space-between;
        padding: 8px 15px;
    }
}
</style>

<script>
// Scroll amount in pixels
const scrollAmount = 300;

// Scroll table left
function scrollTableLeft() {
    const wrapper = document.getElementById('tableScrollWrapper');
    if (wrapper) {
        wrapper.scrollBy({
            left: -scrollAmount,
            behavior: 'smooth'
        });
    }
}

// Scroll table right
function scrollTableRight() {
    const wrapper = document.getElementById('tableScrollWrapper');
    if (wrapper) {
        wrapper.scrollBy({
            left: scrollAmount,
            behavior: 'smooth'
        });
    }
}

// Keyboard navigation
document.addEventListener('keydown', function(e) {
    if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
    
    if (e.key === 'ArrowLeft') {
        scrollTableLeft();
    } else if (e.key === 'ArrowRight') {
        scrollTableRight();
    }
});

// Update scroll button visibility based on scroll position
document.addEventListener('DOMContentLoaded', function() {
    const wrapper = document.getElementById('tableScrollWrapper');
    const leftBtn = document.querySelector('.scroll-left');
    const rightBtn = document.querySelector('.scroll-right');
    
    if (wrapper && leftBtn && rightBtn) {
        function updateScrollButtons() {
            const scrollLeft = wrapper.scrollLeft;
            const maxScroll = wrapper.scrollWidth - wrapper.clientWidth;
            
            leftBtn.style.opacity = scrollLeft > 0 ? '1' : '0.5';
            rightBtn.style.opacity = scrollLeft < maxScroll - 5 ? '1' : '0.5';
        }
        
        wrapper.addEventListener('scroll', updateScrollButtons);
        window.addEventListener('resize', updateScrollButtons);
        updateScrollButtons();
    }
});

</script>

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

