<?php
session_start();
require_once dirname(__DIR__) . '/includes/functions.php';
require_once dirname(__DIR__) . '/includes/sales_modules.php';

billing_require_auth();
billing_ensure_sales_module_support();

$user = billing_current_user();
$organization = billing_current_organization();
if (!$user) {
    billing_redirect('signin.php');
}
if (!$organization || empty($organization['onboarding_completed_at'])) {
    billing_redirect('onboarding.php?step=1');
}

$moduleKey = isset($salesModule) ? (string) $salesModule : 'quotes';
$module = billing_sales_module($moduleKey);
if (!$module) {
    billing_redirect('dashboard.php?tab=dashboard');
}

$stats = billing_dashboard_stats((int) $user['id']);
$organizationName = (string) ($organization['organization_name'] ?? 'bala');
$userLabel = (string) ($user['email'] ?? 'billing-user');
$billingTopbarOrganizationName = $organizationName;
$billingTopbarUserLabel = $userLabel;
$billingActiveNav = (string) $module['nav'];

$listFn = (string) $module['list_fn'];
$records = $listFn((int) $user['id'], (int) $organization['id']);
$flashSuccess = billing_flash('success');

function billing_sales_document_url(string $path, array $changes = []): string
{
    $query = $_GET;
    foreach ($changes as $key => $value) {
        if ($value === null || $value === '') {
            unset($query[$key]);
        } else {
            $query[$key] = $value;
        }
    }

    return $path . ($query !== [] ? '?' . http_build_query($query) : '');
}

function billing_sales_money_value(float $amount): string
{
    return "\u{20B9}" . number_format($amount, 2);
}

function billing_sales_format_date(?string $date): string
{
    $date = (string) $date;
    if ($date === '') {
        return '-';
    }

    $time = strtotime($date);
    return $time ? date('d/m/Y', $time) : $date;
}

function billing_sales_filter_title(string $moduleKey): string
{
    $filter = strtolower((string) ($_GET['filter_by'] ?? ''));

    return match ($moduleKey) {
        'invoices' => $filter === 'status.unpaid' || $filter === 'unpaid' ? 'Unpaid' : 'All Invoices',
        'subscriptions' => 'All Subscriptions',
        'delivery_challans' => 'All Delivery Challans',
        'credit_notes' => 'All Credit Notes',
        default => (string) billing_sales_module($moduleKey)['list_title'],
    };
}

function billing_sales_status_class(string $status): string
{
    $status = strtolower(trim($status));
    return match ($status) {
        'live', 'active', 'paid' => 'is-green',
        'open', 'due today', 'sent' => 'is-blue',
        'draft', 'inactive' => 'is-muted',
        default => 'is-default',
    };
}

function billing_sales_list_headers(string $moduleKey): array
{
    return match ($moduleKey) {
        'invoices' => ['DATE', 'INVOICE#', 'CUSTOMER NAME', 'EMAIL', 'STATUS', 'DUE DATE', 'AMOUNT', 'BALANCE'],
        'subscriptions' => ['CREATED ON', 'ACTIVATED ON', 'SUBSCRIPTION#', 'CUSTOMER NAME', 'PLAN NAME', 'STATUS', 'AMOUNT', 'LAST BILLED ON'],
        'delivery_challans' => ['DATE', 'DELIVERY CHALLAN#', 'REFERENCE NUMBER', 'CUSTOMER NAME', 'STATUS', 'INVOICE STATUS', 'AMOUNT', ''],
        'credit_notes' => ['DATE', 'CREDIT NOTE#', 'REFERENCE NUMBER', 'CUSTOMER NAME', 'INVOICE#', 'STATUS', 'AMOUNT', 'BALANCE'],
        default => ['DATE', 'NUMBER', 'CUSTOMER NAME', 'STATUS', 'AMOUNT'],
    };
}

function billing_sales_invoice_due_label(array $record): string
{
    $status = strtolower((string) ($record['status_label'] ?? ''));
    $invoiceDate = (string) ($record['invoice_date'] ?? '');
    $dueDate = (string) ($record['due_date'] ?? '');
    if ($status === 'sent' && $invoiceDate !== '' && $dueDate !== '' && billing_sales_format_date($invoiceDate) === billing_sales_format_date($dueDate)) {
        return 'DUE TODAY';
    }
    if ($status === 'unpaid' && $invoiceDate !== '' && $dueDate !== '' && billing_sales_format_date($invoiceDate) === billing_sales_format_date($dueDate)) {
        return 'DUE TODAY';
    }
    return strtoupper((string) ($record['status_label'] ?? 'DRAFT'));
}

