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

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

$pageTitle = 'Leave Management';
$currentModule = 'leave';

$siteId = getCurrentSiteId();
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Filters
$search = sanitize($_GET['search'] ?? '');
$status = sanitize($_GET['status'] ?? '');

// Build query
$where = ["la.site_id = ?"];
$params = [$siteId];

if (!empty($search)) {
    $where[] = "(e.employee_code LIKE ? OR e.first_name LIKE ? OR e.last_name LIKE ?)";
    $searchParam = "%{$search}%";
    $params = array_merge($params, [$searchParam, $searchParam, $searchParam]);
}

if (!empty($status)) {
    $where[] = "la.application_status = ?";
    $params[] = $status;
}

$whereClause = implode(' AND ', $where);

try {
    $db = getDB();
    
    // Get total count
    $countSql = "
        SELECT COUNT(*) 
        FROM leave_applications la
        INNER JOIN employees e ON la.employee_id = e.employee_id
        WHERE {$whereClause}
    ";
    $stmt = $db->prepare($countSql);
    $stmt->execute($params);
    $totalRecords = $stmt->fetchColumn();
    $totalPages = ceil($totalRecords / $perPage);
    
    // Get leave applications
    $sql = "
        SELECT 
            la.*,
            e.employee_code,
            CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) as employee_name,
            lt.leave_type_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
        WHERE {$whereClause}
        ORDER BY la.applied_at DESC
        LIMIT ? OFFSET ?
    ";
    $params[] = $perPage;
    $params[] = $offset;
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $leaves = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Leave list error: " . $e->getMessage());
    $leaves = [];
    $totalRecords = 0;
    $totalPages = 0;
}

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

<div class="table-container">
    <div class="table-header">
        <h2 class="table-title">Leave Applications</h2>
        <div class="table-actions">
            <a href="<?php echo BASE_URL; ?>/modules/leave/create.php" class="btn btn-primary">Apply for Leave</a>
        </div>
    </div>
    
    <div class="table-filters">
        <div class="filter-group">
            <label>Search Employee</label>
            <input type="text" name="search" class="form-control" placeholder="Employee Code or Name..." 
                   value="<?php echo htmlspecialchars($search); ?>" 
                   onkeypress="if(event.key==='Enter') filterTable()">
        </div>
        <div class="filter-group">
            <label>Status</label>
            <select name="status" class="form-control" onchange="filterTable()">
                <option value="">All Status</option>
                <option value="pending" <?php echo $status === 'pending' ? 'selected' : ''; ?>>Pending</option>
                <option value="approved" <?php echo $status === 'approved' ? 'selected' : ''; ?>>Approved</option>
                <option value="rejected" <?php echo $status === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                <option value="cancelled" <?php echo $status === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
            </select>
        </div>
        <div class="filter-group">
            <button type="button" class="btn btn-secondary" onclick="resetFilters()">Reset</button>
        </div>
    </div>
    
    <?php if (count($leaves) > 0): ?>
    <table class="data-table">
        <thead>
            <tr>
                <th class="sortable">Employee</th>
                <th class="sortable">Leave Type</th>
                <th class="sortable">Start Date</th>
                <th class="sortable">End Date</th>
                <th class="sortable">Total Days</th>
                <th class="sortable">Status</th>
                <th class="sortable">Applied Date</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($leaves as $leave): ?>
            <tr>
                <td>
                    <strong><?php echo htmlspecialchars($leave['employee_code']); ?></strong><br>
                    <small><?php echo htmlspecialchars($leave['employee_name']); ?></small>
                </td>
                <td><?php echo htmlspecialchars($leave['leave_type_name'] ?? 'N/A'); ?></td>
                <td><?php echo formatDate($leave['start_date']); ?></td>
                <td><?php echo formatDate($leave['end_date']); ?></td>
                <td><?php echo number_format($leave['total_days'], 1); ?> days</td>
                <td>
                    <span class="status-badge status-<?php echo htmlspecialchars($leave['application_status']); ?>">
                        <?php echo ucfirst($leave['application_status']); ?>
                    </span>
                </td>
                <td><?php echo formatDateTime($leave['applied_at']); ?></td>
                <td class="table-actions-cell">
                    <a href="<?php echo BASE_URL; ?>/modules/leave/view.php?id=<?php echo $leave['leave_application_id']; ?>" 
                       class="btn btn-sm btn-secondary">View</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    
    <div class="table-footer">
        <div class="table-info">
            Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $perPage, $totalRecords); ?> of <?php echo number_format($totalRecords); ?> applications
        </div>
        <div class="pagination">
            <?php if ($page > 1): ?>
            <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>" 
               class="btn btn-sm">Previous</a>
            <?php endif; ?>
            <span class="pagination-info">Page <?php echo $page; ?> of <?php echo $totalPages; ?></span>
            <?php if ($page < $totalPages): ?>
            <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>" 
               class="btn btn-sm">Next</a>
            <?php endif; ?>
        </div>
    </div>
    <?php else: ?>
    <div class="table-empty">
        <div class="table-empty-icon">📅</div>
        <div class="table-empty-message">No leave applications found</div>
        <div class="table-empty-submessage">
            <a href="<?php echo BASE_URL; ?>/modules/leave/create.php" class="btn btn-primary">Apply for Leave</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-pending {
    background-color: #fef3c7;
    color: #92400e;
}

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

.status-rejected {
    background-color: #fee2e2;
    color: #991b1b;
}

.status-cancelled {
    background-color: #e5e7eb;
    color: #374151;
}
</style>

<script>
function filterTable() {
    const search = document.querySelector('[name="search"]').value;
    const status = document.querySelector('[name="status"]').value;
    
    const params = new URLSearchParams();
    if (search) params.append('search', search);
    if (status) params.append('status', status);
    
    window.location.href = '?' + params.toString();
}

function resetFilters() {
    window.location.href = '<?php echo BASE_URL; ?>/modules/leave/list.php';
}
</script>

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