<?php
// config.php ko shaamil karein, jo session aur database connection ko sambhalega.
require_once 'config.php';

// Yeh function jaanch karega ki user ke paas zaroori role hai ya nahi.
if (!function_exists('userHasRole')) {
    function userHasRole($required_roles) {
        if (!isset($_SESSION['user_roles'])) return false;
        if (!is_array($required_roles)) {
            $required_roles = [$required_roles];
        }
        return count(array_intersect($required_roles, $_SESSION['user_roles'])) > 0;
    }
}

// Suraksha jaanch: Sirf zaroori roles waale users hi is page ko access kar sakte hain.
if (!userHasRole(['Admin', 'Manager', 'SMM', 'Sales'])) {
    header('Location: dashboard.php');
    exit();
}

// Invoice ID URL se prapt karein
$invoice_id = $_GET['id'] ?? 0;
if (!is_numeric($invoice_id) || $invoice_id <= 0) {
    header('Location: invoices.php');
    exit();
}

// --- FORM SUBMISSION LOGIC ---
// Saari processing HTML print hone se pehle hogi.

// 1. PAYMENT RECORDING LOGIC
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['record_payment'])) {
    $payment_amount = (float)$_POST['payment_amount'];
    $payment_date = $_POST['payment_date'];
    $payment_method = $_POST['payment_method'];
    $notes = $_POST['notes'] ?? '';

    if ($payment_amount > 0 && !empty($payment_date) && !empty($payment_method)) {
        $stmt_payment = $conn->prepare("INSERT INTO invoice_payments (invoice_id, amount_paid, payment_date, payment_method, notes) VALUES (?, ?, ?, ?, ?)");
        if ($stmt_payment) {
            $stmt_payment->bind_param("idsss", $invoice_id, $payment_amount, $payment_date, $payment_method, $notes);
            if ($stmt_payment->execute()) {
                $conn->query("UPDATE invoices SET amount_paid = amount_paid + $payment_amount WHERE id = $invoice_id");
                $check_stmt = $conn->prepare("SELECT total_amount, amount_paid FROM invoices WHERE id = ?");
                $check_stmt->bind_param("i", $invoice_id);
                $check_stmt->execute();
                $result = $check_stmt->get_result()->fetch_assoc();
                if ($result['amount_paid'] >= $result['total_amount']) {
                    $conn->query("UPDATE invoices SET status = 'Paid' WHERE id = $invoice_id");
                }
                $_SESSION['message'] = "Payment recorded successfully!";
                $_SESSION['message_type'] = 'success';
            } else {
                $_SESSION['message'] = "Error recording payment: " . $stmt_payment->error;
            }
            $stmt_payment->close();
        } else {
             $_SESSION['message'] = "Database Error: Could not prepare payment statement.";
        }
    } else {
        $_SESSION['message'] = "Please fill all required payment fields.";
    }
    $_SESSION['message_type'] = 'error';
    header("Location: view-invoice.php?id=" . $invoice_id);
    exit();
}

// 2. INVOICE UPDATE LOGIC
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_invoice'])) {
    $client_name = $_POST['client_name'];
    $client_address = $_POST['client_address'];
    $invoice_date = $_POST['invoice_date'];
    $due_date = $_POST['due_date'];
    $new_total_amount = 0;

    $conn->begin_transaction();
    try {
        // Step 1: Mukhya invoice details update karein
        $stmt_invoice = $conn->prepare("UPDATE invoices SET client_name = ?, client_address = ?, invoice_date = ?, due_date = ? WHERE id = ?");
        $stmt_invoice->bind_param("ssssi", $client_name, $client_address, $invoice_date, $due_date, $invoice_id);
        $stmt_invoice->execute();
        $stmt_invoice->close();

        // Step 2: Purane items delete karein
        $stmt_delete = $conn->prepare("DELETE FROM invoice_items WHERE invoice_id = ?");
        $stmt_delete->bind_param("i", $invoice_id);
        $stmt_delete->execute();
        $stmt_delete->close();

        // Step 3: Naye items insert karein
        $stmt_item = $conn->prepare("INSERT INTO invoice_items (invoice_id, item_description, quantity, unit_price, total) VALUES (?, ?, ?, ?, ?)");
        if(isset($_POST['items'])) {
            foreach ($_POST['items'] as $item) {
                $description = $item['description'];
                $quantity = (float)$item['quantity'];
                $price = (float)$item['price'];
                $item_total = $quantity * $price;
                $new_total_amount += $item_total;

                if (!empty($description) && $quantity > 0) {
                    $stmt_item->bind_param("isddd", $invoice_id, $description, $quantity, $price, $item_total);
                    $stmt_item->execute();
                }
            }
        }
        $stmt_item->close();

        // Step 4: Total amount update karein
        $stmt_update_total = $conn->prepare("UPDATE invoices SET total_amount = ? WHERE id = ?");
        $stmt_update_total->bind_param("di", $new_total_amount, $invoice_id);
        $stmt_update_total->execute();
        $stmt_update_total->close();

        $conn->commit();
        $_SESSION['message'] = "Invoice updated successfully!";
        $_SESSION['message_type'] = 'success';

    } catch (mysqli_sql_exception $exception) {
        $conn->rollback();
        $_SESSION['message'] = "Error updating invoice: " . $exception->getMessage();
        $_SESSION['message_type'] = 'error';
    }
    
    header("Location: view-invoice.php?id=" . $invoice_id);
    exit();
}


