<?php
// Assumes $conn (database connection) and $_SESSION['user_id'] are available from admin_dashboard.php
$salary_table = 'employee_salary'; 
$history_table = 'payslip_history'; // New table for logging generated payslips
$status_message = '';
$generated_content = null; 

// Initialize employee name variable
$employee_name = ''; // Will be populated from DB

// --- Fixed Company and Document Details (Green Box) ---
$fixed_company_info = [
    'logo_url' => 'assets/images/cyberlog_logo_placeholder.png', // Update this path
    'company_name' => 'Cyberlog',
    'address' => '1/6, Block: New-C, Mirpur-1, Dhaka-1216',
    'email' => 'info@cyberlog.com.bd',
    'website' => 'www.cyberlog.com.bd',
];

$fixed_text_top = "Dear [Username], Please see your pay slip for the month(s) of:";
$fixed_text_bottom_1 = "NET PAYABLE (IN WORDS)";
$fixed_text_bottom_2 = "This is a computer-generated statement and hence does not require any signature.";

// Function to convert number to words (Simplified for Taka/Dollars)
function convert_number_to_words($number) {
    $hyphen      = '-';
    $conjunction = ' and ';
    $separator   = ', ';
    $negative    = 'negative ';
    $decimal     = ' point ';
    $dictionary  = array(
        0                   => 'zero',
        1                   => 'one',
        2                   => 'two',
        3                   => 'three',
        4                   => 'four',
        5                   => 'five',
        6                   => 'six',
        7                   => 'seven',
        8                   => 'eight',
        9                   => 'nine',
        10                  => 'ten',
        11                  => 'eleven',
        12                  => 'twelve',
        13                  => 'thirteen',
        14                  => 'fourteen',
        15                  => 'fifteen',
        16                  => 'sixteen',
        17                  => 'seventeen',
        18                  => 'eighteen',
        19                  => 'nineteen',
        20                  => 'twenty',
        30                  => 'thirty',
        40                  => 'fourty',
        50                  => 'fifty',
        60                  => 'sixty',
        70                  => 'seventy',
        80                  => 'eighty',
        90                  => 'ninety',
        100                 => 'hundred',
        1000                => 'thousand',
        1000000             => 'million',
        1000000000          => 'billion',
        1000000000000       => 'trillion',
        1000000000000000    => 'quadrillion',
        1000000000000000000 => 'quintillion'
    );
    
    if (!is_numeric($number)) {
        return false;
    }
    
    if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) {
        // overflow
        trigger_error(
            'convert_number_to_words only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX,
            E_USER_WARNING
        );
        return false;
    }

    if ($number < 0) {
        return $negative . convert_number_to_words(abs($number));
    }
    
    $result = $fraction = null;
    
    if (strpos($number, '.') !== false) {
        list($number, $fraction) = explode('.', $number);
    }
    
    switch (true) {
        case $number < 21:
            $result = $dictionary[(int)$number];
            break;
        case $number < 100:
            $ten = ((int)($number / 10)) * 10;
            $unit = $number % 10;
            $result = $dictionary[$ten];
            if ($unit) {
                $result .= $hyphen . $dictionary[$unit];
            }
            break;
        case $number < 1000:
            $hundred = (int)($number / 100);
            $remainder = $number % 100;
            $result = $dictionary[$hundred] . ' ' . $dictionary[100];
            if ($remainder) {
                $result .= $conjunction . convert_number_to_words($remainder);
            }
            break;
        default:
            $baseUnit = pow(1000, floor(log($number, 1000)));
            $numBaseUnits = (int)($number / $baseUnit);
            $remainder = $number % $baseUnit;
            $result = convert_number_to_words($numBaseUnits) . ' ' . $dictionary[$baseUnit];
            if ($remainder) {
                $result .= $remainder < 100 ? $conjunction : $separator;
                $result .= convert_number_to_words($remainder);
            }
            break;
    }
    
    if (null !== $fraction && is_numeric($fraction)) {
        $result .= $decimal;
        $words = array();
        foreach (str_split((string) $fraction) as $number) {
            $words[] = $dictionary[$number];
        }
        $result .= implode(' ', $words);
    }
    
    return $result;
}


// --- FUNCTION: Builds the PAY SLIP HTML ---
/**
 * @param array $data The employee salary data fetched from the DB.
 * @param string $month_year The month and year for the payslip (e.g., "January 2024").
 * @param string $employee_name The name/username of the employee.
 * @param array $company_info Fixed company details.
 * @param string $text_top Template text for the top.
 * @param string $text_bottom_1 Template text for the net payable in words.
 * @param string $text_bottom_2 Template text for the footer note.
 * @return string The complete HTML content for the payslip.
 */
