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

billing_require_auth();

$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');
}

$customers = billing_get_customers((int) $user['id']);
$sort = strtolower(trim((string) ($_GET['sort'] ?? 'name')));
$allowedSorts = ['name', 'email', 'receivable'];
if (!in_array($sort, $allowedSorts, true)) {
    $sort = 'name';
}

usort($customers, static function (array $left, array $right) use ($sort): int {
    if ($sort === 'email') {
        return strcasecmp((string) ($left['email'] ?? ''), (string) ($right['email'] ?? ''));
    }

    if ($sort === 'receivable') {
        return ((float) ($right['outstanding_amount'] ?? 0)) <=> ((float) ($left['outstanding_amount'] ?? 0));
    }

    return strcasecmp((string) ($left['customer_name'] ?? ''), (string) ($right['customer_name'] ?? ''));
});

if ((string) ($_GET['export'] ?? '') === 'csv') {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="customers-' . date('Ymd-His') . '.csv"');

    echo "\"Name\",\"Company Name\",\"Email\",\"Work Phone\",\"Receivables (BCY)\",\"Unused Credits (BCY)\"\r\n";
    foreach ($customers as $customer) {
        $row = [
            (string) ($customer['customer_name'] ?? ''),
            '',
            (string) ($customer['email'] ?? ''),
            '',
            number_format((float) ($customer['outstanding_amount'] ?? 0), 2),
            number_format(0, 2),
        ];

        $escaped = array_map(static function (string $value): string {
            return '"' . str_replace('"', '""', $value) . '"';
        }, $row);

        echo implode(',', $escaped) . "\r\n";
    }
    exit;
}

$buildCustomersUrl = static function (array $params = []): string {
    $query = array_merge($_GET, $params);
    foreach ($query as $key => $value) {
        if ($value === null || $value === '') {
            unset($query[$key]);
        }
    }

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

$billingActiveNav = 'customers';
$billingTopbarOrganizationName = (string) ($organization['organization_name'] ?? 'Billing');
$billingTopbarUserLabel = (string) ($user['email'] ?? '');
?>
<!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>Customers</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;700;800&display=swap">
<link rel="stylesheet" href="Payslip_Project/assets/fontawesome/css/all.min.css">
<link rel="stylesheet" href="assets/billing.css?v=20260507-css-recovery-2">
</head>
<body class="billing-dashboard-page">
<div class="dashboard-shell">
    <?php include dirname(__DIR__) . '/includes/app_sidebar.php'; ?>
    <div class="dashboard-main">
        <?php include dirname(__DIR__) . '/includes/topbar.php'; ?>
        <main class="dashboard-content billing-customers-page">
            <section class="billing-customers-shell">
                <div class="billing-customers-head">
                    <h1>All Customers <i class="fa-solid fa-angle-down"></i></h1>
                    <div class="billing-customers-actions">
                        <a class="billing-customers-btn billing-customers-btn--green" href="customer_new.php"><i class="fa-solid fa-plus"></i> New</a>
                        <div class="customer-menu-wrap customer-menu-wrap--table">
                            <button class="billing-customers-icon-btn" type="button" aria-label="More actions" data-menu-toggle="customerMoreMenu">
                                <i class="fa-solid fa-ellipsis"></i>
                            </button>
                            <div class="customer-pop-menu customer-pop-menu--table" id="customerMoreMenu" hidden>
                                <button class="menu-item" type="button" data-menu-child="customerSortMenu">
                                    <i class="fa-solid fa-arrow-down-wide-short"></i><span>Sort by</span><i class="fa-solid fa-angle-right"></i>
                                </button>
                                <a class="menu-item" href="customer_import.php">
                                    <i class="fa-solid fa-file-import"></i><span>Import</span><i class="fa-solid fa-angle-right"></i>
                                </a>
                                <a class="menu-item" href="<?php echo billing_escape($buildCustomersUrl(['export' => 'csv'])); ?>">
                                    <i class="fa-solid fa-file-export"></i><span>Export</span><i class="fa-solid fa-angle-right"></i>
                                </a>
                                <a class="menu-item" href="settings.php">
                                    <i class="fa-solid fa-sliders"></i><span>Preferences</span>
                                </a>
                                <button class="menu-item" type="button" data-customer-refresh>
                                    <i class="fa-solid fa-rotate-right"></i><span>Refresh List</span>
                                </button>
                                <a class="menu-item" href="<?php echo billing_escape($buildCustomersUrl(['sort' => null, 'export' => null])); ?>">
                                    <i class="fa-solid fa-arrows-left-right-to-line"></i><span>Reset Column Width</span>
                                </a>
                            </div>
                            <div class="customer-pop-submenu" id="customerSortMenu" hidden>
                                <a class="menu-item" href="<?php echo billing_escape($buildCustomersUrl(['sort' => 'name', 'export' => null])); ?>">
                                    <span>Customer Name</span>
                                </a>
                                <a class="menu-item" href="<?php echo billing_escape($buildCustomersUrl(['sort' => 'email', 'export' => null])); ?>">
                                    <span>Email</span>
                                </a>
                                <a class="menu-item" href="<?php echo billing_escape($buildCustomersUrl(['sort' => 'receivable', 'export' => null])); ?>">
                                    <span>Receivables</span>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>

                <section class="billing-customers-table-card">
                    <table class="billing-customers-table">
                        <thead>
                            <tr>
                                <th class="is-icon"><i class="fa-solid fa-sliders"></i></th>
                                <th class="is-check"><input type="checkbox" aria-label="Select all customers"></th>
                                <th>NAME</th>
                                <th>COMPANY NAME</th>
                                <th>EMAIL</th>
                                <th>WORK PHONE</th>
                                <th class="is-amount">RECEIVABLES (BCY)</th>
                                <th class="is-amount">UNUSED CREDITS (BCY)</th>
                                <th class="is-icon"><i class="fa-solid fa-magnifying-glass"></i></th>
                            </tr>
                        </thead>
                        <tbody data-customer-list>
                            <?php if ($customers === []): ?>
                                <tr>
                                    <td class="billing-customers-empty" colspan="9">No customers available.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($customers as $customer): ?>
                                    <?php
                                    $name = (string) ($customer['customer_name'] ?? '');
                                    $email = (string) ($customer['email'] ?? '');
                                    $receivable = (float) ($customer['outstanding_amount'] ?? 0);
                                    ?>
                                    <tr
                                        data-customer-row
                                        data-customer-name="<?php echo billing_escape(strtolower($name)); ?>"
                                        data-customer-email="<?php echo billing_escape(strtolower($email)); ?>"
                                        data-customer-receivable="<?php echo billing_escape((string) $receivable); ?>"
                                    >
                                        <td></td>
                                        <td class="is-check"><input type="checkbox" aria-label="Select <?php echo billing_escape($name); ?>"></td>
                                        <td><a class="billing-customers-name" href="customer_new.php?id=<?php echo (int) ($customer['id'] ?? 0); ?>"><?php echo billing_escape($name); ?></a></td>
                                        <td class="is-muted">-</td>
                                        <td><?php echo billing_escape($email !== '' ? $email : '-'); ?></td>
                                        <td class="is-muted">-</td>
                                        <td class="is-amount"><?php echo billing_escape('₹' . number_format($receivable, 2)); ?></td>
                                        <td class="is-amount"><?php echo billing_escape('₹' . number_format(0, 2)); ?></td>
                                        <td></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </section>
            </section>
        </main>
    </div>
</div>
<script src="assets/billing.js"></script>
</body>
</html>

