<?php
/**
 * Enterprise HRM ERP System - Payroll List
 */

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

$pageTitle = 'Payroll Management';
$currentModule = 'payroll';

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

// Filters
$search = sanitize($_GET['search'] ?? '');
$periodId = isset($_GET['period_id']) ? (int)$_GET['period_id'] : 0;

// Build query
$where = ["pr.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 ($periodId > 0) {
    $where[] = "pr.period_id = ?";
    $params[] = $periodId;
}

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

try {
    $db = getDB();
    
    // Get payroll periods for filter
    $stmt = $db->prepare("
        SELECT period_id, period_name, period_code, start_date, end_date, period_status
        FROM payroll_periods 
        WHERE site_id = ?
        ORDER BY start_date DESC
        LIMIT 10
    ");
    $stmt->execute([$siteId]);
    $periods = $stmt->fetchAll();
    
    // Get total count
    $countSql = "
        SELECT COUNT(*) 
        FROM payroll_records pr
        INNER JOIN employees e ON pr.employee_id = e.employee_id
        WHERE {$whereClause}
    ";
    $stmt = $db->prepare($countSql);
    $stmt->execute($params);
    $totalRecords = $stmt->fetchColumn();
    $totalPages = ceil($totalRecords / $perPage);
    
    // Get payroll records
    $sql = "
        SELECT 
            pr.*,
            e.employee_code,
            CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) as employee_name,
            pp.period_name, pp.period_code
        FROM payroll_records pr
        INNER JOIN employees e ON pr.employee_id = e.employee_id
        INNER JOIN payroll_periods pp ON pr.period_id = pp.period_id
        WHERE {$whereClause}
        ORDER BY pr.created_at DESC
        LIMIT ? OFFSET ?
    ";
    $params[] = $perPage;
    $params[] = $offset;
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $payrolls = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Payroll list error: " . $e->getMessage());
    $payrolls = [];
    $periods = [];
    $totalRecords = 0;
    $totalPages = 0;
}

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

<div class="table-container">
    <div class="table-header">
        <h2 class="table-title">Payroll Records</h2>
        <div class="table-actions">
            <a href="<?php echo BASE_URL; ?>/modules/payroll/create.php" class="btn btn-primary">Create Payroll Period</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>Payroll Period</label>
            <select name="period_id" class="form-control" onchange="filterTable()">
                <option value="">All Periods</option>
                <?php foreach ($periods as $period): ?>
                <option value="<?php echo $period['period_id']; ?>" 
                        <?php echo $periodId == $period['period_id'] ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($period['period_name']); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="filter-group">
            <button type="button" class="btn btn-secondary" onclick="resetFilters()">Reset</button>
        </div>
    </div>
    
    <?php if (count($payrolls) > 0): ?>
    <table class="data-table">
        <thead>
            <tr>
                <th class="sortable">Period</th>
                <th class="sortable">Employee</th>
                <th class="sortable">Working Days</th>
                <th class="sortable">Present Days</th>
                <th class="sortable">Gross Salary</th>
                <th class="sortable">Deductions</th>
                <th class="sortable">Net Salary</th>
                <th class="sortable">Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($payrolls as $payroll): ?>
            <tr>
                <td>
                    <strong><?php echo htmlspecialchars($payroll['period_code']); ?></strong><br>
                    <small><?php echo htmlspecialchars($payroll['period_name']); ?></small>
                </td>
                <td>
                    <strong><?php echo htmlspecialchars($payroll['employee_code']); ?></strong><br>
                    <small><?php echo htmlspecialchars($payroll['employee_name']); ?></small>
                </td>
                <td><?php echo number_format($payroll['working_days'], 1); ?></td>
                <td><?php echo number_format($payroll['present_days'], 1); ?></td>
                <td><?php echo formatCurrency($payroll['gross_salary']); ?></td>
                <td><?php echo formatCurrency($payroll['total_deductions']); ?></td>
                <td><strong><?php echo formatCurrency($payroll['net_salary']); ?></strong></td>
                <td>
                    <span class="status-badge status-<?php echo htmlspecialchars($payroll['payroll_status']); ?>">
                        <?php echo ucfirst($payroll['payroll_status']); ?>
                    </span>
                </td>
                <td class="table-actions-cell">
                    <a href="<?php echo BASE_URL; ?>/modules/payroll/view.php?id=<?php echo $payroll['payroll_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); ?> records
        </div>
        <div class="pagination">
            <?php if ($page > 1): ?>
            <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&period_id=<?php echo $periodId; ?>" 
               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); ?>&period_id=<?php echo $periodId; ?>" 
               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 payroll records found</div>
        <div class="table-empty-submessage">
            <a href="<?php echo BASE_URL; ?>/modules/payroll/create.php" class="btn btn-primary">Create Payroll Period</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-draft {
    background-color: #e5e7eb;
    color: #374151;
}

.status-calculated {
    background-color: #dbeafe;
    color: #1e40af;
}

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

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

.status-locked {
    background-color: #fee2e2;
    color: #991b1b;
}
</style>

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

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

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