<?php
// Assumes $conn (database connection) and $_SESSION['user_id'] are available from admin_dashboard.php
// UPDATED: Changed table name from 'payslip_salaries' to 'employee_salary'
$salary_table = 'employee_salary'; 
$history_table = 'payslip_history'; // Table to log generated payslips
$status_message = '';
$generated_content = null; 

// --- 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 = "This is to certify that [Username] is working at Cyberlog Ltd., 1/6, Block:
New- C, Mirpur-1, Dhaka-1216, Bangladesh and had drawn the following salary and allowances
per month as follows:";
$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;
    
    // Defaulting to "Taka" for currency context
    if (($number >= 0 && (int)$number == $number)) {
        return ucfirst(trim(convert_currency_to_words_recursive($number, $dictionary)) . " Only.");
    }

    $base_unit = floor($number);
    $text = convert_currency_to_words_recursive($base_unit, $dictionary);
    
    // Handle decimals (Taka/Paisa, Dollar/Cents)
    $fraction = round(($number - $base_unit) * 100);
    if ($fraction > 0) {
        $text .= $conjunction . convert_currency_to_words_recursive($fraction, $dictionary) . ' cent(s)';
    }

    return ucfirst($text . " Only.");
}

function convert_currency_to_words_recursive($number, $dictionary) {
    $hyphen      = '-';
    $conjunction = ' and ';
    $separator   = ', ';
    $negative    = 'negative ';
    $decimal     = ' point ';
    
    $string = $fraction = null;
    $base_unit = floor($number);
    $fraction = null;

    if ($base_unit < 21) {
        $string = $dictionary[$base_unit];
    } elseif ($base_unit < 100) {
        $ten = floor($base_unit / 10) * 10;
        $unit = $base_unit % 10;
        $string = $dictionary[$ten];
        if ($unit) {
            $string .= $hyphen . $dictionary[$unit];
        }
    } elseif ($base_unit < 1000) {
        $hundred = floor($base_unit / 100);
        $remainder = $base_unit % 100;
        $string = $dictionary[$hundred] . ' ' . $dictionary[100];
        if ($remainder) {
            $string .= $conjunction . convert_currency_to_words_recursive($remainder, $dictionary);
        }
    } else {
        $baseUnit = 1000;
        $baseText = 'thousand';

        if ($base_unit >= 1000000) {
            $baseUnit = 1000000;
            $baseText = 'million';
        }
        
        $base = floor($base_unit / $baseUnit);
        $remainder = $base_unit % $baseUnit;
        
        $string = convert_currency_to_words_recursive($base, $dictionary) . ' ' . $baseText;
        
        if ($remainder) {
            $string .= $separator;
            $string .= convert_currency_to_words_recursive($remainder, $dictionary);
        }
    }

    return $string;
}

