<?php
include("../db.php");

if ($_SERVER['REQUEST_METHOD'] !== 'POST' && $_SERVER['REQUEST_METHOD'] !== 'GET') {
    die('Invalid request method');
}

$sale_id = intval($_POST['sale_id'] ?? $_GET['sale_id'] ?? 0);
if (!$sale_id) {
    die('Invalid sale ID');
}

// Get invoice header information
$invoice_sql = "
    SELECT 
        s.*,
        c.phone AS customer_phone,
        c.email AS customer_email,
        c.address AS customer_address,
        u.username AS shift_user,
        sh.start_time AS shift_start,
        sh.end_time AS shift_end
    FROM sales s
    LEFT JOIN customers c ON s.customer_id = c.id
    LEFT JOIN shifts sh ON s.shift_id = sh.id
    LEFT JOIN users u ON sh.user_id = u.id
    WHERE s.id = $sale_id
";

$invoice_result = mysqli_query($conn, $invoice_sql);
if (!$invoice_result || mysqli_num_rows($invoice_result) == 0) {
    die('Invoice not found');
}

$invoice = mysqli_fetch_assoc($invoice_result);

// Get invoice items
$items_sql = "
    SELECT 
        si.*,
        i.item_code,
        i.sku_number,
        cat.name AS category_name,
        sub.name AS subcategory_name
    FROM sale_items si
    LEFT JOIN items i ON si.item_id = i.id
    LEFT JOIN categories cat ON i.category_id = cat.id
    LEFT JOIN sub_categories sub ON i.sub_category_id = sub.id
    WHERE si.sale_id = $sale_id
    ORDER BY si.id
";

$items_result = mysqli_query($conn, $items_sql);

// Get financial transactions
$financial_sql = "
    SELECT 
        at.*,
        je.entry_number,
        je.entry_date
    FROM account_transactions at
    LEFT JOIN journal_entries je ON at.sale_id = je.reference_id AND je.source_type = 'sale'
    WHERE at.sale_id = $sale_id
    ORDER BY at.created_at
";

$financial_result = mysqli_query($conn, $financial_sql);

// Get journal entry details
$journal_sql = "
    SELECT 
        jel.*,
        coa.account_code,
        coa.account_name,
        coa.account_type
    FROM journal_entries je
    JOIN journal_entry_lines jel ON je.id = jel.journal_entry_id
    JOIN chart_of_accounts coa ON jel.account_id = coa.id
    WHERE je.reference_id = $sale_id AND je.source_type = 'sale'
    ORDER BY jel.id
";

$journal_result = mysqli_query($conn, $journal_sql);
?>

