<?php
// Assumes $conn (database connection) and $_SESSION['user_id'] are available 
// from admin_dashboard.php's scope.

$status_message = '';
$user_id = $_SESSION['user_id'] ?? 1; // Default to ID 1 for safety
$generated_content = null;

// --- Fixed Invoice/Letterpad Components (from company_letterpad.php and image) ---
$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";
$company_phone = "+013576990884"; // Extracted from image details

// Fixed Billing Details (Assuming Cyberlog is billing itself or details are placeholder)
$bill_to_company = "Cyberlog Ltd.";
$bill_to_details = "1/6, Block: New- C, Mirpur-1, Dhaka-1216, Bangladesh<br>
Phone: {$company_phone}<br>
Email: info@cyberlog.com.bd";

// --- Function to build the Expense List HTML (mimics the template image) ---
function get_expense_list_html(
    $invoice_no, 
    $invoice_date, 
    $items_data, 
    $subtotal, 
    $advance_payment, 
    $grand_total
) {
    global $company_name, $company_address, $company_email, $company_website, $bill_to_details, $bill_to_company;
    
    // Header for the expense list (Invoice)
    $header_html = "
        <div style='display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 20px;'>
            <div style='flex-grow: 1;'>
                <img src='path/to/your/cyberlog_logo.png' alt='{$company_name} Logo' style='max-width: 150px; height: auto; margin-bottom: 10px;'>
                <h1 style='color: #008000; font-size: 30px; margin: 0;'>{$company_name}</h1>
                <p style='margin: 0; font-size: 10px; border-bottom: 2px solid #008000; width: 150px;'>&nbsp;</p>
            </div>
            <div style='text-align: right; font-size: 12px; color: #555;'>
                <p style='margin: 0 0 5px 0;'>{$company_address} <span style='color: #E74C3C;'>&#x1F4CD;</span></p>
                <p style='margin: 0 0 5px 0;'>info@cyberlog.com.bd <span style='color: #E74C3C;'>&#x2709;</span></p>
                <p style='margin: 0;'>www.cyberlog.com.bd <span style='color: #E74C3C;'>&#x1F310;</span></p>
            </div>
        </div>
    ";

    // Main Invoice Details Section
    $details_html = "
        <div style='margin-bottom: 30px; padding: 20px; background-color: #f0f8ff; border: 1px solid #dcdcdc;'>
            <div style='display: flex; justify-content: space-between; margin-bottom: 10px;'>
                <div>
                    <strong style='color: #E74C3C;'>Invoice No:</strong> <span style='color: #333;'>{$invoice_no}</span>
                </div>
                <div>
                    <strong style='color: #E74C3C;'>Invoice Date:</strong> <span style='color: #333;'>{$invoice_date}</span>
                </div>
            </div>
            <hr style='border: 0; border-top: 1px solid #ccc; margin: 10px 0;'>
            <p style='font-size: 14px; margin-bottom: 5px;'><strong style='color: #2c3e50;'>Bill To:</strong> {$bill_to_company}</p>
            <p style='font-size: 12px; line-height: 1.5; margin: 0; padding-left: 10px;'>{$bill_to_details}</p>
        </div>
    ";
    
    // Expense Items Table
    $items_table_html = "
        <table style='width: 100%; border-collapse: collapse; margin-bottom: 40px;'>
            <thead>
                <tr style='background-color: #f2f2f2;'>
                    <th style='border: 1px solid #333; padding: 8px; width: 5%;'>#</th>
                    <th style='border: 1px solid #333; padding: 8px; width: 50%; text-align: left;'>Description</th>
                    <th style='border: 1px solid #333; padding: 8px; width: 15%;'>Unit Price (BDT)</th>
                    <th style='border: 1px solid #333; padding: 8px; width: 10%;'>Quantity</th>
                    <th style='border: 1px solid #333; padding: 8px; width: 20%;'>Total (BDT)</th>
                </tr>
            </thead>
            <tbody>
    ";
    
    $item_counter = 1;
    foreach ($items_data as $item) {
        $items_table_html .= "
            <tr>
                <td style='border: 1px solid #ccc; padding: 8px; text-align: center;'>{$item_counter}</td>
                <td style='border: 1px solid #ccc; padding: 8px;'>".htmlspecialchars($item['description'])."</td>
                <td style='border: 1px solid #ccc; padding: 8px; text-align: right;'>".number_format($item['unit_price'], 2)."</td>
                <td style='border: 1px solid #ccc; padding: 8px; text-align: center;'>".htmlspecialchars($item['quantity'])."</td>
                <td style='border: 1px solid #ccc; padding: 8px; text-align: right;'>".number_format($item['total_bdt'], 2)."</td>
            </tr>
        ";
        $item_counter++;
    }
    
    // Add 2 blank rows for structure (mimics the template)
    for ($i = $item_counter; $i <= 6; $i++) {
         $items_table_html .= "
            <tr>
                <td style='border: 1px solid #ccc; padding: 8px; text-align: center;'>{$i}</td>
                <td style='border: 1px solid #ccc; padding: 8px;'>&nbsp;</td>
                <td style='border: 1px solid #ccc; padding: 8px;'>&nbsp;</td>
                <td style='border: 1px solid #ccc; padding: 8px;'>&nbsp;</td>
                <td style='border: 1px solid #ccc; padding: 8px;'>&nbsp;</td>
            </tr>
        ";
    }

    $items_table_html .= "
            </tbody>
        </table>
    ";
    
    // Summary and Signature Section
    $summary_and_signature_html = "
        <div style='display: flex; justify-content: space-between;'>
            
            <div style='width: 35%; border: 1px solid #E74C3C; padding: 15px; text-align: center;'>
                <img src='path/to/hridoy_mustofa_signature.png' alt='Signature' style='max-width: 150px; margin-bottom: 5px;'>
                <p style='margin: 5px 0; font-weight: bold;'>Hridoy Mustofa</p>
                <p style='margin: 0; font-size: 12px;'>Founder & CEO</p>
                <p style='margin: 0; font-size: 14px; font-weight: bold; color: #008000;'>{$company_name}log</p>
            </div>

            <div style='width: 40%;'>
                <table style='width: 100%; border-collapse: collapse; margin-left: auto;'>
                    <tr>
                        <td style='border: 1px solid #ccc; padding: 8px;'>Subtotal</td>
                        <td style='border: 1px solid #ccc; padding: 8px; text-align: right;'>".number_format($subtotal, 2)." BDT</td>
                    </tr>
                    <tr>
                        <td style='border: 1px solid #ccc; padding: 8px;'>Advance Payment (50%)</td>
                        <td style='border: 1px solid #ccc; padding: 8px; text-align: right;'>".number_format($advance_payment, 2)." BDT</td>
                    </tr>
                    <tr>
                        <td style='border: 1px solid #ccc; padding: 8px; font-weight: bold;'>Grand Total</td>
                        <td style='border: 1px solid #ccc; padding: 8px; text-align: right; font-weight: bold;'>".number_format($grand_total, 2)." BDT</td>
                    </tr>
                </table>
            </div>
        </div>
    ";
    
    // Combine all parts
    return "
        <div class='letter-page'>
            {$header_html}
            {$details_html}
            {$items_table_html}
            {$summary_and_signature_html}
        </div>
    ";
}