function billing_sales_row_cells(string $moduleKey, array $record): array
{
    return match ($moduleKey) {
        'quotes' => [
            ['type' => 'text', 'value' => billing_sales_format_date((string) ($record['quote_date'] ?? ''))],
            ['type' => 'link', 'value' => (string) ($record['quote_number'] ?? ''), 'suffix_icon' => 'fa-regular fa-envelope'],
            ['type' => 'stack', 'primary' => (string) ($record['customer_name'] ?? ''), 'secondary' => (string) ($record['reference_number'] ?? '')],
            ['type' => 'status', 'value' => strtoupper((string) ($record['status_label'] ?? 'DRAFT')), 'class' => billing_sales_status_class((string) ($record['status_label'] ?? 'Draft'))],
            ['type' => 'amount', 'value' => billing_sales_money_value((float) ($record['total_amount'] ?? 0))],
        ],
        'invoices' => [
            ['type' => 'text', 'value' => billing_sales_format_date((string) ($record['invoice_date'] ?? ''))],
            ['type' => 'link', 'value' => (string) ($record['invoice_number'] ?? ''), 'suffix_icon' => 'fa-regular fa-envelope'],
            ['type' => 'stack', 'primary' => (string) ($record['customer_name'] ?? ''), 'secondary' => ''],
            ['type' => 'text', 'value' => (string) ($record['customer_email'] ?? '')],
            ['type' => 'status', 'value' => billing_sales_invoice_due_label($record), 'class' => 'is-blue'],
            ['type' => 'text', 'value' => billing_sales_format_date((string) ($record['due_date'] ?? ''))],
            ['type' => 'amount', 'value' => billing_sales_money_value((float) ($record['total_amount'] ?? 0))],
            ['type' => 'amount', 'value' => billing_sales_money_value((float) ($record['balance_amount'] ?? 0))],
        ],
        'subscriptions' => [
            ['type' => 'text', 'value' => billing_sales_format_date((string) ($record['created_at'] ?? ''))],
            ['type' => 'text', 'value' => billing_sales_format_date((string) ($record['start_date'] ?? ''))],
            ['type' => 'link', 'value' => (string) ($record['subscription_number'] ?? '')],
            ['type' => 'stack', 'primary' => (string) ($record['customer_name'] ?? ''), 'secondary' => (string) ($record['customer_email'] ?? '')],
            ['type' => 'text', 'value' => (string) ($record['plan_name'] ?? '')],
            ['type' => 'status', 'value' => strtoupper((string) ($record['status_label'] ?? '')), 'class' => 'is-green'],
            ['type' => 'amount', 'value' => billing_sales_money_value((float) ($record['amount'] ?? $record['total_amount'] ?? 0))],
            ['type' => 'text', 'value' => billing_sales_format_date((string) ($record['current_cycle_start'] ?? $record['start_date'] ?? ''))],
        ],
        'delivery_challans' => [
            ['type' => 'text', 'value' => billing_sales_format_date((string) ($record['challan_date'] ?? ''))],
            ['type' => 'link', 'value' => (string) ($record['delivery_challan_number'] ?? '')],
            ['type' => 'text', 'value' => (string) ($record['reference_number'] ?? '')],
            ['type' => 'text', 'value' => (string) ($record['customer_name'] ?? '')],
            ['type' => 'status', 'value' => strtoupper((string) ($record['status_label'] ?? 'DRAFT')), 'class' => 'is-muted'],
            ['type' => 'text', 'value' => ''],
            ['type' => 'amount', 'value' => billing_sales_money_value((float) ($record['total_amount'] ?? 0))],
            ['type' => 'icon', 'icon' => 'fa-solid fa-magnifying-glass'],
        ],
        'credit_notes' => [
            ['type' => 'text', 'value' => billing_sales_format_date((string) ($record['credit_note_date'] ?? ''))],
            ['type' => 'link', 'value' => (string) ($record['credit_note_number'] ?? '')],
            ['type' => 'text', 'value' => (string) ($record['reference_number'] ?? '')],
            ['type' => 'text', 'value' => (string) ($record['customer_name'] ?? '')],
            ['type' => 'text', 'value' => (string) ($record['invoice_number'] ?? '')],
            ['type' => 'status', 'value' => strtoupper((string) ($record['status_label'] ?? 'OPEN')), 'class' => 'is-blue'],
            ['type' => 'amount', 'value' => billing_sales_money_value((float) ($record['total_amount'] ?? 0))],
            ['type' => 'amount', 'value' => billing_sales_money_value((float) ($record['credits_remaining'] ?? $record['total_amount'] ?? 0))],
        ],
        default => [],
    };
}