function get_payslip_html(
    $data, 
    $month_year, 
    $employee_name, // <-- EMPLOYEE NAME ADDED/CONFIRMED HERE
    $company_info, 
    $text_top, 
    $text_bottom_1, 
    $text_bottom_2
) {
    // Basic Calculations (Assuming data fields exist and are numeric)
    $basic_salary = $data['basic_salary'] ?? 0;
    $house_rent = $data['house_rent'] ?? 0;
    $medical_allowance = $data['medical_allowance'] ?? 0;
    $other_allowance = $data['other_allowance'] ?? 0;
    $pf_contribution = $data['pf_contribution'] ?? 0;
    $tax_deduction = $data['tax_deduction'] ?? 0;

    $total_earnings = $basic_salary + $house_rent + $medical_allowance + $other_allowance;
    $total_deductions = $pf_contribution + $tax_deduction;
    $net_payable = $total_earnings - $total_deductions;

    // --- Content Formatting ---
    $month_year_display = htmlspecialchars($month_year);
    $text_top_content = str_replace('[Username]', htmlspecialchars($employee_name), $text_top); // <-- USES RETRIEVED USERNAME

    // Convert net payable to words
    $net_payable_words = ucwords(convert_number_to_words($net_payable));
    $net_payable_text = htmlspecialchars("{$text_bottom_1}: {$net_payable_words} Taka Only");
    
    // Employee Details
    $employee_details = [
        'Employee ID' => $data['id'] ?? 'N/A',
        'Designation' => $data['designation'] ?? 'N/A',
        'Department' => $data['department'] ?? 'N/A',
        'Date of Joining' => $data['date_of_joining'] ?? 'N/A',
        'Bank Account' => $data['bank_account_no'] ?? 'N/A',
        'Payment Mode' => $data['payment_mode'] ?? 'N/A',
    ];

    // --- HTML STRUCTURE ---

    $html = <<<HTML
    <div class="payslip-page" id="printContent">
        <header style="border-bottom: 4px solid #3498db; padding-bottom: 10px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
            <div>
                <img src="{$company_info['logo_url']}" alt="Company Logo" style="max-width: 150px; height: auto; display: block; margin-bottom: 10px;">
                <h1 style="color: #3498db; margin: 0; font-size: 1.5em;">{$company_info['company_name']}</h1>
            </div>
            <div style="text-align: right; font-size: 0.9em; line-height: 1.4;">
                <strong style="color: #333;">Pay Slip for: {$month_year_display}</strong><br>
                {$company_info['address']}<br>
                Email: {$company_info['email']} | Web: {$company_info['website']}
            </div>
        </header>

        <section style="margin-bottom: 20px; padding: 10px; background-color: #ecf0f1; border-radius: 5px;">
            <p style="margin: 0; font-weight: bold; color: #2c3e50;">{$text_top_content}</p>
        </section>

        <!-- Employee and Payslip Details Table -->
        <table style="margin-bottom: 20px;">
            <thead>
                <tr>
                    <th colspan="2" style="text-align: left; background-color: #3498db; color: white;">Employee Details</th>
                    <th colspan="2" style="text-align: left; background-color: #3498db; color: white;">Payslip Information</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><strong>Name:</strong></td>
                    <td>{$employee_name}</td>
                    <td><strong>Month & Year:</strong></td>
                    <td>{$month_year_display}</td>
                </tr>
                <tr>
                    <td><strong>Employee ID:</strong></td>
                    <td>{$employee_details['Employee ID']}</td>
                    <td><strong>Designation:</strong></td>
                    <td>{$employee_details['Designation']}</td>
                </tr>
                <tr>
                    <td><strong>Department:</strong></td>
                    <td>{$employee_details['Department']}</td>
                    <td><strong>Date of Joining:</strong></td>
                    <td>{$employee_details['Date of Joining']}</td>
                </tr>
                <tr>
                    <td><strong>Bank Account:</strong></td>
                    <td>{$employee_details['Bank Account']}</td>
                    <td><strong>Payment Mode:</strong></td>
                    <td>{$employee_details['Payment Mode']}</td>
                </tr>
            </tbody>
        </table>


        <!-- Earnings and Deductions Table -->
        <table style="width: 100%;">
            <thead>
                <tr style="background-color: #7f8c8d; color: white;">
                    <th style="width: 30%; text-align: left;">EARNINGS</th>
                    <th style="width: 20%;">AMOUNT (TK)</th>
                    <th style="width: 30%; text-align: left;">DEDUCTIONS</th>
                    <th style="width: 20%;">AMOUNT (TK)</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td style="text-align: left;">Basic Salary</td>
                    <td style="text-align: right;">{$basic_salary}</td>
                    <td style="text-align: left;">Provident Fund Contribution</td>
                    <td style="text-align: right;">{$pf_contribution}</td>
                </tr>
                <tr>
                    <td style="text-align: left;">House Rent Allowance</td>
                    <td style="text-align: right;">{$house_rent}</td>
                    <td style="text-align: left;">Tax Deduction</td>
                    <td style="text-align: right;">{$tax_deduction}</td>
                </tr>
                <tr>
                    <td style="text-align: left;">Medical Allowance</td>
                    <td style="text-align: right;">{$medical_allowance}</td>
                    <td style="text-align: left;">&nbsp;</td>
                    <td style="text-align: right;">0</td>
                </tr>
                <tr>
                    <td style="text-align: left;">Other Allowance</td>
                    <td style="text-align: right;">{$other_allowance}</td>
                    <td style="text-align: left;">&nbsp;</td>
                    <td style="text-align: right;">0</td>
                </tr>
            </tbody>
            <tfoot>
                <tr style="background-color: #f2f2f2; font-weight: bold;">
                    <td style="text-align: left;">TOTAL EARNINGS</td>
                    <td style="text-align: right;">{$total_earnings}</td>
                    <td style="text-align: left;">TOTAL DEDUCTIONS</td>
                    <td style="text-align: right;">{$total_deductions}</td>
                </tr>
            </tfoot>
        </table>

        <!-- Summary -->
        <div style="margin-top: 30px; border: 2px solid #3498db; padding: 15px; border-radius: 5px;">
            <p style="margin: 0; font-size: 1.1em; font-weight: bold; color: #2c3e50;">
                NET PAYABLE: <span style="float: right; color: #e74c3c;">{$net_payable} TK</span>
            </p>
        </div>
        
        <div style="margin-top: 15px; padding: 10px; background-color: #ecf0f1; border-radius: 5px;">
            <p style="margin: 0; font-style: italic; color: #2c3e50;">
                {$net_payable_text}
            </p>
        </div>

        <footer style="margin-top: 50px; text-align: center; font-size: 0.8em; color: #7f8c8d;">
            <p>{$text_bottom_2}</p>
        </footer>
    </div>
HTML;

    return $html;
}


