<?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.
 */
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.
    $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));

    // 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 = "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.";
    
    // Total in words sentence construction
    $in_words_sentence = "In words: {$total_salary_in_words} Taka Only";

    $html = <<<HTML
    <div class="certificate-page">
        <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>

        <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-unboxed">TO WHOM IT MAY CONCERN</h1>
        </div>
        
        <div class="certificate-body">
            <p class="body-text">{$body_text}</p>
        </div>

        <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>
                    {$table_data_rows}
                    
                    <tr class="total-row-summary">
                        <td class="total-label-cell" colspan="2">Total</td>
                        <td class="total-amount-cell">{$total_salary_formatted}</td>
                    </tr>
                    
                    <tr class="in-words-row-table">
                        <td colspan="3" class="in-words-cell">
                            {$in_words_sentence}
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <div class="closing-section">
            <p class="closing-text">{$closing_text}</p>
        </div>
        
        <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 ---
?>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js" integrity="sha512-GsLlZN/3F2ErC5ifS5QtgpiJtWd43JWSuIgh7mbzZ8zBps+dvLusV+eNQATqgA/HdeKFVgA5v3S/cIrLF7QnIg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>


<style>



<style>
    /* Add this to change the background of the page outside the certificate */
    body {
        background-color: #f0f0f0; /* A light gray shade */
    }

    /* 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 */
        /* You might want to remove the default background from form-card if it's white */
        background-color: transparent; /* Makes the form-card transparent to show body background */
        box-shadow: none; /* Remove any default shadow if present on form-card */
    }

    /* 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; /* KEEP this white for the certificate itself */
        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;
    }

    /* ... rest of your CSS ... */




    /* 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;
    }
    /* 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;
    }

    /* Table Styling */
    .salary-table-container {
        margin: 30px auto;
        width: 100%;
    }
    .salary-table-container table {
        width: 100%;
        border-collapse: collapse;
        border: 1px solid #000; /* Outer border */
        font-size: 12pt;
        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;
    }
    .salary-table-container table thead tr {
        background-color: #ddd;
    }

    /* CRITICAL FIX: Fixed column widths for consistent print layout */
    .month-header, .month-cell { width: 30%; text-align: left; }
    .payment-header, .total-payment-data { width: 35%; text-align: left; }
    .amount-header, .amount-data { width: 35%; text-align: right; }

    /* The 'No salary generated' cell must span the Payment and Amount columns (65%) */
    .no-salary {
        text-align: center !important;
        color: #777;
        font-style: italic;
        width: 70%; /* Total colspan width (35% + 35%) */
    }

    /* Total Summary Row Style */
    .total-row-summary {
        font-weight: bold;
    }
    .total-row-summary .total-label-cell {
        width: 65%; /* Month (30%) + Total Payment (35%) */
        text-align: left !important;
        border-right: 1px solid #333 !important; /* Keep a dividing line */
        background-color: #fff;
    }
    .total-row-summary .total-amount-cell {
        width: 35%;
        text-align: right !important;
        background-color: #fff;
        border-bottom: 2px double #000 !important;
    }

    /* In Words Row - Single line structure WITHIN THE TABLE */
    .in-words-row-table td {
        padding: 8px 10px !important;
        border-top: none !important;
        border-bottom: 1px solid #333 !important;
        text-align: left !important;
        line-height: 1.2;
        width: 100%;
    }

    /* Footer / Closing Text Layout */
    .closing-text {
        margin-top: 30px;
        margin-bottom: 0;
        clear: both;
        font-size: 11pt;
    }
    .footer-note {
        font-size: 9pt;
        margin-top: 15px;
        border-top: 1px solid #ccc;
        padding-top: 10px;
        color: #555;
    }
</style>

<div class="form-card">
    
    
    <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="downloadPdf('SalaryCertificate_<?php echo htmlspecialchars($user_name ?? 'Employee'); ?>_<?php echo date('Ymd'); ?>')" 
                style="background-color: #e74c3c; color: white; padding: 10px 30px; border: none; border-radius: 5px; font-weight: bold;">
                Download as PDF
            </button>
        </div>
        
        <div id="certificate-preview" class="certificate-preview" style="overflow-x: auto;">
            <?php echo $generated_content; ?>
        </div>
    <?php endif; ?>
</div>

<script>
    /**
     * Uses html2pdf.js to capture the .certificate-page DIV and download it as a PDF.
     * This method generally provides better CSS/layout fidelity than window.print().
     * @param {string} filename The desired filename without the .pdf extension.
     */
    function downloadPdf(filename) {
        // Select the main certificate container element
        const element = document.querySelector('.certificate-page'); 
        
        // Define PDF generation options
        const options = {
            margin:       15, // Margins in millimeters
            filename:     filename + '.pdf',
            image:        { type: 'jpeg', quality: 0.98 }, // Use high quality JPEG for better color fidelity
            html2canvas:  { scale: 2, logging: false }, // Scale 2 is good for print resolution
            jsPDF:        { unit: 'mm', format: 'a4', orientation: 'portrait' }
        };

        // Use the html2pdf engine to generate and save the PDF
        html2pdf().set(options).from(element).save();
    }
</script>