// --- FUNCTION: Builds the PAYSLIP HTML ---
function get_payslip_html($data, $fixed_info, $totals) {
    $user_name = htmlspecialchars($data['employee_name'] ?? 'EMPLOYEE NAME');
    $generation_date = htmlspecialchars($data['payslip_date'] ?? date('Y-m-d'));
    $months_text = htmlspecialchars($data['months_text'] ?? 'N/A');
    $currency_symbol = '৳'; // Placeholder symbol, adjust as needed

    $fixed_text_top_personalized = str_replace('[Username]', $user_name, $GLOBALS['fixed_text_top']);
    
    // Format the total net payable for words
    $net_payable_words = convert_number_to_words($totals['total_net_payable']);

    $html_content = "
        <div class='payslip-page'>
            <!-- Header Section (Fixed Company Info) -->
            <div style='display: flex; justify-content: space-between; align-items: flex-start; border-bottom: 2px solid #333; padding-bottom: 10px; margin-bottom: 20px;'>
                <div style='width: 30%;'>
                    <img src='{$fixed_info['logo_url']}' alt='Company Logo' style='max-height: 50px; width: auto; display: block;'>
                </div>
                <div style='width: 70%; text-align: right; font-size: 0.8em;'>
                    <p style='margin: 0;'><strong>{$fixed_info['company_name']}</strong></p>
                    <p style='margin: 0;'>{$fixed_info['address']}</p>
                    <p style='margin: 0;'>Email: {$fixed_info['email']} | Web: {$fixed_info['website']}</p>
                </div>
            </div>

            <!-- Date and Title -->
			<br/>
            <div style='display: flex; justify-content: center; align-items: center; margin-bottom: 20px;'> 
                <h1 style='margin: 0; font-size: 1.8em; text-align: center; border: 1px solid #333; padding: 5px 15px;'>PAYSLIP</h1>
            </div>
			<div style='font-weight: bold;'>Date: {$generation_date}</div>
			
			
            <!-- Fixed Text Top -->
            <p style='font-size: 1em; margin-bottom: 20px; border-bottom: 1px solid #ccc; padding-bottom: 10px;'>
                {$fixed_text_top_personalized} <strong>{$months_text}</strong>.
            </p>

            <!-- Salary Table -->
            <table style='width: 100%; border-collapse: collapse; margin-bottom: 20px;'>
                <thead>
                    <tr style='background-color: #f2f2f2;'>
                        <th style='border: 1px solid #333; padding: 8px; width: 5%; text-align: center;'>S/N</th>
                        <th style='border: 1px solid #333; padding: 8px; width: 25%; text-align: left;'>Month/Year</th>
                        <th style='border: 1px solid #333; padding: 8px; width: 17.5%; text-align: right;'>Basic Salary</th>
                        <th style='border: 1px solid #333; padding: 8px; width: 17.5%; text-align: right;'>Gross Salary</th>
                        <th style='border: 1px solid #333; padding: 8px; width: 17.5%; text-align: right;'>Deduction</th>
                        <th style='border: 1px solid #333; padding: 8px; width: 17.5%; text-align: right;'>Net Payable</th>
                    </tr>
                </thead>
                <tbody>
    ";
    
    // Add dynamic rows for each month
    $sn = 1;
    if (!empty($data['salary_details'])) {
        foreach ($data['salary_details'] as $row) {
            $month_name = date('F', mktime(0, 0, 0, $row['salary_month'], 10));
            $formatted_month_year = "{$month_name} - {$row['salary_year']}";
            
            $html_content .= "
                <tr>
                    <td style='border: 1px solid #ccc; padding: 8px; text-align: center;'>{$sn}</td>
                    <td style='border: 1px solid #ccc; padding: 8px;'>{$formatted_month_year}</td>
                    <td style='border: 1px solid #ccc; padding: 8px; text-align: right;'>{$currency_symbol} " . number_format($row['basic_salary'], 2) . "</td>
                    <td style='border: 1px solid #ccc; padding: 8px; text-align: right;'>{$currency_symbol} " . number_format($row['gross_salary'], 2) . "</td>
                    <td style='border: 1px solid #ccc; padding: 8px; text-align: right;'>{$currency_symbol} " . number_format($row['total_deduction'], 2) . "</td>
                    <td style='border: 1px solid #ccc; padding: 8px; text-align: right;'>{$currency_symbol} " . number_format($row['net_payable'], 2) . "</td>
                </tr>
            ";
            $sn++;
        }
    } else {
         $html_content .= "
            <tr>
                <td colspan='6' style='border: 1px solid #ccc; padding: 10px; text-align: center; font-style: italic;'>No salary data found for the selected month(s) and user.</td>
            </tr>
        ";
    }

    // Totals Row
    $html_content .= "
                <tr style='font-weight: bold; background-color: #e6ffe6; border-top: 2px solid #008000;'>
                    <td colspan='2' style='border: 1px solid #333; padding: 10px; text-align: left;'>TOTALS</td>
                    <td style='border: 1px solid #333; padding: 10px; text-align: right;'>{$currency_symbol} " . number_format($totals['total_basic'], 2) . "</td>
                    <td style='border: 1px solid #333; padding: 10px; text-align: right;'>{$currency_symbol} " . number_format($totals['total_gross'], 2) . "</td>
                    <td style='border: 1px solid #333; padding: 10px; text-align: right;'>{$currency_symbol} " . number_format($totals['total_deduction'], 2) . "</td>
                    <td style='border: 1px solid #333; padding: 10px; text-align: right;'>{$currency_symbol} " . number_format($totals['total_net_payable'], 2) . "</td>
                </tr>
                <!-- Amount in Words Row -->
                <tr style='background-color: #fcfcfc;'>
                    <td colspan='6' style='border: 1px solid #333; padding: 10px; font-weight: bold;'>
                        {$GLOBALS['fixed_text_bottom_1']}: <span style='color: #008000;'>{$net_payable_words}</span>
                    </td>
                </tr>
                
                </tbody>
            </table>

            <!-- Signature/Footer Text -->
            <div style='text-align: center; margin-top: 30px; padding: 10px; border-top: 1px solid #ccc;'>
                <!-- <p style='margin-bottom: 5px; font-weight: bold; font-size: 1.1em;'>{$user_name}</p> -->
                <!-- <p style='font-size: 0.9em; margin-top: 0;'>Employee Signature/Stamp</p> -->
            </div>
            <br/>
			<br/>
			<br/>
			<br/>
			<br/>
			<br/>
			<br/>
			<br/>
			<br/>
			<br/>
			<br/>
			<br/>
			<br/>
			<br/>
			<br/>
			<br/>
			<br/>
			<br/>
			<br/>
            <div style='font-size: 0.8em; text-align: center; margin-top: 50px; color: #555; padding-top: 10px; border-top: 1px dotted #ccc;'>
                {$GLOBALS['fixed_text_bottom_2']}
            </div>

        </div>
    ";

    return $html_content;
}