// --- Logic to Handle Form Submission (Generate & Save) ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['generate_expense_list'])) {
    
    // 1. Sanitize & Prepare Inputs
    $invoice_no = $conn->real_escape_string($_POST['invoice_no'] ?? '');
    $invoice_date = $conn->real_escape_string($_POST['invoice_date'] ?? date('Y-m-d'));
    
    $descriptions = $_POST['description'] ?? [];
    $unit_prices = $_POST['unit_price'] ?? [];
    $quantities = $_POST['quantity'] ?? [];
    $advance = (float)($_POST['advance_payment'] ?? 0);

    $items_data = [];
    $subtotal = 0.00;
    
    // 2. Process Line Items and Calculate Subtotal
    foreach ($descriptions as $i => $desc) {
        $desc = trim($conn->real_escape_string($desc));
        $u_price = (float)($unit_prices[$i] ?? 0);
        $qty = (int)($quantities[$i] ?? 1);
        
        if (!empty($desc) && $u_price > 0 && $qty > 0) {
            $total = $u_price * $qty;
            $subtotal += $total;
            $items_data[] = [
                'description' => $desc,
                'unit_price' => $u_price,
                'quantity' => $qty,
                'total_bdt' => $total
            ];
        }
    }
    
    $grand_total = $subtotal - $advance;

    if (empty($items_data)) {
        $status_message = "<div class='alert alert-error'>Please add at least one expense item with a price greater than zero.</div>";
    } else {
        // 3. Save to Database - Main Record
        $conn->begin_transaction();
        
        $sql_main = "INSERT INTO expense_lists (invoice_no, invoice_date, bill_to_company, bill_to_address, subtotal, advance_payment, grand_total, created_by) 
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        
        if ($stmt_main = $conn->prepare($sql_main)) {
            $stmt_main->bind_param("ssssdddi", $invoice_no, $invoice_date, $bill_to_company, $bill_to_details, $subtotal, $advance, $grand_total, $user_id);
            
            if ($stmt_main->execute()) {
                $last_expense_id = $stmt_main->insert_id;
                $all_items_saved = true;
                
                // 4. Save to Database - Line Items
                $sql_items = "INSERT INTO expense_list_items (expense_id, description, unit_price, quantity, total_bdt) 
                              VALUES (?, ?, ?, ?, ?)";
                
                if ($stmt_items = $conn->prepare($sql_items)) {
                    foreach ($items_data as $item) {
                        $desc = $item['description'];
                        $u_price = $item['unit_price'];
                        $qty = $item['quantity'];
                        $total = $item['total_bdt'];
                        
                        $stmt_items->bind_param("isddb", $last_expense_id, $desc, $u_price, $qty, $total);
                        if (!$stmt_items->execute()) {
                            $all_items_saved = false;
                            break;
                        }
                    }
                    $stmt_items->close();
                } else {
                    $all_items_saved = false;
                    $status_message = "<div class='alert alert-error'>Item Database preparation error: " . $conn->error . "</div>";
                }
                
                if ($all_items_saved) {
                    $conn->commit();
                    $status_message = "<div class='alert alert-success'>Expense List (ID: {$last_expense_id}) generated and saved successfully!</div>";
                } else {
                    $conn->rollback();
                    if (empty($status_message)) {
                        $status_message = "<div class='alert alert-error'>Failed to save all expense line items. Transaction rolled back.</div>";
                    }
                }
            } else {
                $conn->rollback();
                $status_message = "<div class='alert alert-error'>Database error (Main Record): " . $stmt_main->error . "</div>";
            }
            $stmt_main->close();
        } else {
            $status_message = "<div class='alert alert-error'>Database preparation error (Main Record): " . $conn->error . "</div>";
        }
    }

    // 5. Generate HTML Content for the Draft Viewer if successful
    if (strpos($status_message, 'success') !== false) {
        $generated_content = get_expense_list_html(
            htmlspecialchars($invoice_no), 
            date('F j, Y', strtotime($invoice_date)), 
            $items_data, 
            $subtotal, 
            $advance, 
            $grand_total
        );
    }
}


