<?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[$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) {
    
    // --- 1. Define the 12-month period (Current month and 11 preceding months) ---
    $salary_data_map = []; // Map to hold month_year => basic_salary
    $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), '?'));
    
    // Assuming 'employee_salary' table has 'user_id', 'basic_salary', and 'month_year' (as YYYY-MM-01)
    $sql = "SELECT basic_salary, DATE_FORMAT(month_year, '%Y-%m-%01') AS month_key 
            FROM employee_salary 
            WHERE user_id = ? AND DATE_FORMAT(month_year, '%Y-%m-%01') IN ($placeholders)
            ORDER BY month_year DESC";

    $stmt = $conn->prepare($sql);
    
    // Dynamically bind parameters (1 integer for user_id, 12 strings for month_start_dates)
    $types = 'i' . str_repeat('s', count($month_start_dates));
    $params = array_merge([$types, $user_id], $month_start_dates);
    
    // Call bind_param dynamically
    call_user_func_array([$stmt, 'bind_param'], ref_values($params));

    if ($stmt->execute()) {
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $salary_data_map[$row['month_key']] = (float)$row['basic_salary'];
        }
    } else {
        error_log("Database error fetching salary: " . $stmt->error);
        // Fallback for failed query
        $status_message = "<p class='error'>Error fetching salary data.</p>";
    }
    $stmt->close();
    
    // Helper function for call_user_func_array bind_param
    function ref_values($arr){
        if (strnatcmp(phpversion(),'5.3') >= 0) // PHP 5.3+
        {
            $refs = array();
            foreach($arr as $key => $value)
                $refs[$key] = &$arr[$key];
            return $refs;
        }
        return $arr;
    }


    // --- 3. Build the Salary Table Rows and Calculate Total ---
    $table_rows = '';
    
    foreach ($month_list as $month_key => $month_name) {
        $amount = $salary_data_map[$month_key] ?? null;
        
        $table_rows .= "<tr>";
        $table_rows .= "<td class='month-cell'>{$month_name}</td>";
        
        if ($amount !== null) {
            $table_rows .= "<td class='amount-cell'>" . number_format($amount, 2) . "</td>";
            $total_salary += $amount;
        } else {
            $table_rows .= "<td class='amount-cell no-salary'>No salary generated this month</td>";
        }
        $table_rows .= "</tr>";
    }

    $total_salary_in_words = convert_number_to_words($total_salary);


    // --- 4. Generate the HTML Content ---
    
    $certificate_date = date('F d, Y');
    $user_name_upper = strtoupper(htmlspecialchars($user_name));
    $user_role_upper = strtoupper(htmlspecialchars($user_role));

    // Fixed Text Body
    $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 = "We wish him/her every success in life.";
    $footer_note = "This certificate is issued on the request of the employee for official/personal purpose only and for no other purpose.";
    

    $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><strong>{$company_info['company_name']}</strong></p>
                <p>{$company_info['address']}</p>
                <p>Email: {$company_info['email']}</p>
                <p>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>
            
            <h1 class="certificate-title">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 colspan="2" class="table-title">SALARY FOR THE LAST 12 MONTHS</th>
                    </tr>
                    <tr>
                        <th class="month-header">Month</th>
                        <th class="amount-header">Amount (BDT)</th>
                    </tr>
                </thead>
                <tbody>
                    {$table_rows}
                    <tr>
                        <td class="total-label"><strong>TOTAL SALARY</strong></td>
                        <td class="total-amount"><strong>{$total_salary}</strong></td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- SALARY IN WORDS -->
        <div class="total-words-section">
            <p><strong>TOTAL SALARY (IN WORDS):</strong> {$total_salary_in_words} BDT ONLY</p>
        </div>
        
        <!-- CLOSING AND SIGNATURE -->
        <div class="certificate-footer">
            <p class="closing-text">{$closing_text}</p>
            
            <div class="signature-block">
                <img src="{$signature_path}" alt="Signature" class="signature-image">
                <p class="signer-name"><strong>HR Manager Name (Placeholder)</strong></p>
                <p class="signer-title">HR Manager</p>
                <p class="company-name-footer">{$company_info['company_name']}</p>
            </div>
            
            <p class="footer-note">{$footer_note}</p>
        </div>
    </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' => $company_website,
    ];
    $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 ---
?>