$pageTitle = billing_sales_filter_title($moduleKey);
$headers = billing_sales_list_headers($moduleKey);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="<?php echo billing_escape(billing_base_href()); ?>">
<title><?php echo billing_escape((string) $module['list_title']); ?> | Zoho Billing</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&display=swap">
<link rel="stylesheet" href="Payslip_Project/assets/fontawesome/css/all.min.css">
<link rel="stylesheet" href="assets/billing.css?v=20260504-sales-list-2">
<style>
.sales-list-card {
    background: #fff;
    border: 1px solid #dce5ef;
    border-radius: 22px;
    box-shadow: 0 12px 28px rgba(15, 23, 42, 0.05);
    overflow: hidden;
}

.sales-list-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 18px;
    padding: 28px 30px 20px;
}

.sales-list-title {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    color: #10203c;
    font-size: 18px;
    font-weight: 800;
    text-decoration: none;
}

.sales-list-actions,
.sales-list-new-split {
    display: flex;
    align-items: center;
}

.sales-list-actions {
    gap: 12px;
}

.sales-list-new-split {
    border-radius: 8px;
    overflow: hidden;
}

.sales-list-new-btn,
.sales-list-caret-btn,
.sales-list-icon-btn {
    min-height: 40px;
    border: 1px solid #27bc72;
    background: #27bc72;
    color: #fff;
    font: inherit;
    cursor: pointer;
}

.sales-list-new-btn {
    padding: 0 20px;
}

.sales-list-caret-btn {
    min-width: 38px;
    border-left-color: rgba(255, 255, 255, 0.25);
}

.sales-list-icon-btn {
    min-width: 40px;
    border-color: #d6dfeb;
    background: #fff;
    color: #334155;
    border-radius: 8px;
}

.sales-list-table-wrap {
    overflow-x: auto;
}

.sales-list-table {
    width: 100%;
    min-width: 1180px;
    border-collapse: collapse;
}

.sales-list-table thead th {
    padding: 12px 18px;
    border-top: 1px solid #e8edf5;
    border-bottom: 1px solid #e8edf5;
    color: #667085;
    font-size: 12px;
    font-weight: 800;
    text-align: left;
    white-space: nowrap;
    background: #fbfcff;
}

.sales-list-table tbody td {
    padding: 16px 18px;
    border-bottom: 1px solid #edf2f7;
    vertical-align: top;
    color: #0f172a;
}

.sales-list-table tbody tr:hover td {
    background: #fbfdff;
}

.sales-list-table th:first-child,
.sales-list-table td:first-child {
    width: 54px;
}

.sales-list-filter {
    color: #3b82f6;
    font-size: 18px;
}

.sales-list-checkbox {
    width: 19px;
    height: 19px;
}

.sales-list-link {
    color: #2563eb;
    text-decoration: none;
}

