<?php
// Assumes $conn (database connection) and $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role'] are available from admin_dashboard.php
// NOTE: Ensure 'config/db_connection.php' is properly included in admin_dashboard.php 

// Check if user session data is available
if (!isset($_SESSION['user_id'])) {
    // Fallback or redirection logic if not logged in
    echo "<p class='error'>User not authenticated. Please log in.</p>";
    return;
}

$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['username'] ?? 'Employee Name'; // Use session username
$user_role = $_SESSION['role'] ?? 'Unspecified Role'; // Use session role

$status_message = '';
$generated_content = null;

// --- Fixed Company and Document Details ---
$company_name = "Cyberlog";
$company_address = "1/6, Block: New-C, Mirpur-1, Dhaka-1216";
$company_email = "info@cyberlog.com.bd";
$company_website = "www.cyberlog.com.bd";
$logo_path = "assets/images/cyberlog_logo_placeholder.png"; // Placeholder path
$signature_path = "Signature of Hridoy Mustofa.png"; // Placeholder path

// --- Utility Function: Convert Number to Words ---
if (!function_exists('convert_number_to_words')) {
    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                  => 'forty', 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));
        }

        $string = $fraction = null;

        if (strpos($number, '.') !== false) {
            list($number, $fraction) = explode('.', $number);
        }

        switch (true) {
            case $number < 21:
                $string = $dictionary[(int)$number];
                break;
            case $number < 100:
                $tens   = ((int)($number / 10)) * 10;
                $units  = $number % 10;
                $string = $dictionary[$tens];
                if ($units) {
                    $string .= $hyphen . $dictionary[$units];
                }
                break;
            case $number < 1000:
                $hundreds  = (int)($number / 100);
                $remainder = $number % 100;
                $string = $dictionary[$hundreds] . ' ' . $dictionary[100];
                if ($remainder) {
                    $string .= $conjunction . convert_number_to_words($remainder);
                }
                break;
            default:
                $baseUnit = pow(1000, $i = floor(log($number, 1000)));
                $numBaseUnit = (int)($number / $baseUnit);
                $remainder = $number % $baseUnit;
                $string = convert_number_to_words($numBaseUnit) . ' ' . $dictionary[$baseUnit];
                if ($remainder) {
                    $string .= $remainder < 100 ? $conjunction : $separator;
                    $string .= convert_number_to_words($remainder);
                }
                break;
        }

        if (null !== $fraction && is_numeric($fraction)) {
            $string .= $decimal;
            for ($i = 0; $i < strlen($fraction); $i++) {
                $string .= $dictionary[$fraction[$i]] . ' ';
            }
        }

        return ucwords(trim($string));
    }
}


/**
 * Fetches salary data for the last 12 months (including the current month)
 * and generates the HTML certificate content.
 * @param int $user_id The ID of the employee.
 * @param mysqli $conn The database connection object.
 * @param string $user_name The name of the employee.
 * @param string $user_role The role of the employee.
 * @param array $company_info Fixed company details.
 * @param string $logo_path Path to the company logo.
 * @param string $signature_path Path to the signature image.
 * @return string The generated HTML content.
 */
