<div class="page-header" style="margin-bottom: 16px;">
    <div style="flex: 1;">
        <h1 style="font-size: 1.4rem; margin-bottom: 4px;">Sales & Invoices</h1>
        <div class="page-subtitle" style="font-size: 0.85rem;">Track every transaction and payment record.</div>
    </div>
    <div class="flex gap-2">
        <button onclick="window.print()" class="btn btn-outline" style="padding: 6px 12px; font-size: 0.85rem;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 16px; height: 16px;"><polyline points="6 9 6 2 18 2 18 9"></polyline><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v-5a2 2 0 0 1-2 2h-2"></path><rect x="6" y="14" width="12" height="8"></rect></svg>
            Print
        </button>
        <a href="<?= APP_URL ?>/sales/export?<?= http_build_query($_GET) ?>" class="btn btn-outline" style="padding: 6px 12px; font-size: 0.85rem;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 16px; height: 16px;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
            Export CSV
        </a>
        <a href="<?= APP_URL ?>/sales/pos" class="btn btn-primary" style="padding: 6px 12px; font-size: 0.85rem;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 16px; height: 16px;"><circle cx="9" cy="21" r="1"></circle><circle cx="20" cy="21" r="1"></circle><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path></svg>
            POS Terminal
        </a>
    </div>
</div>

<style>
    .dropdown-item:hover {
        background-color: #f5f5f5;
    }
    .show {
        display: block !important;
    }

    .print-header {
        display: none !important;
    }

    @media print {
        @page {
            margin: 10mm;
            size: landscape;
        }
        .page-header,
        .filter-bar,
        .pagination-links,
        .text-right button,
        .dropdown-item,
        .sidebar,
        nav,
        aside {
            display: none !important;
        }
        .card {
            border: none;
            box-shadow: none;
            margin: 0;
            padding: 0;
        }
        .table-wrapper {
            overflow: visible;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 10px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 4px 6px;
            white-space: nowrap;
        }
        th:last-child,
        td:last-child {
            display: none !important;
        }
        tfoot tr {
            background: #667eea !important;
            color: white !important;
        }
        body {
            margin: 0;
            padding: 0;
            font-size: 10px;
        }
        .main-content,
        .content {
            width: 100% !important;
            max-width: 100% !important;
            margin: 0 !important;
            padding: 0 !important;
        }
        .print-header {
            display: block !important;
            margin-bottom: 15px;
            padding: 15px;
            border-bottom: 2px solid #333;
        }
        .print-footer {
            display: block !important;
            margin-top: 15px;
            padding: 10mm;
            border-top: 2px solid #333;
            background: #f9f9f9 !important;
        }
        .print-header h1 {
            margin: 0 0 8px 0;
            font-size: 18px;
            font-weight: bold;
        }
        .print-header .business-info {
            margin: 3px 0;
            font-size: 11px;
        }
        .print-header .print-title {
            margin: 10px 0 0 0;
            font-size: 14px;
            font-weight: bold;
        }
    }
</style>

<?php
$tenant = Auth::tenant();
$businessName = $tenant['business_name'] ?? ($tenant['name'] ?? 'Business Name');
$address = $tenant['address'] ?? '';
$phone = $tenant['phone'] ?? '';
$email = $tenant['email'] ?? '';
?>
<div class="print-header" style="display: none;">
    <h1><?= e($businessName) ?></h1>
    <div class="business-info">
        <?php if ($address): ?><?= e($address) ?><br><?php endif; ?>
        <?php if ($phone): ?>Phone: <?= e($phone) ?><br><?php endif; ?>
        <?php if ($email): ?>Email: <?= e($email) ?><?php endif; ?>
    </div>
    <div class="print-title">Sales & Invoices Report</div>
    <div class="business-info">
        Generated on: <?= date('F j, Y H:i') ?>
    </div>
</div>