// --- Main Script Logic (Handles Form Submission) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['employee_id'], $_POST['month_year'])) {
    if (!isset($conn)) {
        $status_message = "<div class='error-message'>Error: Database connection not available.</div>";
    } else {
        $employee_id = filter_var($_POST['employee_id'], FILTER_SANITIZE_NUMBER_INT);
        $month_year = filter_var($_POST['month_year'], FILTER_SANITIZE_STRING);
        
        // 1. Fetch Employee Salary Data
        $query = "SELECT * FROM {$salary_table} WHERE id = ? LIMIT 1";
        $stmt = $conn->prepare($query);

        if ($stmt === false) {
            $status_message = "<div class='error-message'>Database Prepare Error: " . $conn->error . "</div>";
        } else {
            $stmt->bind_param("i", $employee_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $employee_data = $result->fetch_assoc();
            $stmt->close();

            if ($employee_data) {
                // --- CRITICAL FIX: Use the 'username' field for the employee's name ---
                $employee_name = $employee_data['username'] ?? 'Employee Name Not Found'; 
                
                // 2. Generate Payslip
                $generated_content = get_payslip_html(
                    $employee_data, 
                    $month_year, 
                    $employee_name, // <-- Passing the retrieved username
                    $fixed_company_info, 
                    $fixed_text_top, 
                    $fixed_text_bottom_1, 
                    $fixed_text_bottom_2
                );

                // 3. Log to History (Optional but good practice)
                // This part is skipped for brevity/focus, but would go here in a full app.

                $status_message = "<div class='success-message'>Payslip successfully generated for {$employee_name}.</div>";
            } else {
                $status_message = "<div class='error-message'>Error: Employee ID '{$employee_id}' not found in salary table.</div>";
            }
        }
    }
}


// --- FUNCTION: Renders the Payslip Form ---
function render_payslip_form($conn, $salary_table, $status_message) {
    // Fetch list of employees (ID and Username) for the dropdown
    $employees = [];
    if (isset($conn)) {
        $employee_query = "SELECT employee_id, username FROM {$salary_table} ORDER BY username ASC";
        $employee_result = $conn->query($employee_query);
        if ($employee_result) {
            while ($row = $employee_result->fetch_assoc()) {
                $employees[] = $row;
            }
        }
    }

    echo "<h3>Generate Employee Pay Slip</h3>";
    
    if ($status_message) {
        echo $status_message;
    }

    echo "<form method='POST' class='document-form'>";

    echo "<div class='form-group'>";
    echo "<label for='employee_id'>Select Employee:</label>";
    echo "<select id='employee_id' name='employee_id' required>";
    echo "<option value=''>-- Select Employee --</option>";
    foreach ($employees as $employee) {
        echo "<option value='" . htmlspecialchars($employee['id']) . "'>" . htmlspecialchars($employee['username']) . " (ID: " . htmlspecialchars($employee['id']) . ")</option>";
    }
    echo "</select>";
    echo "</div>";

    echo "<div class='form-group'>";
    echo "<label for='month_year'>Month & Year (e.g., January 2024):</label>";
    echo "<input type='text' id='month_year' name='month_year' placeholder='e.g., January 2024' required>";
    echo "</div>";

    echo "<button type='submit' class='btn-primary'>Generate Payslip</button>";
    echo "</form>";
}
?>