<div class="container-fluid">
    <!-- Invoice Header -->
    <div class="row mb-4">
        <div class="col-md-8">
            <h4>Invoice #<?= htmlspecialchars($invoice['invoice_number']) ?></h4>
            <p class="text-muted mb-1">
                <strong>Date:</strong> <?= date('F j, Y \a\t g:i A', strtotime($invoice['sale_date'])) ?>
            </p>
            <p class="text-muted mb-1">
                <strong>Customer:</strong> <?= htmlspecialchars($invoice['customer_name'] ?: 'Walk-in Customer') ?>
                <?php if ($invoice['customer_phone']): ?>
                    | <strong>Phone:</strong> <?= htmlspecialchars($invoice['customer_phone']) ?>
                <?php endif; ?>
                <?php if ($invoice['customer_email']): ?>
                    | <strong>Email:</strong> <?= htmlspecialchars($invoice['customer_email']) ?>
                <?php endif; ?>
            </p>
            <?php if ($invoice['customer_address']): ?>
                <p class="text-muted mb-1">
                    <strong>Address:</strong> <?= htmlspecialchars($invoice['customer_address']) ?>
                </p>
            <?php endif; ?>
        </div>
        <div class="col-md-4 text-end">
            <div class="card bg-light">
                <div class="card-body p-3">
                    <h6 class="mb-2">Order Details</h6>
                    <p class="mb-1">
                        <strong>Mode:</strong> 
                        <span class="badge bg-<?= $invoice['order_mode'] == 'dine_in' ? 'success' : ($invoice['order_mode'] == 'delivery' ? 'warning' : 'info') ?>">
                            <?= ucwords(str_replace('_', ' ', $invoice['order_mode'] ?: 'walk_in')) ?>
                        </span>
                    </p>
                    <?php if ($invoice['table_id']): ?>
                        <p class="mb-1"><strong>Table:</strong> <?= $invoice['table_id'] ?></p>
                    <?php endif; ?>
                    <?php if ($invoice['delivery_charges'] > 0): ?>
                        <p class="mb-1"><strong>Delivery Charges:</strong> Rs <?= number_format($invoice['delivery_charges'], 2) ?></p>
                    <?php endif; ?>
                    <p class="mb-0">
                        <strong>Payment:</strong> 
                        <span class="badge bg-<?= $invoice['payment_method'] == 'cash' ? 'success' : 'primary' ?>">
                            <?= ucfirst($invoice['payment_method']) ?>
                        </span>
                    </p>
                </div>
            </div>
        </div>
    </div>

    <!-- Invoice Items -->
    <div class="row mb-4">
        <div class="col-12">
            <h5>Invoice Items</h5>
            <div class="table-responsive">
                <table class="table table-bordered table-striped">
                    <thead class="table-light">
                        <tr>
                            <th>#</th>
                            <th>Item</th>
                            <th>Category</th>
                            <th>SKU</th>
                            <th class="text-center">Qty</th>
                            <th class="text-end">Unit Price</th>
                            <th class="text-end">Tax Rate</th>
                            <th class="text-end">Total</th>
                            <th>Remarks</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $item_count = 0;
                        $total_items = 0;
                        if (mysqli_num_rows($items_result) > 0): 
                            while ($item = mysqli_fetch_assoc($items_result)): 
                                $item_count++;
                                $total_items += $item['quantity'];
                        ?>
                            <tr>
                                <td><?= $item_count ?></td>
                                <td>
                                    <strong><?= htmlspecialchars($item['item_name']) ?></strong>
                                    <?php if ($item['item_code']): ?>
                                        <br><small class="text-muted">Code: <?= htmlspecialchars($item['item_code']) ?></small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($item['category_name']): ?>
                                        <?= htmlspecialchars($item['category_name']) ?>
                                        <?php if ($item['subcategory_name']): ?>
                                            <br><small class="text-muted"><?= htmlspecialchars($item['subcategory_name']) ?></small>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td><?= htmlspecialchars($item['sku_number'] ?: '-') ?></td>
                                <td class="text-center"><?= $item['quantity'] ?></td>
                                <td class="text-end">Rs <?= number_format($item['unit_price'], 2) ?></td>
                                <td class="text-end"><?= $item['tax_rate'] > 0 ? $item['tax_rate'] . '%' : '0%' ?></td>
                                <td class="text-end"><strong>Rs <?= number_format($item['total_price'], 2) ?></strong></td>
                                <td>
                                    <?php if ($item['remarks']): ?>
                                        <small class="text-muted"><?= htmlspecialchars($item['remarks']) ?></small>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php 
                            endwhile; 
                        else: 
                        ?>
                            <tr><td colspan="9" class="text-center text-muted">No items found</td></tr>
                        <?php endif; ?>
                    </tbody>
                    <tfoot class="table-secondary">
                        <tr>
                            <td colspan="4" class="text-end"><strong>Total Items:</strong></td>
                            <td class="text-center"><strong><?= $total_items ?></strong></td>
                            <td colspan="4"></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>

    <!-- Financial Summary -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0">Financial Summary</h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-6">
                            <p class="mb-1"><strong>Subtotal:</strong></p>
                            <p class="mb-1"><strong>Tax Amount:</strong></p>
                            <p class="mb-1"><strong>Discount:</strong></p>
                            <?php if ($invoice['delivery_charges'] > 0): ?>
                                <p class="mb-1"><strong>Delivery Charges:</strong></p>
                            <?php endif; ?>
                            <p class="mb-0"><strong>Net Amount:</strong></p>
                        </div>
                        <div class="col-6 text-end">
                            <p class="mb-1">Rs <?= number_format($invoice['net_amount'] - $invoice['tax_amount'] + $invoice['discount_amount'], 2) ?></p>
                            <p class="mb-1">Rs <?= number_format($invoice['tax_amount'], 2) ?></p>
                            <p class="mb-1">Rs <?= number_format($invoice['discount_amount'], 2) ?></p>
                            <?php if ($invoice['delivery_charges'] > 0): ?>
                                <p class="mb-1">Rs <?= number_format($invoice['delivery_charges'], 2) ?></p>
                            <?php endif; ?>
                            <p class="mb-0"><strong>Rs <?= number_format($invoice['net_amount'], 2) ?></strong></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0">Transaction Details</h6>
                </div>
                <div class="card-body">
                    <p class="mb-1"><strong>Shift User:</strong> <?= htmlspecialchars($invoice['shift_user'] ?? 'N/A') ?></p>
                    <?php if ($invoice['shift_start']): ?>
                        <p class="mb-1"><strong>Shift:</strong> <?= date('M j, Y g:i A', strtotime($invoice['shift_start'])) ?></p>
                    <?php endif; ?>
                    <p class="mb-1"><strong>Payment Method:</strong> <?= ucfirst($invoice['payment_method']) ?></p>
                    <p class="mb-0"><strong>Order Mode:</strong> <?= ucwords(str_replace('_', ' ', $invoice['order_mode'] ?: 'walk_in')) ?></p>
                </div>
            </div>
        </div>
    </div>

    <!-- Financial Transactions -->
    <?php if (mysqli_num_rows($financial_result) > 0): ?>
    <div class="row mb-4">
        <div class="col-12">
            <h5>Financial Transactions</h5>
            <div class="table-responsive">
                <table class="table table-bordered table-striped">
                    <thead class="table-light">
                        <tr>
                            <th>Date</th>
                            <th>Type</th>
                            <th>Amount</th>
                            <th>Description</th>
                            <th>Journal Entry</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($transaction = mysqli_fetch_assoc($financial_result)): ?>
                            <tr>
                                <td><?= date('M j, Y g:i A', strtotime($transaction['created_at'])) ?></td>
                                <td>
                                    <span class="badge bg-<?= $transaction['account_type'] == 'cash' ? 'success' : 'primary' ?>">
                                        <?= ucfirst($transaction['account_type']) ?>
                                    </span>
                                </td>
                                <td class="text-end">Rs <?= number_format($transaction['amount'], 2) ?></td>
                                <td><?= htmlspecialchars($transaction['description']) ?></td>
                                <td>
                                    <?php if ($transaction['entry_number']): ?>
                                        <small class="text-muted"><?= htmlspecialchars($transaction['entry_number']) ?></small>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Journal Entries -->
    <?php if (mysqli_num_rows($journal_result) > 0): ?>
    <div class="row">
        <div class="col-12">
            <h5>Journal Entries</h5>
            <div class="table-responsive">
                <table class="table table-bordered table-striped">
                    <thead class="table-light">
                        <tr>
                            <th>Account</th>
                            <th>Account Name</th>
                            <th>Type</th>
                            <th class="text-end">Debit</th>
                            <th class="text-end">Credit</th>
                            <th>Description</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($entry = mysqli_fetch_assoc($journal_result)): ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($entry['account_code']) ?></strong></td>
                                <td><?= htmlspecialchars($entry['account_name']) ?></td>
                                <td>
                                    <span class="badge bg-<?= $entry['account_type'] == 'asset' ? 'primary' : ($entry['account_type'] == 'revenue' ? 'success' : 'warning') ?>">
                                        <?= ucfirst($entry['account_type']) ?>
                                    </span>
                                </td>
                                <td class="text-end">
                                    <?php if ($entry['debit_amount'] > 0): ?>
                                        <strong>Rs <?= number_format($entry['debit_amount'], 2) ?></strong>
                                    <?php else: ?>
                                        -
                                    <?php endif; ?>
                                </td>
                                <td class="text-end">
                                    <?php if ($entry['credit_amount'] > 0): ?>
                                        <strong>Rs <?= number_format($entry['credit_amount'], 2) ?></strong>
                                    <?php else: ?>
                                        -
                                    <?php endif; ?>
                                </td>
                                <td><?= htmlspecialchars($entry['description']) ?></td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>