<div class="card mb-4" style="padding: 12px;">
    <div class="filter-bar">
        <form action="" method="GET">
            <!-- Row 1: Search and Date Range (most common filters) -->
            <div class="flex gap-2 items-center" style="margin-bottom: 8px;">
                <div class="search-box" style="flex: 1; min-width: 200px;">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 14px; height: 14px;"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
                    <input type="text" name="search" class="form-control" placeholder="Search Sale No, Customer..." value="<?= e($_GET['search'] ?? '') ?>" style="padding: 6px 10px 6px 32px; font-size: 0.85rem;">
                </div>
                <div class="flex gap-2 items-center">
                    <input type="date" name="date_from" class="form-control" placeholder="From" style="width: 140px; padding: 6px 8px; font-size: 0.85rem;" value="<?= e($_GET['date_from'] ?? '') ?>">
                    <span style="color: #999; font-size: 0.8rem;">to</span>
                    <input type="date" name="date_to" class="form-control" placeholder="To" style="width: 140px; padding: 6px 8px; font-size: 0.85rem;" value="<?= e($_GET['date_to'] ?? '') ?>">
                </div>
            </div>
            
            <!-- Row 2: Dropdowns and Actions -->
            <div class="flex gap-2 items-center flex-wrap">
                <select name="status" class="form-control" style="width: 130px; padding: 6px 8px; font-size: 0.85rem;" onchange="this.form.submit()">
                    <option value="">All Statuses</option>
                    <option value="completed" <?= ($_GET['status'] ?? '') == 'completed' ? 'selected' : '' ?>>Completed</option>
                    <option value="pending" <?= ($_GET['status'] ?? '') == 'pending' ? 'selected' : '' ?>>Pending</option>
                    <option value="cancelled" <?= ($_GET['status'] ?? '') == 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
                </select>

                <select name="location_id" class="form-control" style="width: 150px; padding: 6px 8px; font-size: 0.85rem;" onchange="this.form.submit()">
                    <option value="">All Locations</option>
                    <?php
                    $locations = db()->prepare("SELECT id, name FROM locations WHERE tenant_id = ? AND is_active = 1 ORDER BY name");
                    $locations->execute([Auth::tenantId()]);
                    foreach ($locations->fetchAll() as $loc):
                    ?>
                        <option value="<?= $loc['id'] ?>" <?= ($_GET['location_id'] ?? '') == $loc['id'] ? 'selected' : '' ?>><?= e($loc['name']) ?></option>
                    <?php endforeach; ?>
                </select>

                <select name="user_id" class="form-control" style="width: 150px; padding: 6px 8px; font-size: 0.85rem;" onchange="this.form.submit()">
                    <option value="">All Users</option>
                    <?php
                    $users = db()->prepare("SELECT id, name FROM users WHERE tenant_id = ? ORDER BY name");
                    $users->execute([Auth::tenantId()]);
                    foreach ($users->fetchAll() as $usr):
                    ?>
                        <option value="<?= $usr['id'] ?>" <?= ($_GET['user_id'] ?? '') == $usr['id'] ? 'selected' : '' ?>><?= e($usr['name']) ?></option>
                    <?php endforeach; ?>
                </select>

                <select name="per_page" class="form-control" style="width: 100px; padding: 6px 8px; font-size: 0.85rem;" onchange="this.form.submit()">
                    <option value="20" <?= ($_GET['per_page'] ?? '20') == '20' ? 'selected' : '' ?>>20</option>
                    <option value="50" <?= ($_GET['per_page'] ?? '20') == '50' ? 'selected' : '' ?>>50</option>
                    <option value="100" <?= ($_GET['per_page'] ?? '20') == '100' ? 'selected' : '' ?>>100</option>
                    <option value="all" <?= ($_GET['per_page'] ?? '20') == 'all' ? 'selected' : '' ?>>All</option>
                </select>

                <div style="margin-left: auto;" class="flex gap-2">
                    <button type="submit" class="btn btn-primary btn-sm" style="padding: 6px 12px; font-size: 0.85rem;">Filter</button>
                    <?php if (!empty($_GET)): ?>
                        <a href="<?= APP_URL ?>/sales" class="btn btn-outline btn-sm" style="padding: 6px 12px; font-size: 0.85rem;">Clear</a>
                    <?php endif; ?>
                </div>
            </div>
        </form>
    </div>

    <div class="summary-section" style="padding: 16px; background: #f9f9f9; border-top: 1px solid #e5e5e5; border-bottom: 1px solid #e5e5e5; margin-top: 12px;">
        <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; font-size: 0.85rem;">
            <div style="display: flex; justify-content: space-between; align-items: center; padding: 8px; background: #fff; border-radius: 6px; border: 1px solid #e5e5e5;">
                <span style="color: #666;">Total Sales:</span>
                <span style="font-weight: 700; color: #28a745;"><?= money($sales['totals']['total_amount']) ?></span>
            </div>
            <div style="display: flex; justify-content: space-between; align-items: center; padding: 8px; background: #fff; border-radius: 6px; border: 1px solid #e5e5e5;">
                <span style="color: #666;">Total Paid:</span>
                <span style="font-weight: 700; color: #16a34a;"><?= money($sales['totals']['total_paid']) ?></span>
            </div>
            <div style="display: flex; justify-content: space-between; align-items: center; padding: 8px; background: #fff; border-radius: 6px; border: 1px solid #e5e5e5;">
                <span style="color: #666;">Outstanding:</span>
                <span style="font-weight: 700; color: #dc3545;"><?= money(max(0, $sales['totals']['outstanding'])) ?></span>
            </div>
            <div style="display: flex; justify-content: space-between; align-items: center; padding: 8px; background: #fff; border-radius: 6px; border: 1px solid #e5e5e5;">
                <span style="color: #666;">Transactions:</span>
                <span style="font-weight: 700; color: var(--primary);"><?= count($sales['data']) ?></span>
            </div>
        </div>

        <?php if (!empty($sales['totals']['by_method'])): ?>
        <div style="margin-top: 12px; padding-top: 12px; border-top: 1px dashed #ccc;">
            <div style="color: #666; font-size: 0.75rem; font-weight: 600; margin-bottom: 8px; text-transform: uppercase;">Payment Breakdown (Paid Amounts)</div>
            <div style="display: flex; gap: 12px; flex-wrap: wrap;">
                <?php foreach ($sales['totals']['by_method'] as $method => $amount): ?>
                <div style="display: flex; align-items: center; gap: 6px; background: #fff; padding: 4px 12px; border-radius: 20px; border: 1px solid #e5e5e5; font-size: 0.8rem;">
                    <span style="color: #666; text-transform: capitalize;"><?= e($method) ?>:</span>
                    <span style="font-weight: 700; color: #16a34a;"><?= money($amount) ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <div class="table-wrapper" style="margin-top: 12px; overflow: visible;">
        <table style="font-size: 0.85rem;">
            <thead>
                <tr>
                    <th style="padding: 8px 10px; font-size: 0.75rem;">Ref No</th>
                    <th style="padding: 8px 10px; font-size: 0.75rem;">Date & Time</th>
                    <th style="padding: 8px 10px; font-size: 0.75rem;">Customer</th>
                    <th style="padding: 8px 10px; font-size: 0.75rem;">Location</th>
                    <th style="padding: 8px 10px; font-size: 0.75rem;">User</th>
                    <th style="padding: 8px 10px; font-size: 0.75rem;">Amount</th>
                    <th style="padding: 8px 10px; font-size: 0.75rem;">Paid</th>
                    <th style="padding: 8px 10px; font-size: 0.75rem;">Payment</th>
                    <th style="padding: 8px 10px; font-size: 0.75rem;">Payment Type</th>
                    <th style="padding: 8px 10px; font-size: 0.75rem;">Status</th>
                    <th style="width: 60px; padding: 8px 10px; font-size: 0.75rem;"></th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $pageTotalAmount = 0;
                $pageTotalPaid = 0;
                if (empty($sales['data'])): ?>
                <tr>
                    <td colspan="11" class="text-center" style="padding: 24px 10px;">No sales found matching your criteria.</td>
                </tr>
                <?php else: 
                    foreach ($sales['data'] as $s): 
                        // Calculate page totals
                        $pageTotalAmount += (float)$s['total'];
                        $pageTotalPaid += (float)min($s['amount_paid'] ?? 0, $s['total']);
                ?>
                <tr>
                    <td style="padding: 8px 10px;"><strong><a href="<?= APP_URL ?>/sales/<?= $s['id'] ?>" class="text-blue-600 hover:underline"><?= e($s['sale_no']) ?></a></strong></td>
                    <td style="padding: 8px 10px; font-size: 0.8rem;"><?= date('M j, Y H:i', strtotime($s['created_at'])) ?></td>
                    <td style="padding: 8px 10px;"><?= e($s['customer_name'] ?? 'Walk-in Customer') ?></td>
                    <td style="padding: 8px 10px;"><?= e($s['location_name']) ?></td>
                    <td style="padding: 8px 10px;"><?= e($s['user_name'] ?? 'N/A') ?></td>
                    <td style="padding: 8px 10px; font-weight: 600;"><?= money($s['total']) ?></td>
                    <td style="padding: 8px 10px; color: #16a34a;"><?= money($s['amount_paid'] ?? 0) ?></td>
                    <td style="padding: 8px 10px;">
                        <?php 
                        $statusBadge = [
                            'paid' => 'badge-success',
                            'partial' => 'badge-info',
                            'pending' => 'badge-danger',
                            'credit' => 'badge-danger'
                        ];
                        $badge = $statusBadge[$s['payment_status']] ?? 'badge-muted';
                        ?>
                        <span class="badge <?= $badge ?>" style="padding: 3px 6px; font-size: 0.7rem;"><?= ucfirst($s['payment_status']) ?></span>
                    </td>
                    <td style="padding: 8px 10px;">
                        <span class="badge badge-info" style="padding: 3px 6px; font-size: 0.7rem;"><?= ucfirst($s['payment_method'] ?? 'cash') ?></span>
                    </td>
                    <td style="padding: 8px 10px;">
                        <span class="badge <?= $s['status'] == 'completed' ? 'badge-primary' : 'badge-muted' ?>" style="padding: 3px 6px; font-size: 0.7rem;"><?= ucfirst($s['status']) ?></span>
                    </td>
                    <td class="text-right">
                        <div style="position: relative; display: inline-block;">
                            <button class="btn btn-ghost btn-icon" onclick="document.getElementById('action-dropdown-<?= $s['id'] ?>').classList.toggle('show')" title="Actions">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="1"></circle><circle cx="19" cy="12" r="1"></circle><circle cx="5" cy="12" r="1"></circle></svg>
                            </button>
                            <div id="action-dropdown-<?= $s['id'] ?>" style="position: absolute; right: 0; top: 100%; margin-top: 5px; background: white; border: 1px solid #ddd; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); min-width: 150px; z-index: 100; display: none;">
                                <a href="<?= APP_URL ?>/sales/<?= $s['id'] ?>" class="dropdown-item" style="display: block; padding: 8px 12px; text-decoration: none; color: #333; border-bottom: 1px solid #eee;">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 14px; margin-right: 8px; vertical-align: text-bottom;"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
                                    View
                                </a>
                                <a href="<?= APP_URL ?>/sales/<?= $s['id'] ?>/edit" class="dropdown-item" style="display: block; padding: 8px 12px; text-decoration: none; color: #333; border-bottom: 1px solid #eee;">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 14px; margin-right: 8px; vertical-align: text-bottom;"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg>
                                    Edit
                                </a>
                                <?php if (($s['total'] - $s['amount_paid']) > 0): ?>
                                <a href="<?= APP_URL ?>/sales/<?= $s['id'] ?>/pay" class="dropdown-item" style="display: block; padding: 8px 12px; text-decoration: none; color: #333; border-bottom: 1px solid #eee;">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 14px; margin-right: 8px; vertical-align: text-bottom;"><rect x="2" y="5" width="20" height="14" rx="2"></rect><line x1="2" y1="10" x2="22" y2="10"></line></svg>
                                    Pay Due
                                </a>
                                <?php endif; ?>
                                <a href="<?= APP_URL ?>/sales/<?= $s['id'] ?>/delete" class="dropdown-item" style="display: block; padding: 8px 12px; text-decoration: none; color: #dc3545;" onclick="return confirm('Are you sure you want to delete this sale?');">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 14px; margin-right: 8px; vertical-align: text-bottom;"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>
                                    Delete
                                </a>
                            </div>
                        </div>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="11" style="padding: 0;">
                        <div style="display: flex; justify-content: center; gap: 24px; padding: 12px 10px; background-color: #f8f8f8; border-top: 1px solid #eee; font-size: 1rem;">
                            <div style="color: #666; font-size: 0.9rem; font-weight: 500; display: flex; align-items: center;">Page Totals:</div>
                            <div style="display: flex; align-items: center; gap: 6px;">
                                <svg viewBox="0 0 24 24" fill="none" stroke="#28a745" stroke-width="2" style="width: 18px; height: 18px;"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path></svg>
                                <span style="font-weight: 700; color: #28a745;"><?= money($pageTotalAmount) ?></span>
                            </div>
                            <div style="display: flex; align-items: center; gap: 6px;">
                                <svg viewBox="0 0 24 24" fill="none" stroke="#16a34a" stroke-width="2" style="width: 18px; height: 18px;"><path d="M20 12V8H6a2 2 0 0 1-2-2c0-1.1.9-2 2-2h12v4"></path><path d="M4 6v12c0 1.1.9 2 2 2h14v-4"></path><path d="M18 12a2 2 0 0 0-2 2c0 1.1.9 2 2 2h4v-4h-4z"></path></svg>
                                <span style="font-weight: 700; color: #16a34a;"><?= money($pageTotalPaid) ?></span>
                            </div>
                            <div style="display: flex; align-items: center; gap: 6px;">
                                <svg viewBox="0 0 24 24" fill="none" stroke="#dc3545" stroke-width="2" style="width: 18px; height: 18px;"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>
                                <span style="font-weight: 700; color: #dc3545;"><?= money(max(0, $pageTotalAmount - $pageTotalPaid)) ?></span>
                            </div>
                        </div>
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>

    <?= paginationLinks($sales, APP_URL . '/sales', $_GET) ?>