?>

<style>
    /* Custom styles for the expense list form and preview */
    .expense-list-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 15px;
    }
    .expense-list-table th, .expense-list-table td {
        border: 1px solid #ccc;
        padding: 8px;
        text-align: left;
    }
    .expense-list-table th {
        background-color: #f2f2f2;
        font-weight: bold;
    }
    .expense-list-table input[type="text"], .expense-list-table input[type="number"] {
        width: 100%;
        padding: 5px;
        border: 1px solid #ddd;
        box-sizing: border-box;
    }
    .total-summary {
        margin-top: 20px;
        text-align: right;
    }
    .total-summary label {
        display: inline-block;
        width: 200px;
        margin-right: 10px;
        font-weight: normal;
        text-align: left;
    }
    .total-summary input {
        width: 150px;
        text-align: right;
        display: inline-block;
    }
    .letter-page {
        /* This is for the preview pane */
        padding: 20px;
        background: white;
        border: 1px solid #ddd;
        box-shadow: 0 0 10px rgba(0,0,0,0.05);
        min-height: 800px;
        box-sizing: border-box;
    }
    .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;
    }
</style>

<div class="form-card">
    <h3>Create New Expense List / Invoice</h3>
    <p>Fill in the required fields to generate a new expense list and save it to the database.</p>
    
    <?php echo $status_message; ?>

    <form action="admin_dashboard.php?page=expense" method="post" id="expenseForm">
        
        <div style="display: flex; gap: 20px;">
            <div style="flex: 1;">
                <label for="invoice_no">Invoice No.</label>
                <input type="text" name="invoice_no" id="invoice_no" required 
                       placeholder="e.g., 10002025-007" 
                       value="<?php echo htmlspecialchars($_POST['invoice_no'] ?? ''); ?>">
            </div>
            <div style="flex: 1;">
                <label for="invoice_date">Invoice Date</label>
                <input type="date" name="invoice_date" id="invoice_date" required 
                       value="<?php echo htmlspecialchars($_POST['invoice_date'] ?? date('Y-m-d')); ?>">
            </div>
        </div>
        
        <div style="margin-top: 20px; border: 1px solid #ddd; padding: 10px; background-color: #f9f9f9;">
            <label>Bill To (Fixed in template)</label>
            <p style="margin: 0; font-size: 0.9em;"><?php echo $bill_to_company; ?><br><?php echo str_replace('<br>', ', ', $bill_to_details); ?></p>
        </div>

        <label style="margin-top: 25px;">Expense Items (Minimum 1 Required)</label>
        <table class="expense-list-table" id="expense_items_table">
            <thead>
                <tr>
                    <th style="width: 50%;">Description</th>
                    <th style="width: 15%;">Unit Price (BDT)</th>
                    <th style="width: 10%;">Qty</th>
                    <th style="width: 20%;">Total (BDT)</th>
                    <th style="width: 5%;">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                // Restore previous entries if form failed validation but was posted
                if (isset($_POST['generate_expense_list']) && !empty($items_data)): 
                    foreach ($items_data as $i => $item):
                ?>
                    <tr data-index="<?php echo $i; ?>">
                        <td><input type="text" name="description[]" value="<?php echo htmlspecialchars($item['description']); ?>" required></td>
                        <td><input type="number" name="unit_price[]" value="<?php echo htmlspecialchars($item['unit_price']); ?>" step="0.01" min="0.01" required oninput="calculateTotal()"></td>
                        <td><input type="number" name="quantity[]" value="<?php echo htmlspecialchars($item['quantity']); ?>" min="1" required oninput="calculateTotal()"></td>
                        <td><input type="text" name="item_total[]" value="<?php echo number_format($item['total_bdt'], 2); ?>" readonly></td>
                        <td><button type="button" onclick="removeRow(this)" style="background-color: #e74c3c; padding: 5px; color: white;">-</button></td>
                    </tr>
                <?php 
                    endforeach; 
                else: 
                // Default minimum rows
                for ($i = 0; $i < 3; $i++): ?>
                    <tr data-index="<?php echo $i; ?>">
                        <td><input type="text" name="description[]" placeholder="Item description (e.g., Ink)" <?php echo ($i==0) ? 'required' : ''; ?>></td>
                        <td><input type="number" name="unit_price[]" value="" step="0.01" min="0" oninput="calculateTotal()"></td>
                        <td><input type="number" name="quantity[]" value="1" min="1" oninput="calculateTotal()"></td>
                        <td><input type="text" name="item_total[]" value="0.00" readonly></td>
                        <td><button type="button" onclick="removeRow(this)" style="background-color: #e74c3c; padding: 5px; color: white;">-</button></td>
                    </tr>
                <?php endfor; endif; ?>
            </tbody>
        </table>

        <button type="button" onclick="addRow()" style="background-color: #2ecc71; color: white; margin-bottom: 20px;">+ Add Item</button>

        <div class="total-summary">
            <label for="subtotal">Subtotal (BDT)</label>
            <input type="text" id="subtotal_display" value="0.00" readonly style="font-weight: bold; margin-bottom: 10px;"><br>
            
            <label for="advance_payment">Advance Payment (e.g., 50%)</label>
            <input type="number" name="advance_payment" id="advance_payment" value="<?php echo htmlspecialchars($_POST['advance_payment'] ?? '0.00'); ?>" step="0.01" min="0" oninput="calculateTotal()" style="margin-bottom: 10px;"><br>

            <label for="grand_total">Grand Total (BDT)</label>
            <input type="text" id="grand_total_display" value="0.00" readonly style="font-weight: bold; background-color: #ecf0f1;">
        </div>
        
        <div style="margin-top: 30px; display: flex; gap: 10px;">
            <button type="submit" name="generate_expense_list" style="background-color: #3498db; color: white;">Generate & Save Expense List</button>
            <button type="reset" style="background-color: #f39c12; color: white;">Reset Form</button>
            <a href="admin_dashboard.php?page=manage_templates" class="button" style="background-color: #7f8c8d; color: white; padding: 12px 20px; text-decoration: none; border-radius: 5px;">Cancel</a>
        </div>
    </form>
