<?php
// PayslipPDFGenerator.php

use Dompdf\Dompdf;

require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';

class PayslipPDFGenerator {

    /**
     * Generates a payslip PDF as a string.
     *
     * @param array $employee Employee data.
     * @param array $payslipData Payslip details.
     * @return string The binary PDF output.
     * @throws Exception If there's an error in PDF generation.
     */
    public function generatePayslipPdf(array $employee, array $payslipData): string {
        try {
            $pdf = new Dompdf();

            $companyName = "MUSANA COMMUNITY DEVELOPMENT ORGANIZATION LTD";
            $companyAddress = "Buseyi Village, Nakalama Sub County, Iganga Uganda";

            // Make sure this path is correct and accessible by Dompdf
            $companyLogoPath = __DIR__ . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'musana-logo-email.png';

            // IMPORTANT: If Dompdf struggles with local file paths, try converting the image to base64
            $logoBase64 = '';
            if (file_exists($companyLogoPath) && is_readable($companyLogoPath)) {
                $type = pathinfo($companyLogoPath, PATHINFO_EXTENSION);
                $data = file_get_contents($companyLogoPath);
                if ($data !== false) {
                    $logoBase64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
                } else {
                    error_log("Failed to read logo file: " . $companyLogoPath);
                }
            } else {
                error_log("Company logo file not found or not readable: " . $companyLogoPath);
            }
            // The image styling itself is handled directly within the img tag now for simplicity
            $logoHtml = $logoBase64 ? '<img src="' . $logoBase64 . '" alt="Company Logo" style="width: 120px; height: auto;">' : ''; // Set specific width here

            // Initialize custom additions and deductions to ensure they are arrays
            $customAdditions = $payslipData['custom_additions'] ?? [];
            $customDeductions = $payslipData['custom_deductions'] ?? [];

            // Build HTML for custom additions
            $customAdditionsHtml = '';
            foreach ($customAdditions as $addition) {
                $description = htmlspecialchars($addition['description'] ?? 'Custom Addition');
                $amount = number_format($addition['amount'] ?? 0, 2);
                $customAdditionsHtml .= '<tr><td>' . $description . '</td><td class="text-right">' . $amount . ' USh</td></tr>';
            }

            // Build HTML for custom deductions
            $customDeductionsHtml = '';
            foreach ($customDeductions as $deduction) {
                $description = htmlspecialchars($deduction['description'] ?? 'Custom Deduction');
                $amount = number_format($deduction['amount'] ?? 0, 2);
                $customDeductionsHtml .= '<tr><td>' . $description . '</td><td class="text-right">' . $amount . ' USh</td></tr>';
            }


            // Output buffering is not needed here as we are returning the PDF string directly
            $html = '
            <!DOCTYPE html>
            <html>
            <head>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
                <title>Payslip - ' . ($employee['employee_name'] ?? 'N/A') . ' - ' . ($payslipData['pay_period_month'] ?? 'N/A') . ' ' . ($payslipData['pay_period_year'] ?? 'N/A') . '</title>
                <style>
                    @page { margin: 20px; }
                    body {
                        font-family: Arial, sans-serif;
                        margin: 0;
                        padding: 0;
                        font-size: 10px;
                        color: #333;
                    }
                    .container {
                        width: 100%;
                        margin: 0 auto;
                        padding: 0px;
                        box-sizing: border-box;
                    }
                    /* REMOVED .header-top, .company-logo, .company-info CSS rules here
                        as they are replaced by table-based layout below */

                    .payslip-title {
                        text-align: left; /* Aligned left, below company info */
                        font-size: 20px;
                        font-weight: bold;
                        color: #000; /* Black color from your first sample */
                        margin: 20px 0 10px 0;
                        clear: both; /* Ensure it clears any previous floats if any elements still use them */
                    }
                    .company-info h1, .company-info p {
                        margin: 0; padding: 0;
                    }

                    .section {
                        margin-bottom: 15px;
                    }
                    .section-header {
                        background-color: #f0f0f0; /* Light gray */
                        color: #333;
                        font-weight: bold;
                        padding: 5px 10px;
                        border-bottom: 1px solid #ccc;
                    }

                    table.info-table {
                        width: 100%;
                        border-collapse: collapse;
                        margin-top: 5px;
                    }
                    table.info-table td {
                        padding: 4px 10px;
                        border: 1px solid #ccc; /* Borders for all cells in employee info */
                    }
                    table.info-table td:nth-child(even) {
                        width: 30%; /* Allocate width for the data column */
                    }
                    table.info-table th { /* Styling for the Employee/Designation/Pay Period header row */
                        background-color: #dbe8f6; /* Light blue similar to sample */
                        font-weight: bold;
                        padding: 6px 10px;
                        border: 1px solid #ccc;
                        text-align: left;
                    }

                    table.data-table {
                        width: 100%;
                        border-collapse: collapse;
                        margin-top: 10px;
                        border: 1px solid #ccc;
                    }
                    table.data-table th, table.data-table td {
                        border: 1px solid #eee;
                        padding: 6px 8px;
                        text-align: left;
                    }
                    table.data-table th {
                        background-color: #f0f0f0;
                        font-weight: bold;
                        font-size: 9.5px;
                    }
                    table.data-table .text-right {
                        text-align: right;
                    }
                    .total-row {
                        background-color: #e0e0e0;
                        font-weight: bold;
                    }
                    .net-salary-box {
                        background-color: #f7faff; /* Light blue background */
                        padding: 10px;
                        margin-top: 20px;
                        text-align: right;
                        font-size: 14px;
                        font-weight: bold;
                        border: 1px solid #0056b3; /* Blue border */
                        overflow: hidden; /* To contain the floated span */
                    }
                    .net-salary-box span {
                        float: left; /* Keep "Net Salary" to the left */
                    }

                    .bank-details {
                        text-align: left; /* Aligned left as in your sample */
                        margin-top: 15px;
                        font-size: 10px;
                    }

                    .footer {
                        text-align: right; /* "Page: 1 / 1" to the right */
                        margin-top: 30px;
                        font-size: 9px;
                        color: #666;
                    }
                </style>
            </head>
            <body>
                <div class="container">
                    <table style="width: 100%; border-collapse: collapse; margin-bottom: 10px;">
                        <tr>
                            <td style="width: 150px; vertical-align: top; padding-right: 15px;">
                                ' . $logoHtml . '
                            </td>
                            <td style="vertical-align: top; text-align: right; font-size: 11px; line-height: 1.4;">
                                <strong>' . $companyName . '</strong><br>
                                ' . $companyAddress . '
                            </td>
                        </tr>
                    </table>

                    <div class="payslip-title">Salary Slip - ' . ($employee['employee_name'] ?? 'N/A') . ' - ' . ($payslipData['pay_period_month'] ?? 'N/A') . ' ' . ($payslipData['pay_period_year'] ?? 'N/A') . '</div>

                    <div class="section">
                        <table class="info-table">
                            <thead>
                                <tr>
                                    <th>Employee</th>
                                    <th>Designation</th>
                                    <th>Pay Period</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>' . ($employee['employee_name'] ?? 'N/A') . '</td>
                                    <td>' . ($employee['designation'] ?? 'N/A') . '</td>
                                    <td>' . ($payslipData['pay_period_start'] ?? 'N/A') . ' - ' . ($payslipData['pay_period_end'] ?? 'N/A') . '</td>
                                </tr>
                                <tr>
                                    <td>Email</td>
                                    <td>Person in charge</td>
                                    <td>Computed on</td>
                                </tr>
                                <tr>
                                    <td>' . ($employee['email'] ?? 'N/A') . '</td>
                                    <td>' . ($employee['person_in_charge'] ?? 'N/A') . '</td>
                                    <td>' . ($payslipData['computed_on'] ?? 'N/A') . '</td>
                                </tr>
                                <tr>
                                    <td>Contract Start Date</td>
                                    <td>Contract Type</td>
                                    <td>Working Schedule</td>
                                </tr>
                                <tr>
                                    <td>' . ($employee['contract_start_date'] ?? 'N/A') . '</td>
                                    <td>' . ($employee['contract_type'] ?? 'N/A') . '</td>
                                    <td>' . ($employee['working_schedule'] ?? 'N/A') . '</td>
                                </tr>
                                <tr>
                                    <td>NSSF NO:</td>
                                    <td>TIN:</td>
                                    <td>Identification:</td>
                                </tr>
                                <tr>
                                    <td>' . ($payslipData['nssf_no'] ?? 'N/A') . '</td>
                                    <td>' . ($payslipData['tin_no'] ?? 'N/A') . '</td>
                                    <td>' . ($employee['nin'] ?? 'N/A') . '</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <div class="section-header">Attendance</div>
                    <div class="section">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>NAME</th>
                                    <th class="text-right">NUMBER OF HOURS</th>
                                    <th class="text-right">NUMBER OF DAYS</th>
                                    <th class="text-right">AMOUNT</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>Attendance</td>
                                    <td class="text-right">' . ($payslipData['attendance_hours'] ?? 'N/A') . '</td>
                                    <td class="text-right">' . ($payslipData['attendance_days'] ?? 'N/A') . '</td>
                                    <td class="text-right">' . number_format($payslipData['attendance_amount'] ?? 0, 2) . ' USh</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <div class="section-header">Earnings</div>
                    <div class="section">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>NAME</th>
                                    <th class="text-right">AMOUNT</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr><td>Basic Salary</td><td class="text-right">' . number_format($payslipData['basic_salary'] ?? 0, 2) . ' USh</td></tr>
                                <tr><td>Facilitation Allowance</td><td class="text-right">' . number_format($payslipData['facilitation_allowance'] ?? 0, 2) . ' USh</td></tr>
                                <tr><td>Transport Allowance</td><td class="text-right">' . number_format($payslipData['transport_allowance'] ?? 0, 2) . ' USh</td></tr>
                                <tr><td>Housing Allowance</td><td class="text-right">' . number_format($payslipData['housing_allowance'] ?? 0, 2) . ' USh</td></tr>
                                <tr><td>Other Allowances</td><td class="text-right">' . number_format($payslipData['other_allowances_total'] ?? 0, 2) . ' USh</td></tr>
                                ' . $customAdditionsHtml . ' <tr class="total-row"><td>GROSS PAY</td><td class="text-right">' . number_format($payslipData['gross_pay'] ?? 0, 2) . ' USh</td></tr>
                            </tbody>
                        </table>
                    </div>

                    <div class="section-header">Deductions</div>
                    <div class="section">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>NAME</th>
                                    <th class="text-right">AMOUNT</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr><td>NSSF Employee Contribution (5%)</td><td class="text-right">' . number_format($payslipData['nssf_5_percent'] ?? 0, 2) . ' USh</td></tr>
                                <tr><td>PAYE (Income Tax)</td><td class="text-right">' . number_format($payslipData['paye'] ?? 0, 2) . ' USh</td></tr>
                                <tr><td>Local Service Tax (LST)</td><td class="text-right">' . number_format($payslipData['local_service_tax'] ?? 0, 2) . ' USh</td></tr>
                                <tr><td>Advance Deduction</td><td class="text-right">' . number_format($payslipData['advance_deduction'] ?? 0, 2) . ' USh</td></tr>
                                <tr><td>Other Deductions</td><td class="text-right">' . number_format($payslipData['other_deductions_total'] ?? 0, 2) . ' USh</td></tr>
                                ' . $customDeductionsHtml . ' <tr class="total-row"><td>TOTAL DEDUCTIONS</td><td class="text-right">' . number_format($payslipData['total_deductions'] ?? 0, 2) . ' USh</td></tr>
                            </tbody>
                        </table>
                    </div>

                    <div class="section-header">Employer Contributions / Other Info</div>
                    <div class="section">
                        <table class="data-table">
                            <tbody>
                                <tr><td>Taxable Income</td><td class="text-right">' . number_format($payslipData['taxable_income'] ?? 0, 2) . ' USh</td></tr>
                                <tr><td>NSSF Employer Contribution (10%)</td><td class="text-right">' . number_format($payslipData['nssf_10_percent'] ?? 0, 2) . ' USh</td></tr>
                            </tbody>
                        </table>
                    </div>

                    <div class="net-salary-box">
                        <span>Net Salary</span>
                        ' . number_format($payslipData['net_salary'] ?? 0, 2) . ' USh
                    </div>

                    <div class="bank-details">
                        To pay on ' . ($employee['ac_no'] ?? 'N/A') . ' - ' . ($employee['bank_name'] ?? 'N/A') . ' Bank of ' . ($employee['ac_name'] ?? 'N/A') . ': ' . number_format($payslipData['net_salary'] ?? 0, 2) . ' USh
                    </div>

                    <div class="footer">
                        Page: 1 / 1
                    </div>
                </div>
            </body>
            </html>';

            $pdf->loadHtml($html);
            $pdf->setPaper('A4', 'portrait');
            $pdf->render();
            return $pdf->output();

        } catch (Exception $e) {
            error_log("PDF generation failed: " . $e->getMessage());
            throw $e; // Re-throw the exception after logging
        }
    }

    /**
     * Helper to generate a safe filename for the payslip PDF.
     *
     * @param array $employee Employee data.
     * @param array $payslipData Payslip details.
     * @return string
     */
    public function getPayslipFilename(array $employee, array $payslipData): string {
        $safeEmployeeName = preg_replace('/[^a-zA-Z0-9_\-.]/', '_', $employee['employee_name'] ?? 'Employee');
        $month = $payslipData['pay_period_month'] ?? date('F');
        $year = $payslipData['pay_period_year'] ?? date('Y');
        return "Payslip---Salary-Slip---{$safeEmployeeName}---{$month}-{$year}.pdf";
    }
}