// --- PAGE DISPLAY LOGIC ---
$message = $_SESSION['message'] ?? '';
$message_type = $_SESSION['message_type'] ?? '';
unset($_SESSION['message'], $_SESSION['message_type']);

require_once 'header.php';

// Invoice data prapt karein
$stmt = $conn->prepare("SELECT * FROM invoices WHERE id = ?");
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$invoice = $stmt->get_result()->fetch_assoc();

if (!$invoice) {
    echo "<div class='p-6 text-center text-red-600'>Invoice not found.</div>";
    require_once 'footer.php';
    exit();
}

$items_stmt = $conn->prepare("SELECT * FROM invoice_items WHERE invoice_id = ?");
$items_stmt->bind_param("i", $invoice_id);
$items_stmt->execute();
$invoice_items = $items_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$payments_stmt = $conn->prepare("SELECT * FROM invoice_payments WHERE invoice_id = ? ORDER BY payment_date DESC");
$payments_stmt->bind_param("i", $invoice_id);
$payments_stmt->execute();
$payments = $payments_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$settings = [];
$settings_result = $conn->query("SELECT * FROM app_settings");
while ($row = $settings_result->fetch_assoc()) {
    $settings[$row['setting_key']] = $row['setting_value'];
}
$clients_result = $conn->query("SELECT id, name FROM clients ORDER BY name ASC");
$clients = $clients_result->fetch_all(MYSQLI_ASSOC);

$balance_due = $invoice['total_amount'] - $invoice['amount_paid'];
?>
<title>View Invoice #<?php echo htmlspecialchars($invoice['id']); ?> - Digify OS</title>