// --- 3. FORM SUBMISSION AND DATA PROCESSING ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["generate_payslip"])) {
    
    // Default to a known User ID if session is unavailable for testing (e.g., 1)
    $employee_id = (int)$_POST['employee_id']; 
    $payslip_date = htmlspecialchars($_POST['payslip_date']);
    $selected_months = $_POST['months'] ?? [];

    if (empty($selected_months)) {
        $status_message = "<div class='alert alert-error'>Please select at least one month.</div>";
    } elseif ($employee_id <= 0) {
        $status_message = "<div class='alert alert-error'>Invalid Employee ID provided.</div>";
    } else {
        
        // 1. Fetch Salary Data
        $placeholders = implode(',', array_fill(0, count($selected_months), '?'));
        // We assume the user is also fixed by the $employee_id, but the query should handle multiple months.
        
        $sql = "SELECT salary_month, salary_year, basic_salary, gross_salary, total_deduction, net_payable 
                FROM {$salary_table} 
                WHERE user_id = ? AND CONCAT(salary_year, '-', LPAD(salary_month, 2, '0')) IN ({$placeholders})
                ORDER BY salary_year ASC, salary_month ASC";

        if ($stmt = $conn->prepare($sql)) {
            $types = 'i' . str_repeat('s', count($selected_months)); // i for user_id, s for month/year strings
            $params = array_merge([$employee_id], $selected_months);
            
            // Need to pass by reference for bind_param, which is complex in PHP for arrays.
            // Using call_user_func_array for dynamic binding
            $bind_names[] = $types;
            for ($i = 0; $i < count($params); $i++) {
                $bind_name = 'p' . $i;
                $$bind_name = $params[$i];
                $bind_names[] = &$$bind_name;
            }
            call_user_func_array([$stmt, 'bind_param'], $bind_names);
            
            $stmt->execute();
            $result = $stmt->get_result();
            $salary_details = $result->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            
            // 2. Calculate Totals and Prepare Display Data
            $totals = [
                'total_basic' => 0,
                'total_gross' => 0,
                'total_deduction' => 0,
                'total_net_payable' => 0
            ];
            $month_names = [];
            
            foreach ($salary_details as $row) {
                $totals['total_basic'] += $row['basic_salary'];
                $totals['total_gross'] += $row['gross_salary'];
                $totals['total_deduction'] += $row['total_deduction'];
                $totals['total_net_payable'] += $row['net_payable'];
                
                $month_names[] = date('F Y', mktime(0, 0, 0, $row['salary_month'], 1, $row['salary_year']));
            }
            
            $months_text = implode(', ', $month_names);
            
            // --- Placeholder: Get Employee Name (Must be fetched from a user/employee table) ---
            // For now, use a placeholder name based on ID
            $employee_name = "{$_SESSION['username']}";
		
		
            
            // 3. Assemble Data for HTML Generation
            $payslip_data = [
                'employee_id' => $employee_id,
                'employee_name' => $employee_name,
                'payslip_date' => $payslip_date,
                'months_text' => $months_text,
                'salary_details' => $salary_details,
				
            ];

            $generated_content = get_payslip_html($payslip_data, $fixed_company_info, $totals);
            
            // 4. Log generation in history table (Create this table if needed, using the logic from completion_certificate.php)
            // For simplicity here, we only set a success message.
            $status_message = "<div class='alert alert-success'>Payslip generated successfully for Employee #{$employee_id} for the months: {$months_text}.</div>";
            
        } else {
            $status_message = "<div class='alert alert-error'>Database error during query preparation: " . $conn->error . "</div>";
        }
    }
}