<style>
    /* Basic Styling for the form and card (will be inherited from admin_dashboard.php) */
    .document-form {
        max-width: 600px;
        margin: 20px auto;
        padding: 20px;
        border: 1px solid #ddd;
        border-radius: 8px;
        background-color: #fff;
    }
    .form-group {
        margin-bottom: 15px;
    }
    .form-group label {
        display: block;
        margin-bottom: 5px;
        font-weight: bold;
        color: #333;
    }
    .document-form input[type="text"],
    .document-form select {
        width: 100%;
        padding: 10px;
        border: 1px solid #ccc;
        border-radius: 4px;
        box-sizing: border-box;
    }
    .btn-primary {
        background-color: #3498db;
        color: white;
        padding: 10px 20px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 1em;
        transition: background-color 0.3s;
    }
    .btn-primary:hover {
        background-color: #2980b9;
    }
    .error-message {
        color: #e74c3c;
        background-color: #fbecec;
        padding: 10px;
        border: 1px solid #e74c3c;
        border-radius: 4px;
        margin-bottom: 15px;
    }
    .success-message {
        color: #27ae60;
        background-color: #e8f9f1;
        padding: 10px;
        border: 1px solid #27ae60;
        border-radius: 4px;
        margin-bottom: 15px;
    }

    /* Print/Payslip Specific Styles (for display and print) */
    .payslip-page {
        max-width: 800px; /* A4 width */
        margin: 40px auto;
        border: 1px solid #ddd;
        padding: 20px;
        background-color: white;
        box-shadow: 0 0 10px rgba(0,0,0,0.1);
    }
    .payslip-page table {
        font-size: 0.9em;
        table-layout: fixed;
    }
    .payslip-page table th, .payslip-page table td { 
        border: 1px solid #aaa; /* Slightly lighter border for display */
        padding: 8px; 
    }
</style>

<div class="form-card">
    <?php if ($generated_content === null) : ?>
        <!-- Display the form if content is not yet generated -->
        <?php render_payslip_form($conn ?? null, $salary_table, $status_message); ?>
    <?php else : ?>
        <!-- Display the generated content and print button -->
        <h3 style="text-align: center;">Generated Pay Slip for <?php echo htmlspecialchars($employee_name); ?></h3>
        
        <?php echo $status_message; ?>

        <div class="payslip-output-container">
            <?php echo $generated_content; ?>
        </div>

        <button onclick="printPayslip()" class="btn-primary" style="margin-top: 20px;">Print / Download PDF</button>

        <!-- Script to handle printing -->
        <script>
        function printPayslip() {
            const printContent = document.getElementById('printContent').outerHTML;
            const printWindow = window.open('', '', 'height=800,width=800');
            
            printWindow.document.write('<html><head><title>Pay Slip - <?php echo $employee_name . ' (' . ($month_year ?? 'Month') . ')'; ?></title>');
            
            // --- IMPORTANT: Include all CSS styles necessary for a proper PDF layout ---
            printWindow.document.write(`
                <style>
                    body { font-family: Arial, sans-serif; margin: 0; padding: 0; }
                    .payslip-page {
                        position: relative;
                        padding: 40px; 
                        background: white;
                        min-height: 1100px; /* A4 size approximation */
                        box-sizing: border-box;
                        width: 100%;
                        font-size: 10pt;
                    }
                    .payslip-page h1, .payslip-page h2 { color: #333; }
                    .payslip-page table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
                    /* Ensure all borders are visible in print */
                    .payslip-page table th, .payslip-page table td { 
                        border: 1px solid #333 !important; 
                        padding: 8px; 
                        font-size: 10pt;
                    }
                    .payslip-page table thead tr { background-color: #f2f2f2; }
                    .payslip-page img { max-width: 150px; height: auto; display: block; }
                </style>
            `);
            printWindow.document.write('</head><body>');
            printWindow.document.write('<div class="print-container">'); // Wrap content for print media query
            printWindow.document.write(printContent);
            printWindow.document.write('</div>');
            printWindow.document.write('</body></html>');
            printWindow.document.close();
            printWindow.print();
        }
        </script>
    <?php endif; ?>
</div>
