<?php
/**
 * Enterprise HRM ERP System - View Payroll Record
 */

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

$pageTitle = 'View Payroll Record';
$currentModule = 'payroll';

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

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

try {
    $db = getDB();
    $stmt = $db->prepare("
        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, pp.start_date as period_start, pp.end_date as period_end
        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 pr.payroll_id = ? AND pr.site_id = ?
    ");
    $stmt->execute([$payrollId, $siteId]);
    $payroll = $stmt->fetch();
    
    if (!$payroll) {
        redirect(BASE_URL . '/modules/payroll/list.php', 'Payroll record not found.', 'error');
    }
    
    // Get payroll details (earnings and deductions breakdown)
    $stmt = $db->prepare("
        SELECT pd.*, sc.component_name, sc.component_type
        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_name
    ");
    $stmt->execute([$payrollId]);
    $details = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Error loading payroll: " . $e->getMessage());
    redirect(BASE_URL . '/modules/payroll/list.php', 'Error loading payroll data.', 'error');
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Payroll Details</h2>
        <a href="<?php echo BASE_URL; ?>/modules/payroll/list.php" class="btn btn-secondary">Back to List</a>
    </div>
    
    <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 30px;">
        <div>
            <h3 style="margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid var(--border-color);">Employee & Period</h3>
            
            <table style="width: 100%; border-collapse: collapse;">
                <tr>
                    <td style="padding: 8px 0; font-weight: 600; width: 40%;">Employee:</td>
                    <td style="padding: 8px 0;">
                        <strong><?php echo htmlspecialchars($payroll['employee_code']); ?></strong><br>
                        <small><?php echo htmlspecialchars($payroll['employee_name']); ?></small>
                    </td>
                </tr>
                <tr>
                    <td style="padding: 8px 0; font-weight: 600;">Period:</td>
                    <td style="padding: 8px 0;">
                        <strong><?php echo htmlspecialchars($payroll['period_code']); ?></strong><br>
                        <small><?php echo htmlspecialchars($payroll['period_name']); ?></small>
                    </td>
                </tr>
                <tr>
                    <td style="padding: 8px 0; font-weight: 600;">Period Dates:</td>
                    <td style="padding: 8px 0;">
                        <?php echo formatDate($payroll['period_start']); ?> to <?php echo formatDate($payroll['period_end']); ?>
                    </td>
                </tr>
                <tr>
                    <td style="padding: 8px 0; font-weight: 600;">Status:</td>
                    <td style="padding: 8px 0;">
                        <span class="status-badge status-<?php echo htmlspecialchars($payroll['payroll_status']); ?>">
                            <?php echo ucfirst($payroll['payroll_status']); ?>
                        </span>
                    </td>
                </tr>
            </table>
        </div>
        
        <div>
            <h3 style="margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid var(--border-color);">Attendance Summary</h3>
            
            <table style="width: 100%; border-collapse: collapse;">
                <tr>
                    <td style="padding: 8px 0; font-weight: 600; width: 40%;">Working Days:</td>
                    <td style="padding: 8px 0;"><?php echo number_format($payroll['working_days'], 1); ?></td>
                </tr>
                <tr>
                    <td style="padding: 8px 0; font-weight: 600;">Present Days:</td>
                    <td style="padding: 8px 0;"><?php echo number_format($payroll['present_days'], 1); ?></td>
                </tr>
                <tr>
                    <td style="padding: 8px 0; font-weight: 600;">Absent Days:</td>
                    <td style="padding: 8px 0;"><?php echo number_format($payroll['absent_days'], 1); ?></td>
                </tr>
                <tr>
                    <td style="padding: 8px 0; font-weight: 600;">Overtime Hours:</td>
                    <td style="padding: 8px 0;"><?php echo number_format($payroll['overtime_hours'], 2); ?> hrs</td>
                </tr>
            </table>
        </div>
    </div>
    
    <?php if (count($details) > 0): ?>
    <div style="margin-top: 30px;">
        <h3 style="margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid var(--border-color);">Salary Breakdown</h3>
        
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 30px;">
            <div>
                <h4 style="color: var(--success-color); margin-bottom: 10px;">Earnings</h4>
                <table style="width: 100%; border-collapse: collapse;">
                    <?php 
                    $totalEarnings = 0;
                    foreach ($details as $detail): 
                        if ($detail['component_type'] === 'earning'):
                            $totalEarnings += $detail['amount'];
                    ?>
                    <tr>
                        <td style="padding: 5px 0;"><?php echo htmlspecialchars($detail['component_name']); ?></td>
                        <td style="padding: 5px 0; text-align: right;"><?php echo formatCurrency($detail['amount']); ?></td>
                    </tr>
                    <?php 
                        endif;
                    endforeach; 
                    ?>
                    <tr style="border-top: 2px solid var(--border-color); font-weight: 600;">
                        <td style="padding: 8px 0;">Total Earnings</td>
                        <td style="padding: 8px 0; text-align: right;"><?php echo formatCurrency($totalEarnings); ?></td>
                    </tr>
                </table>
            </div>
            
            <div>
                <h4 style="color: var(--error-color); margin-bottom: 10px;">Deductions</h4>
                <table style="width: 100%; border-collapse: collapse;">
                    <?php 
                    $totalDeductions = 0;
                    foreach ($details as $detail): 
                        if ($detail['component_type'] === 'deduction'):
                            $totalDeductions += $detail['amount'];
                    ?>
                    <tr>
                        <td style="padding: 5px 0;"><?php echo htmlspecialchars($detail['component_name']); ?></td>
                        <td style="padding: 5px 0; text-align: right;"><?php echo formatCurrency($detail['amount']); ?></td>
                    </tr>
                    <?php 
                        endif;
                    endforeach; 
                    ?>
                    <tr style="border-top: 2px solid var(--border-color); font-weight: 600;">
                        <td style="padding: 8px 0;">Total Deductions</td>
                        <td style="padding: 8px 0; text-align: right;"><?php echo formatCurrency($totalDeductions); ?></td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <div style="margin-top: 30px; padding: 20px; background: #f8fafc; border-radius: 8px;">
        <div style="display: flex; justify-content: space-between; align-items: center;">
            <div>
                <strong style="font-size: 18px;">Net Salary</strong><br>
                <small style="color: var(--text-secondary);">After all deductions</small>
            </div>
            <div style="font-size: 24px; font-weight: 600; color: var(--primary-color);">
                <?php echo formatCurrency($payroll['net_salary']); ?>
            </div>
        </div>
    </div>
</div>

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