.sales-list-link-inline {
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.sales-list-stack {
    display: grid;
    gap: 4px;
}

.sales-list-stack-sub {
    color: #667085;
}

.sales-list-amount {
    text-align: right;
    white-space: nowrap;
}

.sales-list-status {
    white-space: nowrap;
    font-weight: 500;
}

.sales-list-status.is-green {
    color: #10b981;
}

.sales-list-status.is-blue {
    color: #2563eb;
}

.sales-list-status.is-muted {
    color: #8a94a6;
}

.sales-list-status.is-default {
    color: #475569;
}

.sales-list-end-icon {
    color: #667085;
}

.sales-list-empty {
    min-height: 360px;
    display: grid;
    place-items: center;
    color: #64748b;
}
</style>
</head>
<body>
<div class="dashboard-shell customer-shell">
    <?php include dirname(__DIR__) . '/includes/app_sidebar.php'; ?>
    <div class="dashboard-main customer-main">
        <?php include dirname(__DIR__) . '/includes/topbar.php'; ?>
        <main class="catalog-page">
            <?php if ($flashSuccess): ?><div class="customer-flash"><?php echo billing_escape($flashSuccess); ?></div><?php endif; ?>
            <section class="sales-list-card">
                <div class="sales-list-head">
                    <a class="sales-list-title" href="<?php echo billing_escape((string) $module['list_path']); ?>">
                        <?php echo billing_escape($pageTitle); ?>
                        <i class="fa-solid fa-angle-down"></i>
                    </a>

                    <div class="sales-list-actions">
                        <?php if ($moduleKey === 'invoices'): ?>
                            <div class="sales-list-new-split">
                                <button class="sales-list-new-btn" type="button" onclick="window.location.href='<?php echo billing_escape((string) $module['new_path']); ?>';"><i class="fa-solid fa-plus"></i> New</button>
                                <button class="sales-list-caret-btn" type="button" aria-label="More new options"><i class="fa-solid fa-angle-down"></i></button>
                            </div>
                        <?php else: ?>
                            <button class="sales-list-new-btn" type="button" onclick="window.location.href='<?php echo billing_escape((string) $module['new_path']); ?>';"><i class="fa-solid fa-plus"></i> New</button>
                        <?php endif; ?>
                        <button class="sales-list-icon-btn" type="button" aria-label="More actions"><i class="fa-solid fa-ellipsis"></i></button>
                    </div>
                </div>

                <?php if ($records === []): ?>
                    <div class="sales-list-empty">No records found.</div>
                <?php else: ?>
                    <div class="sales-list-table-wrap">
                        <table class="sales-list-table">
                            <thead>
                                <tr>
                                    <th>
                                        <span class="sales-list-filter"><i class="fa-solid fa-sliders"></i></span>
                                        <input class="sales-list-checkbox" type="checkbox" aria-label="Select all">
                                    </th>
                                    <?php foreach ($headers as $index => $header): ?>
                                        <th>
                                            <?php echo billing_escape($header); ?>
                                            <?php if ($moduleKey === 'credit_notes' && $index === 1): ?>
                                                <i class="fa-solid fa-arrow-up-long" style="font-size:10px;color:#2563eb;"></i>
                                            <?php endif; ?>
                                        </th>
                                    <?php endforeach; ?>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($records as $record): ?>
                                    <?php $cells = billing_sales_row_cells($moduleKey, $record); ?>
                                    <tr>
                                        <td><input class="sales-list-checkbox" type="checkbox" aria-label="Select row"></td>
                                        <?php foreach ($cells as $cell): ?>
                                            <td class="<?php echo in_array($cell['type'], ['amount'], true) ? 'sales-list-amount' : ''; ?>">
                                                <?php if ($cell['type'] === 'link'): ?>
                                                    <a class="sales-list-link sales-list-link-inline" href="<?php echo billing_escape(billing_sales_document_url((string) $module['new_path'], ['id' => (int) $record['id']])); ?>">
                                                        <span><?php echo billing_escape((string) $cell['value']); ?></span>
                                                        <?php if (!empty($cell['suffix_icon'])): ?><i class="<?php echo billing_escape((string) $cell['suffix_icon']); ?>" style="color:#667085;"></i><?php endif; ?>
                                                    </a>
                                                <?php elseif ($cell['type'] === 'stack'): ?>
                                                    <div class="sales-list-stack">
                                                        <a class="sales-list-link" href="<?php echo billing_escape(billing_sales_document_url((string) $module['new_path'], ['id' => (int) $record['id']])); ?>"><?php echo billing_escape((string) $cell['primary']); ?></a>
                                                        <?php if (($cell['secondary'] ?? '') !== ''): ?><span class="sales-list-stack-sub"><?php echo billing_escape((string) $cell['secondary']); ?></span><?php endif; ?>
                                                    </div>
                                                <?php elseif ($cell['type'] === 'status'): ?>
                                                    <span class="sales-list-status <?php echo billing_escape((string) ($cell['class'] ?? 'is-default')); ?>"><?php echo billing_escape((string) $cell['value']); ?></span>
                                                <?php elseif ($cell['type'] === 'icon'): ?>
                                                    <span class="sales-list-end-icon"><i class="<?php echo billing_escape((string) $cell['icon']); ?>"></i></span>
                                                <?php else: ?>
                                                    <?php echo $cell['value'] !== '' ? billing_escape((string) $cell['value']) : '&nbsp;'; ?>
                                                <?php endif; ?>
                                            </td>
                                        <?php endforeach; ?>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </section>
        </main>
    </div>
</div>
<script src="assets/billing.js"></script>
</body>
</html>



