<?php
/**
 * Enterprise HRM ERP System - Payslip PDF Export
 * Simple HTML to PDF (can be enhanced with TCPDF/FPDF)
 */

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

$payrollId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$format = $_GET['format'] ?? 'pdf';

if ($payrollId <= 0) {
    die('Invalid payslip ID');
}

$siteId = getCurrentSiteId();

try {
    $db = getDB();
    
    $stmt = $db->prepare("
        SELECT pr.*, e.employee_code, e.first_name, e.last_name, e.middle_name,
               d.department_name, des.designation_name,
               pp.period_name, pp.start_date, pp.end_date, pp.pay_date,
               s.site_name, s.site_address
        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
        INNER JOIN sites s ON pr.site_id = s.site_id
        LEFT JOIN departments d ON e.department_id = d.department_id
        LEFT JOIN designations des ON e.designation_id = des.designation_id
        WHERE pr.payroll_id = ? AND pr.site_id = ?
    ");
    $stmt->execute([$payrollId, $siteId]);
    $payroll = $stmt->fetch();
    
    if (!$payroll) {
        die('Payslip not found');
    }
    
    // Get payroll details
    $stmt = $db->prepare("
        SELECT sc.component_code, sc.component_name, sc.component_type, pd.amount
        FROM payroll_details pd
        INNER JOIN salary_components sc ON pd.component_id = sc.component_id
        WHERE pd.payroll_id = ?
        ORDER BY sc.component_type DESC, sc.component_code
    ");
    $stmt->execute([$payrollId]);
    $details = $stmt->fetchAll();
    
    $earnings = [];
    $deductions = [];
    foreach ($details as $detail) {
        if ($detail['component_type'] === 'earning') {
            $earnings[] = $detail;
        } else {
            $deductions[] = $detail;
        }
    }
    
} catch (Exception $e) {
    die('Error loading payslip: ' . $e->getMessage());
}

// For now, redirect to print view (can be enhanced with actual PDF library)
if ($format === 'pdf') {
    header('Location: ' . BASE_URL . '/modules/payroll/payslip.php?id=' . $payrollId . '&format=print');
    exit;
}

// CSV Export
if ($format === 'csv') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="payslip_' . $payroll['employee_code'] . '_' . date('Y-m', strtotime($payroll['start_date'])) . '.csv"');
    
    $output = fopen('php://output', 'w');
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF)); // BOM for UTF-8
    
    fputcsv($output, ['PAYSLIP']);
    fputcsv($output, ['']);
    fputcsv($output, ['Employee Code', $payroll['employee_code']]);
    fputcsv($output, ['Employee Name', trim($payroll['first_name'] . ' ' . ($payroll['middle_name'] ?? '') . ' ' . $payroll['last_name'])]);
    fputcsv($output, ['Period', $payroll['period_name']]);
    fputcsv($output, ['']);
    fputcsv($output, ['EARNINGS']);
    foreach ($earnings as $earning) {
        fputcsv($output, [$earning['component_name'], formatCurrency($earning['amount'])]);
    }
    fputcsv($output, ['Total Earnings', formatCurrency($payroll['total_earnings'])]);
    fputcsv($output, ['']);
    fputcsv($output, ['DEDUCTIONS']);
    foreach ($deductions as $deduction) {
        fputcsv($output, [$deduction['component_name'], formatCurrency($deduction['amount'])]);
    }
    fputcsv($output, ['Total Deductions', formatCurrency($payroll['total_deductions'])]);
    fputcsv($output, ['Net Salary', formatCurrency($payroll['net_salary'])]);
    
    fclose($output);
    exit;
}