function generate_salary_certificate_html($user_id, $conn, $user_name, $user_role, $company_info, $logo_path, $signature_path) {
    global $status_message; // Allow setting status message inside function if DB error occurs
    
    // --- 1. Define the 12-month period (Current month and 11 preceding months) ---
    $salary_data_map = []; // Map to hold month_year => salary_amount
    $total_salary = 0.00;
    
    // Generate an array of the last 12 months (YYYY-MM-01 format)
    $month_list = [];
    $today = new DateTime('first day of this month');
    
    for ($i = 0; $i < 12; $i++) {
        $month_date = clone $today;
        $month_date->modify("-$i months");
        $month_list[$month_date->format('Y-m-01')] = $month_date->format('F Y');
    }
    
    // Reverse the list to display in order from 12 months back to current month
    $month_list = array_reverse($month_list);

    // --- 2. Database Query (Fetch existing salary data) ---
    $month_start_dates = array_keys($month_list);
    $placeholders = implode(',', array_fill(0, count($month_start_dates), '?'));
    
    // Using 'salary_month' and 'gross_salary' columns, which matches the table structure provided.
    // NOTE: DATE_FORMAT in MySQL is used to match the PHP-generated month_key strings.
    $sql = "SELECT gross_salary, salary_month, salary_year 
            FROM employee_salary 
            WHERE user_id = ? 
            ORDER BY salary_year ASC, salary_month ASC";

    $stmt = $conn->prepare($sql);
    
    // Bind parameters: 1 integer for user_id
    $stmt->bind_param('i', $user_id);

    if ($stmt->execute()) {
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            // Reconstruct the key to match PHP's expected format (YYYY-MM-01) for lookup
            $month_key = date('Y-m-01', mktime(0, 0, 0, $row['salary_month'], 1, $row['salary_year']));
            $salary_data_map[$month_key] = (float)$row['gross_salary'];
        }
    } else {
        $status_message = "<p class='error'>Error fetching salary data from DB. Query failed: " . htmlspecialchars($stmt->error) . "</p>";
    }
    $stmt->close();


    // --- 3. Build the Salary Table Rows and Calculate Total ---
    $table_data_rows = '';
    
    foreach ($month_list as $month_key => $month_name) {
        $amount = $salary_data_map[$month_key] ?? null;
        
        $table_data_rows .= "<tr>";
        // Format the month name to match the template (e.g., Nov-24)
        $month_short_year = substr($month_name, 0, 3) . '-' . substr($month_name, -2);
        $table_data_rows .= "<td class='month-cell'>{$month_short_year}</td>";
        
        if ($amount !== null) {
            $amount_formatted = number_format($amount, 2);
            $table_data_rows .= "<td class='total-payment-data'>...</td>"; // Total Payment - Placeholder (Red box)
            $table_data_rows .= "<td class='amount-data'>{$amount_formatted}</td>"; // Amount in BDT (Red box)
            $total_salary += $amount;
        } else {
            $table_data_rows .= "<td class='amount-data no-salary' colspan='2'>No salary generated this month</td>";
        }
        $table_data_rows .= "</tr>";
    }

    $total_salary_in_words = convert_number_to_words($total_salary);
    $total_salary_formatted = number_format($total_salary, 2);


    // --- 4. Generate the HTML Content ---
    
    $certificate_date = date('d.m.Y'); // Template uses DD.MM.YYYY format
    $user_name_upper = strtoupper(htmlspecialchars($user_name));
    $user_role_upper = strtoupper(htmlspecialchars($user_role));

    // 1 & 2. REMOVED ** and used regular text, ensuring proper spacing.
    $body_text = "This is to certify that {$user_name_upper} has been working in our company, {$company_info['company_name']} as a {$user_role_upper} to till date. The salary details for the last 12 months are provided below:";
    
    // Fixed Final Text
    $closing_text = "This Financial certificate is being issued to him on his request.";
    $footer_note = "This is a computer-generated document. No signature is required. {$company_info['company_name']} Ltd.";
    

    $html = <<<HTML
    <div class="certificate-page">
        <!-- FIXED HEADER SECTION -->
        <header class="fixed-header">
            <div class="logo-container">
                <img src="{$logo_path}" alt="{$company_info['company_name']} Logo" class="company-logo">
            </div>
            <div class="address-block">
                <p class="company-info-name">{$company_info['company_name']}</p>
                <p class="company-info-address">{$company_info['address']}</p>
                <p class="company-info-email">Email: {$company_info['email']}</p>
                <p class="company-info-website">Website: {$company_info['website']}</p>
            </div>
        </header>
        
        <div class="header-separator"></div>

        <!-- DATE AND TITLE SECTION -->
        <div class="date-title-section">
            <div class="date-block">
                <span class="date-label">Date:</span> 
                <span class="date-value">{$certificate_date}</span>
            </div>
            
            <!-- 1. REMOVED BOX FROM TITLE -->
            <h1 class="certificate-title-unboxed">TO WHOM IT MAY CONCERN</h1>
        </div>
        
        <!-- FIXED BODY TEXT -->
        <div class="certificate-body">
            <p class="body-text">{$body_text}</p>
        </div>

        <!-- SALARY TABLE -->
        <div class="salary-table-container">
            <table>
                <thead>
                    <tr>
                        <th class="month-header">Month</th>
                        <th class="payment-header">Total Payment</th>
                        <th class="amount-header">Amount in BDT</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- DYNAMIC MONTH ROWS -->
                    {$table_data_rows}
                    
                    <!-- TOTAL ROW (Now a regular table row for structure) -->
                    <tr class="total-row-summary">
                        <td class="total-label-cell" colspan="2">Total</td>
                        <td class="total-amount-cell">{$total_salary_formatted}</td>
                    </tr>
                    
                    <!-- 4. NEW ROW FOR IN WORDS (Single merged cell) -->
                    <tr class="in-words-row-table">
                        <td colspan="3" class="in-words-cell">
                            <span class="in-words-label">In words:</span> 
                            <span class="in-words-value">{$total_salary_in_words}</span> 
                            <span class="taka-only-text">Taka Only</span>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <!-- CLOSING TEXT -->
        <div class="closing-section">
            <p class="closing-text">{$closing_text}</p>
        </div>
        
        <!-- FOOTER NOTE -->
        <p class="footer-note">{$footer_note}</p>
    </div>