// --- Utility functions for form and month selection ---
function get_month_options() {
    $months = [];
    $current_year = date('Y');
    $current_month = date('n');

    // Generate options for the current year up to the current month
    for ($m = 1; $m <= $current_month; $m++) {
        $month_name = date('F', mktime(0, 0, 0, $m, 1));
        $value = "{$current_year}-" . str_pad($m, 2, '0', STR_PAD_LEFT);
        $months[$value] = "{$month_name} {$current_year}";
    }
    // Optionally add a few months from previous year
    for ($m = 10; $m <= 12; $m++) {
        $month_name = date('F', mktime(0, 0, 0, $m, 1));
        $prev_year = $current_year - 1;
        $value = "{$prev_year}-" . str_pad($m, 2, '0', STR_PAD_LEFT);
        $months[$value] = "{$month_name} {$prev_year}";
    }
    krsort($months); // Sort descending (newest first)
    return $months;
}

?>

<style>
    /* General styles for alerts and buttons, matching convey_expense.php */
    .alert-error { background-color: #fbecec; border: 1px solid #e74c3c; color: #e74c3c; padding: 10px; border-radius: 5px; margin-bottom: 10px; }
    .alert-success { background-color: #e8f5e9; border: 1px solid #2ecc71; color: #2ecc71; padding: 10px; border-radius: 5px; margin-bottom: 10px; }
    .alert-info { background-color: #ebf5fb; border: 1px solid #3498db; color: #3498db; padding: 10px; border-radius: 5px; margin-bottom: 10px; }
    .button-group-aligned {
        margin-top: 30px;
        display: flex; 
        justify-content: space-between; 
        align-items: center; 
        width: 100%; 
    }
    .right-aligned-buttons {
        display: flex; 
        gap: 10px;    
    }
    .action-button {
        min-width: 150px; 
        text-align: center;
        padding: 12px 20px; 
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-size: 16px;
        text-decoration: none;
        font-weight: bold;
        transition: background-color 0.3s;
        display: inline-block; 
    }
    .primary-btn { background-color: #3498db; color: white; }
    .primary-btn:hover { background-color: #2980b9; }
    .warning-btn { background-color: #ffcc66; color: #333; }
    .warning-btn:hover { background-color: #f6b300; }
    .secondary-btn { background-color: #aab8c2; color: white; }
    .secondary-btn:hover { background-color: #8c97a1; }
    
    /* Styles for the payslip draft area */
    .payslip-page { 
        padding: 40px; 
        background: white; 
        border: 1px solid #ddd; 
        box-shadow: 0 0 10px rgba(0,0,0,0.05); 
        box-sizing: border-box; 
        margin: 20px auto; 
        max-width: 800px;
        min-height: 1100px; /* A4 size approximation */
        font-family: Arial, sans-serif;
    }
    
    @media print {
        body > *:not(.print-container) { display: none !important; }
        .print-container { 
            display: block !important; 
            width: 100%; 
            margin: 0; 
            padding: 0; 
        }
        .payslip-page { 
            box-shadow: none !important; 
            border: none !important; 
            min-height: auto !important; 
            width: 100% !important; 
            padding: 20px !important;
        }
        .payslip-page table th, .payslip-page table td { 
            border: 1px solid #333 !important; 
        }
    }
</style>

<!-- Payslip Generation Form -->
<div class="form-card">
    <h3>Monthly Payslip Generator</h3>
    
    <?php echo $status_message; ?>

    <form action="admin_dashboard.php?page=pay_slip" method="post">
        
        <div style="display: flex; gap: 20px; margin-bottom: 20px;">
            <!-- Employee ID (Red Box placeholder) -->
            <div class="form-group" style="flex: 1;">
                <label for="employee_id" style="color: #FF0000; font-weight: bold; border-left: 3px solid #FF0000; padding-left: 5px;">Employee ID (for Data Fetch):</label>
                <input type="number" id="employee_id" name="employee_id" value="<?php echo htmlspecialchars($_POST['employee_id'] ?? ($_SESSION['user_id'] ?? 1)); ?>" required 
                       style="border: 1px solid #FF0000; width: 100%; padding: 8px;">
            </div>

            <!-- Payslip Date -->
            <div class="form-group" style="flex: 1;">
                <label for="payslip_date" style="color: #333; font-weight: bold; border-left: 3px solid #333; padding-left: 5px;">Payslip Date:</label>
                <input type="date" id="payslip_date" name="payslip_date" value="<?php echo htmlspecialchars($_POST['payslip_date'] ?? date('Y-m-d')); ?>" required 
                       style="border: 1px solid #ccc; width: 100%; padding: 8px;">
            </div>
        </div>

        <!-- Month Selection (Multiple Select) -->
        <div class="form-group">
            <label for="months" style="color: #333; font-weight: bold; border-left: 3px solid #333; padding-left: 5px;">Select Month(s) for Payslip:</label>
            <select id="months" name="months[]" multiple required size="5"
                    style="border: 1px solid #ccc; width: 100%; padding: 8px;">
                <?php
                $available_months = get_month_options();
                $selected_months_post = $_POST['months'] ?? [];
                
                foreach ($available_months as $value => $label): 
                    $selected = in_array($value, $selected_months_post) ? 'selected' : '';
                ?>
                    <option value="<?php echo $value; ?>" <?php echo $selected; ?>><?php echo $label; ?></option>
                <?php endforeach; ?>
            </select>
            <small style="display: block; margin-top: 5px; color: #777;">Hold CTRL (or Cmd on Mac) to select multiple months.</small>
        </div>

        <div class="button-group-aligned">
            <button type="submit" name="generate_payslip" class="action-button primary-btn">
                Generate Payslip
            </button>
            <div class="right-aligned-buttons">
                 <button type="reset" class="action-button warning-btn">
                    Reset Form
                </button>
                <a href="admin_dashboard.php?page=manage_templates" class="action-button secondary-btn">
                    Cancel
                </a>
            </div>
        </div>
    </form>
</div>

<!-- Generated Content Draft Section -->
<?php if (isset($generated_content)): ?>
<div class="form-card print-container-wrapper" style="margin-top: 20px;">
    <h3>Generated Payslip Draft & Download</h3>
    <p>Review the draft below. Click Download to open a printable PDF view.</p>
    
    <div style="text-align: center; margin-bottom: 20px;">
        <button onclick="downloadPdf('Payslip_<?php echo htmlspecialchars($_POST['employee_id'] ?? 1); ?>_<?php echo date('Ymd'); ?>')" 
                style="background-color: #e74c3c; color: white; padding: 10px 30px; border: none; border-radius: 5px;">
            Download as PDF
        </button>
        <button onclick="window.location.href='admin_dashboard.php?page=pay_slip';" 
                style="background-color: #5d9cec; color: white; padding: 10px 30px; border: none; border-radius: 5px; margin-left: 10px;">
            + Create New Payslip
        </button>
    </div>
    
    <div id="print_area" class="print-container">
        <?php echo $generated_content; ?>
    </div>
</div>
<?php endif; ?>

<!-- History Section (Placeholder as table structure is not fully defined yet) -->
<div class="form-card" style="margin-top: 40px;">
    <h3>Payslip Generation History</h3>
    <div class="alert alert-info">Payslip generation history is currently not logged. Database table `payslip_history` would be required for this feature.</div>
</div>

<script>
    // JavaScript function to simulate PDF download using the print feature
    function downloadPdf(filename) {
        const printContent = document.getElementById('print_area').innerHTML;
        const printWindow = window.open('', '', 'height=600,width=800');
        printWindow.document.write('<html><head><title>' + filename + '</title>');
        
        // Include the necessary CSS styles for the print view
        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: 100px; height: auto; }
            </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.focus();
        printWindow.print();
    }
</script>
