<?php
/**
 * Enterprise HRM ERP System - Statutory Export
 */

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

$siteId = getCurrentSiteId();
$periodId = isset($_GET['period_id']) ? (int)$_GET['period_id'] : 0;
$format = $_GET['format'] ?? 'excel';

if ($periodId <= 0) {
    redirect(BASE_URL . '/modules/statutory/list.php', 'Invalid period ID.', 'error');
}

try {
    $db = getDB();
    
    // Get period info
    $stmt = $db->prepare("SELECT * FROM payroll_periods WHERE period_id = ? AND site_id = ?");
    $stmt->execute([$periodId, $siteId]);
    $period = $stmt->fetch();
    
    if (!$period) {
        redirect(BASE_URL . '/modules/statutory/list.php', 'Period not found.', 'error');
    }
    
    // Get statutory data
    $stmt = $db->prepare("
        SELECT 
            pr.employee_id,
            e.employee_code, e.first_name, e.last_name, e.middle_name,
            e.pf_number, e.esic_number, e.uan_number,
            d.department_name, des.designation_name,
            SUM(CASE WHEN sc.component_code = 'PF' AND sc.component_type = 'deduction' THEN pd.amount ELSE 0 END) as pf_amount,
            SUM(CASE WHEN sc.component_code = 'ESIC' AND sc.component_type = 'deduction' THEN pd.amount ELSE 0 END) as esic_amount,
            pr.gross_salary, pr.net_salary
        FROM payroll_records pr
        INNER JOIN employees e ON pr.employee_id = e.employee_id
        LEFT JOIN departments d ON e.department_id = d.department_id
        LEFT JOIN designations des ON e.designation_id = des.designation_id
        LEFT JOIN payroll_details pd ON pr.payroll_id = pd.payroll_id
        LEFT JOIN salary_components sc ON pd.component_id = sc.component_id
        WHERE pr.period_id = ? AND pr.site_id = ?
        GROUP BY pr.employee_id, pr.payroll_id
        ORDER BY e.employee_code
    ");
    $stmt->execute([$periodId, $siteId]);
    $statutoryData = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Statutory export error: " . $e->getMessage());
    redirect(BASE_URL . '/modules/statutory/list.php', 'Error exporting statutory data.', 'error');
}

$filename = 'Statutory_Register_' . date('F_Y', strtotime($period['start_date']));

if ($format === 'csv') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
    
    $output = fopen('php://output', 'w');
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF)); // BOM for UTF-8
    
    // Headers
    fputcsv($output, ['Employee Code', 'Employee Name', 'Department', 'PF Number', 'UAN', 'ESIC Number', 'Gross Salary', 'PF Amount', 'ESIC Amount', 'Net Salary']);
    
    // Data
    foreach ($statutoryData as $data) {
        fputcsv($output, [
            $data['employee_code'],
            trim($data['first_name'] . ' ' . ($data['middle_name'] ?? '') . ' ' . $data['last_name']),
            $data['department_name'] ?? 'N/A',
            $data['pf_number'] ?? 'N/A',
            $data['uan_number'] ?? 'N/A',
            $data['esic_number'] ?? 'N/A',
            $data['gross_salary'],
            $data['pf_amount'],
            $data['esic_amount'],
            $data['net_salary']
        ]);
    }
    
    fclose($output);
    exit;
} else {
    // Excel format (HTML table)
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="' . $filename . '.xls"');
    
    echo '<table border="1">';
    echo '<tr><th>Employee Code</th><th>Employee Name</th><th>Department</th><th>PF Number</th><th>UAN</th><th>ESIC Number</th><th>Gross Salary</th><th>PF Amount</th><th>ESIC Amount</th><th>Net Salary</th></tr>';
    
    foreach ($statutoryData as $data) {
        echo '<tr>';
        echo '<td>' . htmlspecialchars($data['employee_code']) . '</td>';
        echo '<td>' . htmlspecialchars(trim($data['first_name'] . ' ' . ($data['middle_name'] ?? '') . ' ' . $data['last_name'])) . '</td>';
        echo '<td>' . htmlspecialchars($data['department_name'] ?? 'N/A') . '</td>';
        echo '<td>' . htmlspecialchars($data['pf_number'] ?? 'N/A') . '</td>';
        echo '<td>' . htmlspecialchars($data['uan_number'] ?? 'N/A') . '</td>';
        echo '<td>' . htmlspecialchars($data['esic_number'] ?? 'N/A') . '</td>';
        echo '<td>' . formatCurrency($data['gross_salary']) . '</td>';
        echo '<td>' . formatCurrency($data['pf_amount']) . '</td>';
        echo '<td>' . formatCurrency($data['esic_amount']) . '</td>';
        echo '<td>' . formatCurrency($data['net_salary']) . '</td>';
        echo '</tr>';
    }
    
    echo '</table>';
    exit;
}

