<?php
/**
 * Enterprise HRM ERP System - Payslip View/Export
 */

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

$pageTitle = 'Payslip';
$currentModule = 'payroll';

$siteId = getCurrentSiteId();
$payrollId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$employeeId = isset($_GET['employee_id']) ? (int)$_GET['employee_id'] : 0;
$periodId = isset($_GET['period_id']) ? (int)$_GET['period_id'] : 0;

// For employees, they can only view their own payslip
$currentUserId = getCurrentUserId();
$isEmployee = ($_SESSION['role_code'] ?? '') === 'employee';

try {
    $db = getDB();
    
    if ($payrollId > 0) {
        $stmt = $db->prepare("
            SELECT pr.*, e.employee_code, e.first_name, e.last_name, e.middle_name,
                   e.email, e.phone, 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) {
            redirect(BASE_URL . '/modules/payroll/list.php', 'Payslip not found.', 'error');
        }
        
        // Check if employee is viewing their own payslip
        if ($isEmployee) {
            // Get employee_id from user
            $stmt = $db->prepare("SELECT employee_id FROM employees WHERE site_id = ? AND email = ? LIMIT 1");
            $stmt->execute([$siteId, $_SESSION['email'] ?? '']);
            $empId = $stmt->fetchColumn();
            
            if ($payroll['employee_id'] != $empId) {
                redirect(BASE_URL . '/dashboard.php', 'You can only view your own payslip.', 'error');
            }
        }
        
    } elseif ($employeeId > 0 && $periodId > 0) {
        // Get payslip by employee and period
        $stmt = $db->prepare("
            SELECT pr.*, e.employee_code, e.first_name, e.last_name, e.middle_name,
                   e.email, e.phone, 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.employee_id = ? AND pr.period_id = ? AND pr.site_id = ?
        ");
        $stmt->execute([$employeeId, $periodId, $siteId]);
        $payroll = $stmt->fetch();
        
        if (!$payroll) {
            redirect(BASE_URL . '/modules/payroll/list.php', 'Payslip not found.', 'error');
        }
        
        $payrollId = $payroll['payroll_id'];
    } else {
        redirect(BASE_URL . '/modules/payroll/list.php', 'Invalid payslip parameters.', 'error');
    }
    
    // Get payroll details (earnings and deductions)
    $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) {
    error_log("Error loading payslip: " . $e->getMessage());
    redirect(BASE_URL . '/modules/payroll/list.php', 'Error loading payslip.', 'error');
}

$format = $_GET['format'] ?? 'view'; // view, pdf, print

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

<div class="card" style="max-width: 800px; margin: 0 auto;">
    <div class="card-header" style="text-align: center;">
        <h2 class="card-title">PAYSLIP</h2>
        <div style="display: flex; gap: 10px; justify-content: center; margin-top: 10px;">
            <a href="<?php echo BASE_URL; ?>/modules/payroll/payslip.php?id=<?php echo $payrollId; ?>&format=print" 
               class="btn btn-sm btn-secondary" target="_blank">Print</a>
            <a href="<?php echo BASE_URL; ?>/modules/payroll/payslip_export.php?id=<?php echo $payrollId; ?>&format=pdf" 
               class="btn btn-sm btn-primary">Export PDF</a>
        </div>
    </div>
    
    <!-- Payslip Content -->
    <div style="padding: 30px;">
        <!-- Company & Employee Info -->
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 30px; margin-bottom: 30px; padding-bottom: 20px; border-bottom: 2px solid #e5e7eb;">
            <div>
                <h3 style="margin-bottom: 10px; color: var(--primary-color);"><?php echo htmlspecialchars($payroll['site_name']); ?></h3>
                <p style="font-size: 12px; color: var(--text-secondary); line-height: 1.6;">
                    <?php echo nl2br(htmlspecialchars($payroll['site_address'] ?? '')); ?>
                </p>
            </div>
            <div style="text-align: right;">
                <p style="margin-bottom: 5px;"><strong>Employee Code:</strong> <?php echo htmlspecialchars($payroll['employee_code']); ?></p>
                <p style="margin-bottom: 5px;"><strong>Name:</strong> <?php echo htmlspecialchars(trim($payroll['first_name'] . ' ' . ($payroll['middle_name'] ?? '') . ' ' . $payroll['last_name'])); ?></p>
                <p style="margin-bottom: 5px;"><strong>Department:</strong> <?php echo htmlspecialchars($payroll['department_name'] ?? 'N/A'); ?></p>
                <p style="margin-bottom: 5px;"><strong>Designation:</strong> <?php echo htmlspecialchars($payroll['designation_name'] ?? 'N/A'); ?></p>
            </div>
        </div>
        
        <!-- Period Info -->
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 30px; padding: 15px; background: #f9fafb; border-radius: 6px;">
            <div>
                <p style="font-size: 12px; color: var(--text-secondary); margin-bottom: 5px;">Pay Period</p>
                <p style="font-weight: 600;"><?php echo htmlspecialchars($payroll['period_name']); ?></p>
            </div>
            <div>
                <p style="font-size: 12px; color: var(--text-secondary); margin-bottom: 5px;">Period</p>
                <p style="font-weight: 600;"><?php echo formatDate($payroll['start_date']); ?> to <?php echo formatDate($payroll['end_date']); ?></p>
            </div>
            <div>
                <p style="font-size: 12px; color: var(--text-secondary); margin-bottom: 5px;">Pay Date</p>
                <p style="font-weight: 600;"><?php echo formatDate($payroll['pay_date']); ?></p>
            </div>
        </div>
        
        <!-- Earnings & Deductions -->
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 30px; margin-bottom: 30px;">
            <!-- Earnings -->
            <div>
                <h4 style="margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid #e5e7eb;">EARNINGS</h4>
                <table style="width: 100%; border-collapse: collapse;">
                    <?php foreach ($earnings as $earning): ?>
                    <tr>
                        <td style="padding: 8px 0; border-bottom: 1px solid #f3f4f6;"><?php echo htmlspecialchars($earning['component_name']); ?></td>
                        <td style="text-align: right; padding: 8px 0; border-bottom: 1px solid #f3f4f6; font-weight: 500;">
                            <?php echo formatCurrency($earning['amount']); ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <tr style="background: #f9fafb;">
                        <td style="padding: 10px 0; font-weight: 600;">Total Earnings</td>
                        <td style="text-align: right; padding: 10px 0; font-weight: 600; font-size: 16px;">
                            <?php echo formatCurrency($payroll['total_earnings']); ?>
                        </td>
                    </tr>
                </table>
            </div>
            
            <!-- Deductions -->
            <div>
                <h4 style="margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid #e5e7eb;">DEDUCTIONS</h4>
                <table style="width: 100%; border-collapse: collapse;">
                    <?php foreach ($deductions as $deduction): ?>
                    <tr>
                        <td style="padding: 8px 0; border-bottom: 1px solid #f3f4f6;"><?php echo htmlspecialchars($deduction['component_name']); ?></td>
                        <td style="text-align: right; padding: 8px 0; border-bottom: 1px solid #f3f4f6; font-weight: 500;">
                            <?php echo formatCurrency($deduction['amount']); ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if ($payroll['tax_amount'] > 0): ?>
                    <tr>
                        <td style="padding: 8px 0; border-bottom: 1px solid #f3f4f6;">Tax (TDS)</td>
                        <td style="text-align: right; padding: 8px 0; border-bottom: 1px solid #f3f4f6; font-weight: 500;">
                            <?php echo formatCurrency($payroll['tax_amount']); ?>
                        </td>
                    </tr>
                    <?php endif; ?>
                    <tr style="background: #f9fafb;">
                        <td style="padding: 10px 0; font-weight: 600;">Total Deductions</td>
                        <td style="text-align: right; padding: 10px 0; font-weight: 600; font-size: 16px;">
                            <?php echo formatCurrency($payroll['total_deductions'] + $payroll['tax_amount']); ?>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
        
        <!-- Net Salary -->
        <div style="padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 8px; text-align: center;">
            <p style="font-size: 14px; margin-bottom: 10px; opacity: 0.9;">NET SALARY</p>
            <p style="font-size: 32px; font-weight: 600; margin: 0;"><?php echo formatCurrency($payroll['net_salary']); ?></p>
        </div>
        
        <!-- Attendance Summary -->
        <div style="margin-top: 30px; padding: 15px; background: #f9fafb; border-radius: 6px;">
            <h4 style="margin-bottom: 15px;">ATTENDANCE SUMMARY</h4>
            <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; text-align: center;">
                <div>
                    <p style="font-size: 12px; color: var(--text-secondary); margin-bottom: 5px;">Working Days</p>
                    <p style="font-size: 18px; font-weight: 600;"><?php echo number_format($payroll['working_days'], 1); ?></p>
                </div>
                <div>
                    <p style="font-size: 12px; color: var(--text-secondary); margin-bottom: 5px;">Present Days</p>
                    <p style="font-size: 18px; font-weight: 600; color: #10b981;"><?php echo number_format($payroll['present_days'], 1); ?></p>
                </div>
                <div>
                    <p style="font-size: 12px; color: var(--text-secondary); margin-bottom: 5px;">Absent Days</p>
                    <p style="font-size: 18px; font-weight: 600; color: #ef4444;"><?php echo number_format($payroll['absent_days'], 1); ?></p>
                </div>
                <div>
                    <p style="font-size: 12px; color: var(--text-secondary); margin-bottom: 5px;">OT Hours</p>
                    <p style="font-size: 18px; font-weight: 600; color: #3b82f6;"><?php echo number_format($payroll['overtime_hours'], 2); ?></p>
                </div>
            </div>
        </div>
        
        <!-- Footer -->
        <div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #e5e7eb; text-align: center;">
            <p style="font-size: 11px; color: var(--text-secondary);">
                This is a computer-generated payslip. No signature required.
            </p>
        </div>
    </div>
</div>

<?php if ($format === 'print'): ?>
<style>
@media print {
    body { margin: 0; padding: 0; }
    .sidebar, .top-bar, .card-header, .btn { display: none !important; }
    .card { box-shadow: none; border: none; }
}
</style>
<script>
window.onload = function() {
    window.print();
}
</script>
<?php endif; ?>

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