HTML;

    return $html;
}

// Check for required environment variables/objects
if (!isset($conn)) {
    $status_message = "<p class='error'>Database connection (\$conn) is not available. Please ensure 'config/db_connection.php' is included.</p>";
} else {
    // Collect all company info for the function call
    $company_info = [
        'company_name' => $company_name,
        'address' => $company_address,
        'email' => $company_email,
        'website' => 'www.cyberlog.com.bd', // Use fixed value
    ];
    $generated_content = generate_salary_certificate_html($user_id, $conn, $user_name, $user_role, $company_info, $logo_path, $signature_path);
}

// --- HTML/CSS for Display and Print Preparation ---
?>

<style>
    /* Styling for the form and card (will be inherited from admin_dashboard.php) */
    .form-card {
        padding: 0; /* Remove internal padding to allow certificate to fill card width */
    }

    /* Print/Certificate Specific Styles */
    .certificate-page {
        /* Set page size properties for both display and printing */
        max-width: 210mm; /* A4 width */
        min-height: 297mm; /* A4 height */
        margin: 0 auto; /* Center on screen */
        padding: 30px 40px; /* Internal padding */
        background: white;
        box-sizing: border-box;
        box-shadow: 0 0 10px rgba(0,0,0,0.1); /* Shadow for screen display */
        font-family: 'Arial', sans-serif;
        line-height: 1.6;
        font-size: 11pt;
    }

    /* Header Styling */
    .fixed-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        padding-bottom: 10px;
    }
    .company-logo { 
        max-width: 150px; 
        height: auto; 
    }
    .address-block {
        text-align: right;
        font-size: 10pt;
        color: #555;
        line-height: 1.4;
    }
    .address-block p { margin: 0; padding: 0; }
    .company-info-name { 
        margin-top: 0 !important; 
        font-weight: bold;
        color: #000;
        font-size: 1.1em;
    }

    .header-separator {
        border-bottom: 2px solid #000;
        margin-bottom: 20px;
    }

    /* Date and Title */
    .date-title-section {
        margin-top: 20px;
    }
    .date-block {
        text-align: right;
        margin-bottom: 30px;
        font-weight: bold;
        font-size: 10pt;
    }
    /* 1. Unboxed Title Style */
    .certificate-title-unboxed {
        text-align: center;
        font-size: 1.4em;
        font-weight: 700;
        color: #000;
        padding: 5px 0;
        margin: 0 auto;
        width: 70%;
    }

    /* Body Text */
    .certificate-body {
        margin-top: 40px;
        margin-bottom: 20px;
        text-align: justify;
    }
    .body-text {
        font-size: 11pt;
    }
    .body-text strong {
        /* This keeps the dynamic data bold but removes the extra text decoration */
        font-weight: bold;
    }


    /* Table Styling */
    .salary-table-container {
        margin: 30px auto;
        width: 90%; 
    }
    .salary-table-container table { 
        width: 100%; 
        border-collapse: collapse; 
        border: 1px solid #000; /* Outer border */
        font-size: 13pt; /* 3. Made table font size larger (Increased to 13pt) */
        line-height: 1.2;
    }
    .salary-table-container table th, 
    .salary-table-container table td { 
        border: 1px solid #333; /* Inner borders */
        padding: 8px 10px; 
        height: 30px; /* Ensure visual height for empty cells */
    }
    .salary-table-container table thead tr { 
        background-color: #ddd; 
    }
    .month-header { width: 30%; }
    .payment-header { width: 35%; text-align: left; }
    .amount-header { width: 35%; text-align: right; }
    .month-cell { text-align: left; }
    .total-payment-data { text-align: left; }
    .amount-data { text-align: right; }
    .no-salary { 
        text-align: center !important; 
        color: #777; 
        font-style: italic; 
    }

    /* Total Summary Row Style */
    .total-row-summary {
        font-weight: bold;
    }
    .total-row-summary .total-label-cell {
        text-align: left !important;
        border-right: none !important;
        background-color: #fff;
    }
    .total-payment-cell, .total-amount-cell {
        text-align: right !important;
        background-color: #fff;
    }
    .total-payment-cell { 
        text-align: left !important;
        border-left: none !important;
    }
    /* Total box styling */
    .total-row-summary .total-label-cell {
        width: 30%;
        border-bottom: 2px double #000 !important;
    }
    .total-row-summary .total-payment-cell {
        width: 35%;
        border-bottom: 2px double #000 !important;
        border-left: 1px solid #333 !important;
    }
    .total-row-summary .total-amount-cell {
        width: 35%;
        border-bottom: 2px double #000 !important;
    }


    /* 4 & 5. In Words Row - Single line structure WITHIN THE TABLE */
    .in-words-row-table {
        background-color: #fcfcfc;
    }
    .in-words-cell {
        text-align: left !important;
        font-size: 11pt; /* Use smaller font for this row */
        padding: 5px 10px !important;
        border-top: none !important; /* Remove top border of the cell */
        border-bottom: none !important;
        
        /* Layout adjustments for single sentence */
        display: flex; 
        align-items: center;
        justify-content: flex-start;
    }
    .in-words-label {
        font-style: italic;
        font-weight: bold;
        text-decoration: none;
        padding-right: 5px;
    }
    .words-value {
        font-weight: normal;
        padding-left: 5px;
        flex-grow: 1;
        border-left: 1px solid #000;
        padding-left: 10px;
    }
    .taka-only-text {
        font-weight: bold;
        border-left: 1px solid #000;
        padding-left: 10px;
    }
    
    /* Footer / Closing Text Layout */
    .closing-text {
        margin-top: 30px;
        margin-bottom: 0; /* Adjusted margin */
        clear: both;
        font-size: 11pt;
    }
    .footer-note {
        font-size: 9pt;
        margin-top: 15px; /* Reduced margin */
        border-top: 1px solid #ccc;
        padding-top: 10px;
        color: #555;
    }

    /* Print Specific Overrides */
    @media print {
        body { 
            background: none !important; 
            margin: 0; 
            padding: 0; 
        }
        .certificate-page {
            box-shadow: none !important;
            border: none !important;
            margin: 0;
        }
    }