<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">
            <button onclick="printCertificate()" class="btn btn-primary">Print / Generate PDF</button>
        </div>
        
        <!-- Display the generated content -->
        <div id="certificate-preview" class="certificate-preview">
            <?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 ---
        printWindow.document.write(`
            <style>
                body { 
                    font-family: 'Arial', sans-serif; 
                    margin: 0; 
                    padding: 0; 
                    -webkit-print-color-adjust: exact;
                }
                .certificate-page {
                    position: relative;
                    padding: 40px; 
                    background: white;
                    min-height: 1100px; /* A4 size approximation */
                    box-sizing: border-box;
                    width: 100%;
                    font-size: 11pt;
                    line-height: 1.6;
                }

                /* Header Styling */
                .fixed-header {
                    display: flex;
                    justify-content: space-between;
                    align-items: flex-start;
                    padding-bottom: 10px;
                    margin-bottom: 5px;
                }
                .logo-container {
                    flex-basis: 25%;
                }
                .company-logo { 
                    max-width: 180px; 
                    height: auto; 
                }
                .address-block {
                    flex-basis: 70%;
                    text-align: right;
                    font-size: 10pt;
                    color: #555;
                    line-height: 1.4;
                }
                .address-block p { margin: 0; padding: 0; }

                .header-separator {
                    border-bottom: 3px solid #000;
                    margin-bottom: 25px;
                }

                /* Date and Title */
                .date-title-section {
                    margin-bottom: 40px;
                }
                .date-block {
                    text-align: right;
                    margin-bottom: 30px;
                    font-weight: bold;
                }
                .certificate-title {
                    text-align: center;
                    font-size: 1.6em;
                    font-weight: 700;
                    color: #000;
                    border: 2px solid #000;
                    padding: 8px 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 {
                    font-weight: bold; /* Ensure bold remains strong */
                }


                /* Table Styling */
                .salary-table-container {
                    margin: 30px 0;
                    width: 80%; /* Match the look of the template */
                    margin-left: auto;
                    margin-right: auto;
                }
                .salary-table-container table { 
                    width: 100%; 
                    border-collapse: collapse; 
                    border: 2px solid #000; /* Outer border */
                }
                .salary-table-container table th, 
                .salary-table-container table td { 
                    border: 1px solid #333; /* Inner borders */
                    padding: 10px; 
                    font-size: 11pt;
                    text-align: left;
                }
                .salary-table-container table thead tr { 
                    background-color: #f2f2f2; 
                }
                .table-title {
                    text-align: center !important;
                    font-weight: bold;
                    background-color: #ddd !important;
                    font-size: 1.1em !important;
                }
                .month-header { width: 65%; }
                .amount-header { width: 35%; text-align: right !important; }
                .amount-cell { text-align: right !important; }
                .total-label, .total-amount { 
                    background-color: #f2f2f2; 
                    font-weight: bold;
                }
                .total-amount { text-align: right !important; }
                .no-salary { color: #888; font-style: italic; }

                /* Total in Words */
                .total-words-section {
                    margin-bottom: 50px;
                }
                
                /* Footer / Signature */
                .certificate-footer {
                    margin-top: 80px; /* Space before signature block */
                }
                .closing-text {
                    margin-bottom: 60px;
                }
                .signature-block {
                    margin-top: 50px;
                    width: 300px;
                }
                .signature-image {
                    max-width: 150px;
                    height: auto;
                    display: block;
                    margin-bottom: -15px; /* Overlap with line if needed */
                }
                .signer-name {
                    margin-top: 15px;
                    padding-top: 5px;
                    border-top: 1px solid #000;
                    font-weight: bold;
                    margin-bottom: 0;
                }
                .signer-title, .company-name-footer {
                    margin: 0;
                    font-size: 10pt;
                }
                
                .footer-note {
                    font-size: 9pt;
                    margin-top: 50px;
                    border-top: 1px solid #ccc;
                    padding-top: 10px;
                    color: #555;
                }
            </style>
        `);
        
        printWindow.document.write('</head><body>');
        printWindow.document.write(printContent);
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        printWindow.focus();
        
        // Wait for images (like logo/signature) to load before printing
        printWindow.onload = function() {
            printWindow.print();
            // Optional: Close window after printing/pdf saving
            // printWindow.close(); 
        };
    }
</script>