<div class="p-6 md:p-10" x-data="{ paymentModalOpen: false, editModalOpen: false }">

    <?php if ($message): ?>
    <div class="mb-4 p-4 rounded-lg <?php echo ($message_type == 'error') ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800'; ?>">
        <?php echo htmlspecialchars($message); ?>
    </div>
    <?php endif; ?>

    <div class="flex justify-between items-center mb-6 no-print">
        <a href="invoices.php" class="text-blue-600 hover:underline">&larr; Back to Invoices</a>
        <div>
            <button @click="editModalOpen = true" class="px-4 py-2 bg-yellow-500 text-white font-semibold rounded-lg shadow-md hover:bg-yellow-600 mr-2">Edit Invoice</button>
            <button @click="paymentModalOpen = true" class="px-4 py-2 bg-green-600 text-white font-semibold rounded-lg shadow-md hover:bg-green-700 mr-2">Record Payment</button>
            <button id="download-pdf-btn" class="px-4 py-2 bg-blue-600 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700">Download PDF</button>
        </div>
    </div>
    
    <div id="invoice-to-print" class="bg-white p-8 rounded-lg shadow-lg max-w-4xl mx-auto font-sans">
       <!-- Invoice Body -->
        <header class="flex justify-between items-start pb-6 border-b-2 border-gray-200">
            <div class="flex items-center">
                <?php if (!empty($settings['company_logo'])): ?>
                    <img src="<?php echo htmlspecialchars($settings['company_logo']); ?>" alt="Company Logo" class="max-h-20 mr-4">
                <?php endif; ?>
                <div>
                    <h1 class="text-2xl font-bold text-gray-800"><?php echo htmlspecialchars($settings['company_name'] ?? 'Your Company'); ?></h1>
                    <p class="text-xs text-gray-500"><?php echo nl2br(htmlspecialchars($settings['company_address'] ?? 'Your Address')); ?></p>
                    <p class="text-xs text-gray-500 mt-1"><?php echo htmlspecialchars($settings['company_pan_gst'] ?? ''); ?></p>
                </div>
            </div>
            <div class="text-right">
                <h2 class="text-4xl font-bold text-gray-700 uppercase">INVOICE</h2>
                <p class="text-sm text-gray-500 mt-1"># <?php echo htmlspecialchars(str_pad($invoice['id'], 4, '0', STR_PAD_LEFT)); ?></p>
            </div>
        </header>
        <section class="flex justify-between items-start mt-8">
            <div>
                <h3 class="text-sm font-semibold text-gray-500 uppercase">Bill To</h3>
                <p class="text-lg font-bold text-gray-800 mt-1"><?php echo htmlspecialchars($invoice['client_name']); ?></p>
                <p class="text-sm text-gray-600"><?php echo nl2br(htmlspecialchars($invoice['client_address'])); ?></p>
            </div>
            <div class="text-right">
                <div class="grid grid-cols-2 gap-x-6">
                    <span class="font-semibold text-gray-600">Invoice Date:</span>
                    <span class="text-gray-800"><?php echo date("d M, Y", strtotime($invoice['invoice_date'])); ?></span>
                    <span class="font-semibold text-gray-600">Due Date:</span>
                    <span class="text-gray-800"><?php echo date("d M, Y", strtotime($invoice['due_date'])); ?></span>
                </div>
                 <div class="mt-4 p-3 bg-gray-50 rounded-lg">
                    <?php
                        $status_color = 'bg-yellow-100 text-yellow-800';
                        if ($invoice['status'] == 'Paid') $status_color = 'bg-green-100 text-green-800';
                        if ($balance_due > 0 && strtotime($invoice['due_date']) < time()) $status_color = 'bg-red-100 text-red-800';
                    ?>
                    <span class="px-3 py-1 text-sm font-bold rounded-full <?php echo $status_color; ?>">
                        <?php 
                            if ($balance_due > 0 && strtotime($invoice['due_date']) < time()) {
                                echo 'Overdue';
                            } else {
                                echo htmlspecialchars($invoice['status']);
                            }
                        ?>
                    </span>
                 </div>
            </div>
        </section>
        <section class="mt-10">
            <table class="w-full text-left">
                <thead class="bg-gray-100">
                    <tr>
                        <th class="py-2 px-4 font-semibold text-gray-600 uppercase text-sm">Item Description</th>
                        <th class="py-2 px-4 font-semibold text-gray-600 uppercase text-sm text-center">Qty</th>
                        <th class="py-2 px-4 font-semibold text-gray-600 uppercase text-sm text-right">Unit Price</th>
                        <th class="py-2 px-4 font-semibold text-gray-600 uppercase text-sm text-right">Total</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($invoice_items as $item): ?>
                        <tr class="border-b">
                            <td class="py-3 px-4"><?php echo htmlspecialchars($item['item_description']); ?></td>
                            <td class="py-3 px-4 text-center"><?php echo htmlspecialchars($item['quantity']); ?></td>
                            <td class="py-3 px-4 text-right">₹<?php echo number_format($item['unit_price'], 2); ?></td>
                            <td class="py-3 px-4 text-right">₹<?php echo number_format($item['total'], 2); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </section>
        <section class="flex justify-end mt-6">
            <div class="w-full md:w-2/5">
                <div class="flex justify-between py-2 text-sm">
                    <span class="font-semibold text-gray-600">Subtotal:</span>
                    <span class="font-medium text-gray-800">₹<?php echo number_format($invoice['total_amount'], 2); ?></span>
                </div>
                 <div class="flex justify-between py-2 text-sm">
                    <span class="font-semibold text-gray-600">Total Paid:</span>
                    <span class="font-medium text-gray-800">₹<?php echo number_format($invoice['amount_paid'], 2); ?></span>
                </div>
                <div class="flex justify-between py-3 border-t-2 mt-2 bg-gray-100 px-4 rounded-lg">
                    <span class="font-bold text-lg text-gray-800">Balance Due:</span>
                    <span class="font-bold text-lg text-red-600">₹<?php echo number_format($balance_due, 2); ?></span>
                </div>
            </div>
        </section>
        <footer class="mt-10 border-t-2 pt-6">
             <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
                <?php if (!empty($settings['invoice_notes'])): ?>
                <div class="md:col-span-2"><h4 class="text-sm font-semibold text-gray-500 uppercase mb-2">Notes & Terms</h4><p class="text-xs text-gray-600 whitespace-pre-wrap"><?php echo htmlspecialchars($settings['invoice_notes']); ?></p></div>
                <?php endif; ?>
                <div class="md:col-span-1">
                     <?php if (!empty($settings['bank_details'])): ?>
                     <div><h4 class="text-sm font-semibold text-gray-500 uppercase mb-2">Bank Details</h4><p class="text-xs text-gray-600 whitespace-pre-wrap"><?php echo htmlspecialchars($settings['bank_details']); ?></p></div>
                     <?php endif; ?>
                      <?php if (!empty($settings['payment_qr_code'])): ?>
                     <div class="mt-4"><h4 class="text-sm font-semibold text-gray-500 uppercase mb-2">Scan to Pay</h4><img src="<?php echo htmlspecialchars($settings['payment_qr_code']); ?>" alt="Payment QR Code" class="h-24 w-24"></div>
                     <?php endif; ?>
                </div>
             </div>
        </footer>
        <?php if (!empty($payments)): ?>
        <div class="mt-10 border-t pt-6">
            <h3 class="font-semibold text-gray-700 mb-4">Payment History</h3>
            <div class="space-y-3">
                <?php foreach ($payments as $payment): ?>
                <div class="bg-gray-50 p-3 rounded-md flex justify-between items-center">
                    <div>
                        <p class="font-medium text-gray-800">Paid on <?php echo date("d M, Y", strtotime($payment['payment_date'])); ?> via <?php echo htmlspecialchars($payment['payment_method']); ?></p>
                        <?php if(!empty($payment['notes'])): ?><p class="text-sm text-gray-500">Note: <?php echo htmlspecialchars($payment['notes']); ?></p><?php endif; ?>
                    </div>
                    <div class="font-bold text-green-600">₹<?php echo number_format($payment['amount_paid'], 2); ?></div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Edit Invoice Modal -->
    <div x-show="editModalOpen" x-transition class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50 no-print" @keydown.escape.window="editModalOpen = false" style="display: none;">
        <div class="bg-white rounded-lg shadow-xl p-8 w-full max-w-3xl max-h-[90vh] flex flex-col" @click.away="editModalOpen = false">
            <h3 class="text-xl font-semibold mb-6 flex-shrink-0">Edit Invoice #<?php echo htmlspecialchars($invoice['id']); ?></h3>
            <div class="overflow-y-auto pr-4 flex-grow">
                <form method="POST" action="view-invoice.php?id=<?php echo $invoice_id; ?>" x-data="editInvoiceForm()">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                        <div>
                            <h4 class="text-lg font-semibold mb-4 text-gray-700">Bill To:</h4>
                            <div class="space-y-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-600">Client/Company Name</label>
                                    <input type="text" name="client_name" x-model="invoiceData.client_name" required class="mt-1 block w-full border-gray-300 rounded-md">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-600">Address</label>
                                    <textarea name="client_address" rows="3" x-model="invoiceData.client_address" class="mt-1 block w-full border-gray-300 rounded-md"></textarea>
                                </div>
                            </div>
                        </div>
                        <div>
                            <h4 class="text-lg font-semibold mb-4 text-gray-700">Invoice Details:</h4>
                            <div class="space-y-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-600">Invoice Date</label>
                                    <input type="date" name="invoice_date" x-model="invoiceData.invoice_date" required class="mt-1 block w-full border-gray-300 rounded-md">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-600">Due Date</label>
                                    <input type="date" name="due_date" x-model="invoiceData.due_date" required class="mt-1 block w-full border-gray-300 rounded-md">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="mt-10">
                        <h4 class="text-lg font-semibold text-gray-700 border-b pb-2 mb-4">Items</h4>
                        <div class="space-y-4">
                            <template x-for="(item, index) in items" :key="index">
                                <div class="grid grid-cols-12 gap-4 items-center">
                                    <div class="col-span-5"><input type="text" :name="'items['+index+'][description]'" x-model="item.description" placeholder="Item Description" class="w-full border-gray-300 rounded-md text-sm"></div>
                                    <div class="col-span-2"><input type="number" :name="'items['+index+'][quantity]'" x-model.number="item.quantity" @input="calculateTotal()" placeholder="Qty" class="w-full border-gray-300 rounded-md text-sm"></div>
                                    <div class="col-span-2"><input type="number" step="0.01" :name="'items['+index+'][price]'" x-model.number="item.price" @input="calculateTotal()" placeholder="Price" class="w-full border-gray-300 rounded-md text-sm"></div>
                                    <div class="col-span-2 text-right"><span class="font-medium text-sm" x-text="formatCurrency(item.quantity * item.price)"></span></div>
                                    <div class="col-span-1"><button type="button" @click="removeItem(index)" class="text-red-500 hover:text-red-700">&times;</button></div>
                                </div>
                            </template>
                        </div>
                        <button type="button" @click="addItem()" class="mt-4 px-4 py-2 bg-blue-500 text-white rounded-md text-sm">+ Add Item</button>
                    </div>
                    <div class="flex justify-end mt-8">
                        <span class="font-bold text-lg">Total: </span><span class="font-bold text-lg ml-2" x-text="formatCurrency(total)"></span>
                    </div>
                    <div class="flex justify-end mt-8 border-t pt-6 flex-shrink-0">
                        <button type="button" @click="editModalOpen = false" class="px-4 py-2 border rounded-md mr-2">Cancel</button>
                        <button type="submit" name="update_invoice" class="px-4 py-2 bg-blue-600 text-white rounded-md">Save Changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>


    <!-- Record Payment Modal -->
    <div x-show="paymentModalOpen" x-transition class="fixed inset-0 bg-gray-900 bg-opacity-50 flex items-center justify-center z-40 no-print" @keydown.escape.window="paymentModalOpen = false" style="display: none;">
        <div class="bg-white rounded-lg shadow-xl p-8 w-full max-w-md" @click.away="paymentModalOpen = false">
            <h3 class="text-xl font-semibold mb-6">Record Payment for Invoice #<?php echo htmlspecialchars($invoice['id']); ?></h3>
            <form method="POST" action="view-invoice.php?id=<?php echo $invoice_id; ?>">
                <div class="space-y-4">
                    <div><label for="payment_amount" class="block text-sm font-medium">Amount</label><input type="number" step="0.01" name="payment_amount" value="<?php echo $balance_due; ?>" required class="mt-1 block w-full border-gray-300 rounded-md"></div>
                    <div><label for="payment_date" class="block text-sm font-medium">Payment Date</label><input type="date" name="payment_date" value="<?php echo date('Y-m-d'); ?>" required class="mt-1 block w-full border-gray-300 rounded-md"></div>
                    <div><label for="payment_method" class="block text-sm font-medium">Payment Method</label><select name="payment_method" required class="mt-1 block w-full border-gray-300 rounded-md"><option>Bank Transfer</option><option>Cash</option><option>Cheque</option><option>UPI</option><option>Other</option></select></div>
                    <div><label for="notes" class="block text-sm font-medium">Notes (Optional)</label><textarea name="notes" rows="2" class="mt-1 block w-full border-gray-300 rounded-md"></textarea></div>
                </div>
                <div class="flex justify-end mt-8"><button type="button" @click="paymentModalOpen = false" class="px-4 py-2 border rounded-md mr-2">Cancel</button><button type="submit" name="record_payment" class="px-4 py-2 bg-blue-600 text-white rounded-md">Save Payment</button></div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.2/html2pdf.bundle.min.js"></script>