</style>

<div class="form-card">
    <h3>Generate Salary Certificate</h3>
    
    <div id="status-message"><?php echo $status_message; ?></div>

    <?php if ($generated_content): ?>
        <div class="button-container" style="text-align: center; margin-bottom: 20px;">
            <button onclick="printCertificate()" class="btn-primary" style="background-color: #FFCDD2; color: #D32F2F; padding: 12px 25px; border: 1px solid #D32F2F; font-weight: bold;">Print / Generate PDF</button>
        </div>
        
        <!-- Display the generated content -->
        <div id="certificate-preview" class="certificate-preview" style="overflow-x: auto;">
            <?php echo $generated_content; ?>
        </div>
    <?php endif; ?>
</div>


<script>
    // JavaScript function to handle printing the certificate
    function printCertificate() {
        const printContent = document.getElementById('certificate-preview').innerHTML;
        const printWindow = window.open('', '', 'height=800,width=800');
        
        printWindow.document.write('<html><head><title>Salary Certificate</title>');
        
        // --- IMPORTANT: Include all CSS styles necessary for a proper PDF layout ---
        // We inject the CSS from the <style> block directly into the print window
        const styleSheet = document.querySelector('style').innerHTML;
        
        printWindow.document.write(`
            <style>
                ${styleSheet}
                /* Print specific overrides */
                .certificate-page { 
                    padding: 40px; 
                    box-shadow: none !important; 
                    border: none !important; 
                    margin: 0;
                    width: 100%;
                }
                .salary-table-container {
                    width: 100% !important;
                    margin: 30px 0 !important;
                }
                /* Print specific table border fix */
                 .total-row-summary td {
                    border-top: 1px solid #333 !important; /* Ensure separation from last month row */
                 }
                .total-row-summary .total-amount-cell {
                    border-bottom: 2px double #000 !important; /* Ensure double bottom border for total */
                }
            </style>
        `);
        
        printWindow.document.write('</head><body>');
        printWindow.document.write(printContent);
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        printWindow.focus();
        
        // Wait for content to render, then print
        printWindow.onload = function() {
            printWindow.print();
        };
    }
</script>