</div>

<div class="print-footer" style="display: none; margin-top: 20px; padding: 15px; background: #f9f9f9; border: 1px solid #ddd; border-top: 2px solid #333;">
    <h3 style="margin: 0 0 10px 0; font-size: 14px; font-weight: bold;">Summary Totals</h3>
    <div style="display: flex; justify-content: space-between; gap: 30px; margin-bottom: 5px;">
        <span>Total Sales:</span>
        <span style="font-weight: bold;"><?= money($sales['totals']['total_amount']) ?></span>
    </div>
    <div style="display: flex; justify-content: space-between; gap: 30px; margin-bottom: 5px;">
        <span>Total Paid:</span>
        <span style="font-weight: bold;"><?= money($sales['totals']['total_paid']) ?></span>
    </div>
    <div style="display: flex; justify-content: space-between; gap: 30px; margin-bottom: 15px;">
        <span>Outstanding:</span>
        <span style="font-weight: bold;"><?= money(max(0, $sales['totals']['outstanding'])) ?></span>
    </div>
    
    <?php if (!empty($sales['totals']['by_method'])): ?>
    <h3 style="margin: 0 0 10px 0; font-size: 14px; font-weight: bold; border-top: 1px solid #ccc; padding-top: 10px;">Payment Breakdown</h3>
    <?php foreach ($sales['totals']['by_method'] as $method => $amount): ?>
    <div style="display: flex; justify-content: space-between; gap: 30px; margin-bottom: 5px;">
        <span style="text-transform: capitalize;"><?= e($method) ?>:</span>
        <span style="font-weight: bold; color: #333;"><?= money($amount) ?></span>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
</div>

<script>
// Close dropdown when clicking outside
document.addEventListener('click', function(event) {
    const dropdowns = document.querySelectorAll('[id^="action-dropdown-"]');
    dropdowns.forEach(function(dropdown) {
        if (!dropdown.contains(event.target) && !event.target.closest('button[onclick*="action-dropdown-"]')) {
            dropdown.classList.remove('show');
        }
    });
});
</script>