<script>
document.getElementById('download-pdf-btn').addEventListener('click', function () {
    const element = document.getElementById('invoice-to-print');
    const btn = this;
    const opt = { margin: 0.5, filename: 'Invoice-<?php echo htmlspecialchars(str_pad($invoice['id'], 4, '0', STR_PAD_LEFT)); ?>.pdf', image: { type: 'jpeg', quality: 0.98 }, html2canvas:  { scale: 2, useCORS: true }, jsPDF: { unit: 'in', format: 'a4', orientation: 'portrait' } };
    btn.innerText = 'Downloading...';
    btn.disabled = true;
    html2pdf().from(element).set(opt).save().then(() => {
        btn.innerText = 'Download PDF';
        btn.disabled = false;
    });
});

function editInvoiceForm() {
    const invoiceDataPHP = <?php echo json_encode($invoice); ?>;
    const itemsDataPHP = <?php echo json_encode($invoice_items); ?>;

    return {
        invoiceData: {
            client_name: invoiceDataPHP.client_name,
            client_address: invoiceDataPHP.client_address,
            invoice_date: invoiceDataPHP.invoice_date,
            due_date: invoiceDataPHP.due_date
        },
        items: itemsDataPHP.map(item => ({
            description: item.item_description,
            quantity: parseFloat(item.quantity),
            price: parseFloat(item.unit_price)
        })),
        total: 0,
        init() {
            this.calculateTotal();
        },
        addItem() { this.items.push({ description: '', quantity: 1, price: 0 }); },
        removeItem(index) {
            if (this.items.length > 1) this.items.splice(index, 1);
            this.calculateTotal();
        },
        calculateTotal() {
            let subtotal = 0;
            this.items.forEach(item => {
                subtotal += (parseFloat(item.quantity) || 0) * (parseFloat(item.price) || 0);
            });
            this.total = subtotal;
        },
        formatCurrency(amount) {
            return new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format(amount);
        }
    }
}
</script>

<?php require_once 'footer.php'; ?>

