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

$billingActiveNav = 'events';
$billingTopbarOrganizationName = (string) ($organization['organization_name'] ?? 'Billing');
$billingTopbarUserLabel = (string) ($user['email'] ?? '');

$organizationId = (int) ($organization['id'] ?? 0);
$eventRows = billing_fetch_all(
    "SELECT occurred_at, event_id, event_type, event_source FROM (
        SELECT created_at AS occurred_at, CONCAT('CUS-', LPAD(id, 5, '0')) AS event_id, 'Customer Added' AS event_type, 'User' AS event_source, id AS sort_id
        FROM customers
        WHERE user_id = ? AND COALESCE(is_deleted, 0) = 0

        UNION ALL

        SELECT COALESCE(updated_at, created_at) AS occurred_at, CONCAT('INV-', LPAD(id, 5, '0')) AS event_id,
            CASE
                WHEN status_label = 'Paid' THEN 'Invoice Payment Recorded'
                WHEN status_label = 'Overdue' THEN 'Invoice Notification'
                ELSE 'Invoice Notification'
            END AS event_type,
            'User' AS event_source,
            id AS sort_id
        FROM invoices
        WHERE user_id = ? AND organization_id = ? AND COALESCE(is_deleted, 0) = 0

        UNION ALL

        SELECT created_at AS occurred_at, CONCAT('SUB-', LPAD(id, 5, '0')) AS event_id,
            CASE
                WHEN status_label IN ('Live', 'Active') THEN 'Subscription Activation'
                ELSE 'Subscription Update'
            END AS event_type,
            'User' AS event_source,
            id AS sort_id
        FROM subscriptions
        WHERE user_id = ? AND organization_id = ? AND COALESCE(is_deleted, 0) = 0

        UNION ALL

        SELECT created_at AS occurred_at, CONCAT('COU-', LPAD(id, 5, '0')) AS event_id, 'Coupon Added' AS event_type, 'User' AS event_source, id AS sort_id
        FROM coupons
        WHERE user_id = ? AND organization_id = ? AND COALESCE(is_deleted, 0) = 0

        UNION ALL

        SELECT created_at AS occurred_at, CONCAT('EXP-', LPAD(id, 5, '0')) AS event_id, 'Expense Added' AS event_type, 'User' AS event_source, id AS sort_id
        FROM expenses
        WHERE user_id = ? AND organization_id = ? AND COALESCE(is_deleted, 0) = 0

        UNION ALL

        SELECT created_at AS occurred_at, CONCAT('PRO-', LPAD(id, 5, '0')) AS event_id, 'Project Added' AS event_type, 'User' AS event_source, id AS sort_id
        FROM projects
        WHERE user_id = ? AND organization_id = ? AND COALESCE(is_deleted, 0) = 0
    ) activity
    ORDER BY occurred_at DESC, sort_id DESC
    LIMIT 25",
    'iiiiiiiiiii',
    [
        (int) $user['id'],
        (int) $user['id'],
        $organizationId,
        (int) $user['id'],
        $organizationId,
        (int) $user['id'],
        $organizationId,
        (int) $user['id'],
        $organizationId,
        (int) $user['id'],
        $organizationId,
    ]
);

$formatEventDate = static function (?string $value): string {
    if (!$value) {
        return '-';
    }

    try {
        return (new DateTimeImmutable($value))->format('d/m/Y h:i A');
    } catch (Throwable $exception) {
        return '-';
    }
};
?>
<!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>Events</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-events-page">
<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="dashboard-content billing-app-page">
            <div class="billing-maintenance-strip">
                <span>Planned India Data Center Maintenance on 10th May 2026 and 17th May 2026, between 06.30AM to 09.30AM IST.</span>
                <a href="reports.php">Know more</a>
            </div>

            <section class="app-screen">
                <div class="app-page-heading">
                    <div class="app-title-row">
                        <h1>All Events</h1>
                        <button class="app-title-caret" type="button" aria-label="Open event filters">
                            <i class="fa-solid fa-angle-down"></i>
                        </button>
                    </div>
                </div>

                <div class="app-data-card">
                    <div class="app-table-tools">
                        <button class="app-table-search" type="button" aria-label="Search events">
                            <i class="fa-solid fa-magnifying-glass"></i>
                        </button>
                    </div>
                    <div class="app-table-wrap">
                        <table class="app-table">
                            <thead>
                                <tr>
                                    <th>OCCURRED AT</th>
                                    <th>EVENT ID</th>
                                    <th>EVENT TYPE</th>
                                    <th>EVENT SOURCE</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($eventRows === []): ?>
                                    <tr><td class="app-table-empty" colspan="4">No events available.</td></tr>
                                <?php else: ?>
                                    <?php foreach ($eventRows as $event): ?>
                                        <tr>
                                            <td><?php echo billing_escape($formatEventDate($event['occurred_at'] ?? null)); ?></td>
                                            <td><?php echo billing_escape((string) ($event['event_id'] ?? '')); ?></td>
                                            <td><?php echo billing_escape((string) ($event['event_type'] ?? '')); ?></td>
                                            <td><?php echo billing_escape((string) ($event['event_source'] ?? '')); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>
        </main>
    </div>
</div>
<script src="assets/billing.js?v=20260507-layout-fix-2"></script>
</body>
</html>