</div>

<?php if (isset($generated_content)): ?>
<div class="form-card" style="margin-top: 20px;">
    <h3>Generated Expense List Draft & Download</h3>
    <p>Review the draft below. Click Download to generate a printable PDF.</p>
    
    <div style="text-align: center; margin-bottom: 20px;">
        <button onclick="downloadPdf('<?php echo htmlspecialchars($_POST['invoice_no'] ?? 'Expense_List'); ?>')" 
                style="background-color: #e74c3c; color: white; padding: 10px 30px; border: none; border-radius: 5px;">
            <i class="fas fa-file-pdf"></i> Download as PDF
        </button>
    </div>
    
    <div id="print_area" class="print-container">
        <?php echo $generated_content; ?>
    </div>
</div>

<script>
    // --- JavaScript for Dynamic Table and Calculations ---

    document.addEventListener('DOMContentLoaded', function() {
        calculateTotal(); // Calculate totals on page load
    });

    function addRow() {
        const tableBody = document.querySelector('#expense_items_table tbody');
        const newRow = tableBody.insertRow();
        const index = tableBody.rows.length -1;
        newRow.setAttribute('data-index', index);
        
        newRow.innerHTML = `
            <td><input type="text" name="description[]" placeholder="Item description"></td>
            <td><input type="number" name="unit_price[]" value="" step="0.01" min="0" oninput="calculateTotal()"></td>
            <td><input type="number" name="quantity[]" value="1" min="1" oninput="calculateTotal()"></td>
            <td><input type="text" name="item_total[]" value="0.00" readonly></td>
            <td><button type="button" onclick="removeRow(this)" style="background-color: #e74c3c; padding: 5px; color: white;">-</button></td>
        `;
        
        // Ensure the first row always has the required attribute for description
        if(tableBody.rows.length > 0) {
            tableBody.rows[0].querySelector('input[name="description[]"]').setAttribute('required', 'required');
        }
    }

    function removeRow(button) {
        const tableBody = document.querySelector('#expense_items_table tbody');
        if (tableBody.rows.length > 1) { // Prevent removing the last row
            button.closest('tr').remove();
            calculateTotal(); // Recalculate after removal
        } else {
            alert("You must have at least one expense item.");
        }
    }

    function calculateTotal() {
        const tableBody = document.querySelector('#expense_items_table tbody');
        let subtotal = 0.00;
        
        // Iterate through each row to calculate item total and subtotal
        Array.from(tableBody.rows).forEach(row => {
            const priceInput = row.querySelector('input[name="unit_price[]"]');
            const qtyInput = row.querySelector('input[name="quantity[]"]');
            const totalInput = row.querySelector('input[name="item_total[]"]');
            
            const price = parseFloat(priceInput.value) || 0;
            const qty = parseInt(qtyInput.value) || 0;
            
            const itemTotal = price * qty;
            
            totalInput.value = itemTotal.toFixed(2);
            subtotal += itemTotal;
        });
        
        const advancePayment = parseFloat(document.getElementById('advance_payment').value) || 0.00;
        const grandTotal = subtotal - advancePayment;
        
        // Update display fields
        document.getElementById('subtotal_display').value = subtotal.toFixed(2);
        document.getElementById('grand_total_display').value = grandTotal.toFixed(2);
    }
    
    // --- PDF Download Simulation using Print Functionality (from company_letterpad) ---
    function downloadPdf(filename) {
        // ... (The PDF download function is intentionally omitted here but should be copied from company_letterpad.php 
        // and adapted to the new styling for a complete solution in a real environment.)
        alert("PDF Download simulated. In a real application, server-side PDF generation is recommended.");
    }
</script>
<?php endif; ?>