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

billing_require_auth();
billing_ensure_product_catalog_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');
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['coupon_action'], $_POST['coupon_id'])) {
    $couponId = (int) $_POST['coupon_id'];
    $action = billing_clean((string) $_POST['coupon_action']);
    if ($couponId > 0 && in_array($action, ['mark_inactive', 'mark_active'], true)) {
        $status = $action === 'mark_inactive' ? 'Inactive' : 'Active';
        if (billing_set_coupon_status((int) $user['id'], (int) $organization['id'], $couponId, $status)) {
            billing_flash('success', $status === 'Inactive' ? 'Coupon marked as inactive.' : 'Coupon marked as active.');
        }
    }
    $redirect = 'coupons.php?id=' . $couponId;
    if (isset($_GET['filter_by']) && $_GET['filter_by'] !== '') {
        $redirect .= '&filter_by=' . urlencode((string) $_GET['filter_by']);
    }
    if (isset($_GET['sort_column']) && $_GET['sort_column'] !== '') {
        $redirect .= '&sort_column=' . urlencode((string) $_GET['sort_column']);
    }
    if (isset($_GET['sort_order']) && $_GET['sort_order'] !== '') {
        $redirect .= '&sort_order=' . urlencode((string) $_GET['sort_order']);
    }
    billing_redirect($redirect);
}

function billing_coupon_valid_upto_label(?string $date): string
{
    if (!$date) {
        return '-';
    }

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

function billing_coupon_maximum_label($value): string
{
    return $value === null || $value === '' ? 'Unlimited' : (string) (int) $value;
}

function billing_coupon_filter_options(): array
{
    return [
        'all' => 'All Coupons',
        'active' => 'Active Coupons',
        'inactive' => 'Inactive Coupons',
        'expired' => 'Expired Coupons',
    ];
}

function billing_coupon_matches_filter(array $coupon, string $filter): bool
{
    $status = strtolower((string) ($coupon['status_label'] ?? ''));
    $expirationDate = (string) ($coupon['expiration_date'] ?? '');
    $isExpired = $expirationDate !== '' && strtotime($expirationDate) !== false && strtotime($expirationDate) < strtotime(date('Y-m-d'));

    if ($filter === 'active') {
        return $status === 'active';
    }
    if ($filter === 'inactive') {
        return $status === 'inactive';
    }
    if ($filter === 'expired') {
        return $isExpired;
    }

    return true;
}

function billing_coupon_sort_value(array $coupon, string $column)
{
    if ($column === 'coupon_name') {
        return strtolower((string) ($coupon['coupon_name'] ?? ''));
    }
    if ($column === 'discount_value') {
        return (float) ($coupon['discount_value'] ?? 0);
    }
    if ($column === 'status_label') {
        return strtolower((string) ($coupon['status_label'] ?? ''));
    }

    return strtotime((string) ($coupon['created_at'] ?? '')) ?: 0;
}

function billing_coupon_base_query(array $overrides = []): string
{
    $params = array_merge(
        [
            'filter_by' => $_GET['filter_by'] ?? 'all',
            'sort_column' => $_GET['sort_column'] ?? 'created_at',
            'sort_order' => $_GET['sort_order'] ?? 'asc',
        ],
        $overrides
    );

    return http_build_query(array_filter($params, static fn($value): bool => $value !== null && $value !== ''));
}

$filterOptions = billing_coupon_filter_options();
$selectedFilter = strtolower((string) ($_GET['filter_by'] ?? 'all'));
if (!isset($filterOptions[$selectedFilter])) {
    $selectedFilter = 'all';
}

$sortColumn = strtolower((string) ($_GET['sort_column'] ?? 'created_at'));
if (!in_array($sortColumn, ['created_at', 'coupon_name', 'discount_value', 'status_label'], true)) {
    $sortColumn = 'created_at';
}

$sortOrder = strtolower((string) ($_GET['sort_order'] ?? 'asc'));
if (!in_array($sortOrder, ['asc', 'desc'], true)) {
    $sortOrder = 'asc';
}

$coupons = billing_get_coupons((int) $user['id'], (int) $organization['id']);
$coupons = array_values(array_filter(
    $coupons,
    static fn(array $coupon): bool => billing_coupon_matches_filter($coupon, $selectedFilter)
));

usort($coupons, static function (array $left, array $right) use ($sortColumn, $sortOrder): int {
    $leftValue = billing_coupon_sort_value($left, $sortColumn);
    $rightValue = billing_coupon_sort_value($right, $sortColumn);
    if ($leftValue === $rightValue) {
        return 0;
    }
    $comparison = $leftValue <=> $rightValue;
    return $sortOrder === 'asc' ? $comparison : -$comparison;
});

if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="coupons-' . date('Ymd-His') . '.csv"');
    $stream = fopen('php://output', 'w');
    if ($stream !== false) {
        fputcsv($stream, ['Coupon Name', 'Coupon Code', 'Status', 'Discount Value', 'Discount By', 'Redemption Type', 'Maximum Redemption', 'Valid Upto']);
        foreach ($coupons as $coupon) {
            fputcsv($stream, [
                (string) ($coupon['coupon_name'] ?? ''),
                (string) ($coupon['coupon_code'] ?? ''),
                (string) ($coupon['status_label'] ?? ''),
                number_format((float) ($coupon['discount_value'] ?? 0), 2, '.', ''),
                (string) ($coupon['discount_by'] ?? ''),
                (string) ($coupon['redemption_type'] ?? ''),
                billing_coupon_maximum_label($coupon['maximum_redemptions'] ?? null),
                billing_coupon_valid_upto_label($coupon['expiration_date'] ?? null),
            ]);
        }
        fclose($stream);
    }
    exit;
}

$selectedCouponId = (int) ($_GET['id'] ?? 0);
$selectedCoupon = null;
foreach ($coupons as $coupon) {
    if ((int) $coupon['id'] === $selectedCouponId) {
        $selectedCoupon = $coupon;
        break;
    }
}
if (!$selectedCoupon && $selectedCouponId > 0) {
    $selectedCoupon = billing_get_coupon((int) $user['id'], (int) $organization['id'], $selectedCouponId);
    if ($selectedCoupon && !billing_coupon_matches_filter($selectedCoupon, $selectedFilter)) {
        $selectedCoupon = null;
    }
}
if (!$selectedCoupon && $selectedCouponId > 0 && $coupons !== []) {
    $selectedCoupon = $coupons[0];
    $selectedCouponId = (int) ($selectedCoupon['id'] ?? 0);
}

$flashSuccess = billing_flash('success');
$currentViewLabel = $filterOptions[$selectedFilter];
$listOnlyMode = $selectedCouponId <= 0;
$exportQuery = billing_coupon_base_query(['export' => 'csv']);
$toggleSortOrder = $sortOrder === 'asc' ? 'desc' : 'asc';
$selectedCouponUrl = 'coupons.php?' . billing_coupon_base_query(['id' => $selectedCouponId]);
$listUrl = 'coupons.php?' . billing_coupon_base_query(['id' => null]);
?>
<!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>Coupons | 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-coupon-2">
<style>
.catalog-split-card.coupon-split-active {
    grid-template-columns: 440px minmax(0, 1fr);
}

.coupon-view-trigger {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    padding: 10px 14px;
    border-radius: 14px;
    background: #f3f6ff;
    color: #10203c;
    font-size: 18px;
    font-weight: 800;
    text-decoration: none;
}

.coupon-head-actions,
.coupon-toolbar,
.coupon-menu-list a,
.coupon-menu-list button,
.coupon-list-card-top,
.coupon-list-card-meta,
.coupon-summary-top,
.coupon-card-tabs,
.coupon-code-box,
.coupon-detail-shell {
    display: flex;
}

.coupon-head-actions,
.coupon-toolbar,
.coupon-card-tabs {
    align-items: center;
}

.coupon-head-actions,
.coupon-toolbar {
    gap: 12px;
}

.coupon-toolbar {
    position: relative;
}

.coupon-icon-btn {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    border: 1px solid #d9e2ef;
    background: #fff;
    color: #334155;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
    cursor: pointer;
}

.coupon-icon-btn--green {
    border-color: #20c46c;
    background: #20c46c;
    color: #fff;
}

.coupon-icon-btn--danger {
    border: 0;
    background: transparent;
    color: #ef4444;
}

.coupon-dropdown {
    position: relative;
}

.coupon-dropdown-panel {
    position: absolute;
    top: calc(100% + 10px);
    left: 0;
    min-width: 240px;
    padding: 10px 0;
    border: 1px solid #e6edf5;
    border-radius: 18px;
    background: #fff;
    box-shadow: 0 18px 40px rgba(15, 23, 42, 0.12);
    display: none;
    z-index: 30;
}

.coupon-dropdown.is-open .coupon-dropdown-panel {
    display: block;
}

.coupon-view-list a,
.coupon-menu-list a,
.coupon-menu-list button {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    width: 100%;
    padding: 12px 16px;
    background: transparent;
    border: 0;
    color: #334155;
    font: inherit;
    text-decoration: none;
    cursor: pointer;
}

.coupon-view-list a.is-active,
.coupon-menu-list a:hover,
.coupon-menu-list button:hover {
    background: #eef4ff;
    color: #2563eb;
}

.coupon-view-list a i,
.coupon-menu-list a i,
.coupon-menu-list button i {
    width: 16px;
    text-align: center;
}

.coupon-view-footer {
    padding: 12px 16px 4px;
    border-top: 1px solid #edf2f8;
}

.coupon-view-footer a {
    color: #2563eb;
    text-decoration: none;
    font-weight: 700;
}

.coupon-list-table thead th:first-child,
.coupon-list-table tbody td:first-child {
    width: 42px;
}

.coupon-list-table tbody tr[data-href] {
    cursor: pointer;
}

.coupon-list-table tbody tr[data-href]:hover {
    background: #f8fbff;
}

.coupon-list-table .customer-name-link {
    color: #111827;
    font-weight: 500;
    text-decoration: none;
}

.coupon-list-table .customer-name-link:hover {
    color: #2563eb;
}

.coupon-list-stack {
    padding: 0 0 18px;
}

.coupon-list-card {
    display: grid;
    grid-template-columns: 30px minmax(0, 1fr) auto;
    gap: 14px;
    padding: 16px 18px;
    border-top: 1px solid #edf2f8;
    text-decoration: none;
    color: inherit;
}

.coupon-list-card.is-active {
    background: #f4f7ff;
}

.coupon-list-card-top {
    justify-content: space-between;
    gap: 18px;
    margin-bottom: 10px;
}

.coupon-list-card-top strong,
.coupon-list-card-amount strong,
.coupon-summary-meta h2 {
    color: #0f172a;
}

.coupon-list-card-top strong {
    font-size: 16px;
}

.coupon-list-card-top span,
.coupon-list-card-meta,
.coupon-summary-meta p,
.coupon-amount-box span,
.coupon-detail-empty,
.coupon-kv-grid dt {
    color: #64748b;
}

.coupon-list-card-amount {
    text-align: right;
}

.coupon-list-card-amount strong {
    display: block;
    font-size: 18px;
}

.coupon-list-card-meta {
    flex-wrap: wrap;
    gap: 12px 18px;
    font-size: 13px;
}

.coupon-status-pill {
    display: inline-flex;
    align-items: center;
    padding: 5px 10px;
    border-radius: 999px;
    font-size: 11px;
    font-weight: 800;
    letter-spacing: 0.04em;
    text-transform: uppercase;
}

.coupon-status-pill.is-active {
    background: #e8fff0;
    color: #138a3b;
}

.coupon-status-pill.is-inactive,
.coupon-status-pill.is-expired {
    background: #f3f4f6;
    color: #4b5563;
}

.coupon-detail-shell {
    flex-direction: column;
    min-height: 100%;
}

.coupon-detail-toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 14px;
    padding: 0 22px;
    border-top: 1px solid #e7edf5;
    border-bottom: 1px solid #e7edf5;
    min-height: 52px;
}

.coupon-card-panel {
    margin: 22px;
    border: 1px solid #e6edf5;
    border-radius: 20px;
    background: #fff;
}

.coupon-summary-card {
    border-bottom: 1px solid #edf2f8;
    padding: 22px;
    background: linear-gradient(180deg, #ffffff 0%, #fbfdff 100%);
    border-radius: 20px 20px 0 0;
}

.coupon-summary-card .catalog-badge {
    margin-top: 0;
    margin-bottom: 16px;
}

.coupon-summary-top {
    align-items: center;
    justify-content: space-between;
    gap: 22px;
}

.coupon-summary-main {
    display: grid;
    grid-template-columns: 164px minmax(0, 1fr);
    gap: 18px;
    align-items: center;
    min-width: 0;
}

.coupon-amount-box {
    min-height: 76px;
    border: 1px solid #e4eaf3;
    border-radius: 12px;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    text-align: center;
    padding: 10px 14px;
}

.coupon-amount-box strong {
    display: block;
    font-size: 22px;
}

.coupon-summary-meta h2 {
    margin: 0 0 8px;
    font-size: 18px;
}

.coupon-code-box {
    align-items: center;
    gap: 12px;
    padding: 14px 18px;
    border: 1px dashed #6bcf8e;
    border-radius: 16px;
    color: #159947;
    background: #f6fff9;
    font-weight: 700;
}

.coupon-copy-btn {
    border: 0;
    background: transparent;
    color: #3b82f6;
    cursor: pointer;
    font-size: 15px;
}

.coupon-card-tabs {
    gap: 28px;
    padding: 0 22px;
    min-height: 64px;
    border-bottom: 1px solid #edf2f8;
}

.coupon-card-tabs a {
    color: #556579;
    font-weight: 700;
    text-decoration: none;
}

.coupon-card-tabs a.is-active {
    color: #111827;
    border-bottom: 3px solid #4b87ef;
    padding-bottom: 16px;
}

.coupon-kv-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 4px 42px;
    padding: 22px;
}

.coupon-kv-grid dl {
    margin: 0;
}

.coupon-kv-grid div {
    display: grid;
    grid-template-columns: 180px minmax(0, 1fr);
    gap: 18px;
    padding: 12px 0;
    border-bottom: 1px solid #f2f5fa;
}

.coupon-kv-grid dd {
    margin: 0;
    color: #111827;
    font-weight: 700;
}

.coupon-detail-empty {
    padding: 54px 22px;
}

@media (max-width: 1200px) {
    .catalog-split-card.coupon-split-active,
    .coupon-kv-grid,
    .coupon-summary-main {
        grid-template-columns: 1fr;
    }

    .coupon-summary-top {
        flex-direction: column;
        align-items: flex-start;
    }
}
</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; ?>

            <?php if ($coupons === []): ?>
                <section class="customer-views-card">
                    <div class="catalog-list-head">
                        <div class="catalog-view-links">
                            <span class="coupon-view-trigger"><?php echo billing_escape($currentViewLabel); ?> <i class="fa-solid fa-angle-down"></i></span>
                        </div>
                        <div class="coupon-head-actions">
                            <a class="customer-btn customer-btn--green" href="coupon_new.php"><i class="fa-solid fa-plus"></i> New</a>
                        </div>
                    </div>
                    <div class="catalog-empty-state catalog-empty-state--wide">
                        <h2>No coupons found</h2>
                        <p>Create product-specific coupons with validity, redemption limits, and plan or addon applicability.</p>
                    </div>
                </section>
            <?php else: ?>
                <section class="catalog-split-card<?php echo $listOnlyMode ? ' catalog-split-card--list-only' : ' coupon-split-active'; ?>">
                    <div class="catalog-list-pane<?php echo $listOnlyMode ? ' catalog-list-pane--empty' : ''; ?>">
                        <div class="catalog-list-head">
                            <div class="coupon-dropdown" data-dropdown>
                                <a class="coupon-view-trigger" href="#" data-dropdown-trigger>
                                    <?php echo billing_escape($currentViewLabel); ?>
                                    <i class="fa-solid fa-angle-down"></i>
                                </a>
                                <div class="coupon-dropdown-panel">
                                    <div class="coupon-view-list">
                                        <?php foreach ($filterOptions as $filterValue => $filterLabel): ?>
                                            <a class="<?php echo $selectedFilter === $filterValue ? 'is-active' : ''; ?>" href="coupons.php?<?php echo billing_escape(billing_coupon_base_query(['filter_by' => $filterValue, 'id' => null])); ?>">
                                                <span><?php echo billing_escape($filterLabel === 'All Coupons' ? 'All' : str_replace(' Coupons', '', $filterLabel)); ?></span>
                                                <i class="fa-regular fa-star"></i>
                                            </a>
                                        <?php endforeach; ?>
                                    </div>
                                    <div class="coupon-view-footer">
                                        <a href="#" onclick="return false;"><i class="fa-solid fa-circle-plus"></i> New Custom View</a>
                                    </div>
                                </div>
                            </div>

                            <div class="coupon-toolbar">
                                <a class="coupon-icon-btn coupon-icon-btn--green" href="coupon_new.php" aria-label="New coupon"><i class="fa-solid fa-plus"></i></a>

                                <div class="coupon-dropdown" data-dropdown>
                                    <button class="coupon-icon-btn" type="button" data-dropdown-trigger aria-label="More actions">
                                        <i class="fa-solid fa-ellipsis"></i>
                                    </button>
                                    <div class="coupon-dropdown-panel">
                                        <div class="coupon-menu-list">
                                            <a href="coupons.php?<?php echo billing_escape(billing_coupon_base_query(['sort_order' => $toggleSortOrder])); ?>">
                                                <span><i class="fa-solid fa-arrow-down-wide-short"></i> Sort by <?php echo $sortOrder === 'asc' ? 'descending' : 'ascending'; ?></span>
                                                <i class="fa-solid fa-angle-right"></i>
                                            </a>
                                            <button type="button" onclick="window.location.href='coupon_new.php';">
                                                <span><i class="fa-solid fa-file-import"></i> Import Coupons</span>
                                            </button>
                                            <a href="coupons.php?<?php echo billing_escape($exportQuery); ?>">
                                                <span><i class="fa-solid fa-file-export"></i> Export Coupons</span>
                                            </a>
                                            <a href="coupons.php?<?php echo billing_escape(billing_coupon_base_query(['sort_column' => 'created_at', 'sort_order' => 'asc'])); ?>">
                                                <span><i class="fa-solid fa-rotate-left"></i> Reset Column Width</span>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <?php if ($listOnlyMode): ?>
                            <div class="customer-table-wrap">
                                <table class="customer-table-view coupon-list-table">
                                    <thead>
                                        <tr>
                                            <th class="customer-table-filter-col"><i class="fa-solid fa-sliders"></i></th>
                                            <th>NAME</th>
                                            <th>COUPON CODE</th>
                                            <th>STATUS</th>
                                            <th>DISCOUNT VALUE</th>
                                            <th>DISCOUNT BY</th>
                                            <th>REDEMPTION TYPE</th>
                                            <th>MAXIMUM REDEMPTION</th>
                                            <th>VALID UPTO</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($coupons as $coupon): ?>
                                            <tr data-href="coupons.php?<?php echo billing_escape(billing_coupon_base_query(['id' => (int) $coupon['id']])); ?>">
                                                <td><input type="checkbox" aria-label="Select coupon" onclick="event.stopPropagation();"></td>
                                                <td><a class="customer-name-link" href="coupons.php?<?php echo billing_escape(billing_coupon_base_query(['id' => (int) $coupon['id']])); ?>"><?php echo billing_escape((string) $coupon['coupon_name']); ?></a></td>
                                                <td><?php echo billing_escape((string) $coupon['coupon_code']); ?></td>
                                                <td><?php echo billing_escape((string) $coupon['status_label']); ?></td>
                                                <td><?php echo '&#8377;' . billing_escape(number_format((float) $coupon['discount_value'], 2)); ?></td>
                                                <td><?php echo billing_escape((string) $coupon['discount_by']); ?></td>
                                                <td><?php echo billing_escape((string) $coupon['redemption_type']); ?></td>
                                                <td><?php echo billing_escape(billing_coupon_maximum_label($coupon['maximum_redemptions'])); ?></td>
                                                <td><?php echo billing_escape(billing_coupon_valid_upto_label($coupon['expiration_date'] ?? null)); ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="coupon-list-stack">
                                <?php foreach ($coupons as $coupon): ?>
                                    <?php
                                    $statusClass = strtolower((string) ($coupon['status_label'] ?? 'inactive'));
                                    if ($statusClass !== 'active' && $statusClass !== 'inactive') {
                                        $statusClass = 'expired';
                                    }
                                    ?>
                                    <a class="coupon-list-card<?php echo (int) $coupon['id'] === $selectedCouponId ? ' is-active' : ''; ?>" href="coupons.php?<?php echo billing_escape(billing_coupon_base_query(['id' => (int) $coupon['id']])); ?>">
                                        <div><input type="checkbox" aria-label="Select coupon"></div>
                                        <div>
                                            <div class="coupon-list-card-top">
                                                <div>
                                                    <strong><?php echo billing_escape((string) $coupon['coupon_name']); ?></strong><br>
                                                    <span><?php echo billing_escape((string) $coupon['coupon_code']); ?></span>
                                                </div>
                                                <div class="coupon-list-card-amount">
                                                    <strong><?php echo '&#8377;' . billing_escape(number_format((float) $coupon['discount_value'], 2)); ?></strong>
                                                    <span><?php echo billing_escape((string) $coupon['redemption_type']); ?></span>
                                                </div>
                                            </div>
                                            <div class="coupon-list-card-meta">
                                                <span class="coupon-status-pill is-<?php echo billing_escape($statusClass); ?>"><?php echo billing_escape((string) $coupon['status_label']); ?></span>
                                            </div>
                                        </div>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>

                    <?php if (!$listOnlyMode): ?>
                        <div class="catalog-detail-pane">
                            <?php if ($selectedCoupon): ?>
                                <div class="coupon-detail-shell">
                                    <div class="catalog-detail-head">
                                        <div>
                                            <h1><?php echo billing_escape((string) $selectedCoupon['coupon_name']); ?></h1>
                                        </div>
                                        <a class="coupon-icon-btn coupon-icon-btn--danger" href="<?php echo billing_escape($listUrl); ?>" aria-label="Close detail pane">
                                            <i class="fa-solid fa-xmark"></i>
                                        </a>
                                    </div>

                                    <div class="coupon-detail-toolbar">
                                        <div class="catalog-detail-actions">
                                            <a class="customer-btn" href="coupon_new.php?id=<?php echo (int) $selectedCoupon['id']; ?>"><i class="fa-regular fa-pen-to-square"></i> Edit</a>
                                            <form method="post" action="<?php echo billing_escape($selectedCouponUrl); ?>">
                                                <input type="hidden" name="coupon_id" value="<?php echo (int) $selectedCoupon['id']; ?>">
                                                <input type="hidden" name="coupon_action" value="<?php echo $selectedCoupon['status_label'] === 'Active' ? 'mark_inactive' : 'mark_active'; ?>">
                                                <button class="customer-btn" type="submit"><?php echo $selectedCoupon['status_label'] === 'Active' ? 'Mark as Inactive' : 'Mark as Active'; ?></button>
                                            </form>
                                        </div>
                                        <div class="coupon-dropdown" data-dropdown>
                                            <button class="coupon-icon-btn" type="button" data-dropdown-trigger aria-label="More detail actions">
                                                <i class="fa-solid fa-ellipsis"></i>
                                            </button>
                                            <div class="coupon-dropdown-panel">
                                                <div class="coupon-menu-list">
                                                    <a href="coupon_new.php?id=<?php echo (int) $selectedCoupon['id']; ?>">
                                                        <span><i class="fa-regular fa-pen-to-square"></i> Edit Coupon</span>
                                                    </a>
                                                    <a href="coupons.php?<?php echo billing_escape($exportQuery); ?>">
                                                        <span><i class="fa-solid fa-file-export"></i> Export Coupons</span>
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <section class="coupon-card-panel">
                                        <div class="coupon-summary-card">
                                            <span class="catalog-badge" style="background: <?php echo $selectedCoupon['status_label'] === 'Active' ? '#2f9e1f' : '#e5e7eb'; ?>; color: <?php echo $selectedCoupon['status_label'] === 'Active' ? '#ffffff' : '#374151'; ?>;"><?php echo billing_escape((string) $selectedCoupon['status_label']); ?></span>
                                            <div class="coupon-summary-top">
                                                <div class="coupon-summary-main">
                                                    <div class="coupon-amount-box">
                                                        <strong><?php echo '&#8377;' . billing_escape(number_format((float) $selectedCoupon['discount_value'], 2)); ?></strong>
                                                        <span>DISCOUNT</span>
                                                    </div>
                                                    <div class="coupon-summary-meta">
                                                        <h2><?php echo billing_escape((string) $selectedCoupon['coupon_name']); ?></h2>
                                                        <p>Redemption Type: <?php echo billing_escape((string) $selectedCoupon['redemption_type']); ?></p>
                                                    </div>
                                                </div>
                                                <div class="coupon-code-box">
                                                    <span>CODE: <strong><?php echo billing_escape((string) $selectedCoupon['coupon_code']); ?></strong></span>
                                                    <button class="coupon-copy-btn" type="button" data-copy-code="<?php echo billing_escape((string) $selectedCoupon['coupon_code']); ?>" aria-label="Copy code">
                                                        <i class="fa-regular fa-copy"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="coupon-card-tabs">
                                            <a class="is-active" href="#" onclick="return false;">Coupon Details</a>
                                            <a href="#" onclick="return false;">Transactions</a>
                                            <a href="#" onclick="return false;">Activity Logs</a>
                                        </div>

                                        <div class="coupon-kv-grid">
                                            <dl>
                                                <div><dt>Coupon Name</dt><dd><?php echo billing_escape((string) $selectedCoupon['coupon_name']); ?></dd></div>
                                                <div><dt>Redemption Type</dt><dd><?php echo billing_escape((string) $selectedCoupon['redemption_type']); ?></dd></div>
                                                <div><dt>Product Name</dt><dd><?php echo billing_escape((string) $selectedCoupon['product_name']); ?></dd></div>
                                            </dl>
                                            <dl>
                                                <div><dt>Coupon Code</dt><dd><?php echo billing_escape((string) $selectedCoupon['coupon_code']); ?></dd></div>
                                                <div><dt>Maximum Redemptions</dt><dd><?php echo billing_escape(billing_coupon_maximum_label($selectedCoupon['maximum_redemptions'])); ?></dd></div>
                                                <div><dt>Valid Upto</dt><dd><?php echo billing_escape(billing_coupon_valid_upto_label($selectedCoupon['expiration_date'] ?? null)); ?></dd></div>
                                            </dl>
                                        </div>
                                    </section>
                                </div>
                            <?php else: ?>
                                <div class="coupon-detail-empty">Select a coupon to see its details.</div>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </section>
            <?php endif; ?>
        </main>
    </div>
</div>
<script src="assets/billing.js"></script>
<script>
document.querySelectorAll('[data-dropdown]').forEach(function (dropdown) {
    var trigger = dropdown.querySelector('[data-dropdown-trigger]');
    if (!trigger) {
        return;
    }

    trigger.addEventListener('click', function (event) {
        event.preventDefault();
        document.querySelectorAll('[data-dropdown].is-open').forEach(function (openDropdown) {
            if (openDropdown !== dropdown) {
                openDropdown.classList.remove('is-open');
            }
        });
        dropdown.classList.toggle('is-open');
    });
});

document.addEventListener('click', function (event) {
    document.querySelectorAll('[data-dropdown].is-open').forEach(function (dropdown) {
        if (!dropdown.contains(event.target)) {
            dropdown.classList.remove('is-open');
        }
    });
});

document.querySelectorAll('[data-copy-code]').forEach(function (button) {
    button.addEventListener('click', function () {
        var code = button.getAttribute('data-copy-code') || '';
        if (navigator.clipboard && code !== '') {
            navigator.clipboard.writeText(code);
        }
    });
});

document.querySelectorAll('tr[data-href]').forEach(function (row) {
    row.addEventListener('click', function (event) {
        if (event.target.closest('a, button, input, label')) {
            return;
        }
        var href = row.getAttribute('data-href');
        if (href) {
            window.location.href = href;
        }
    });
});
</script>
</body>
</html>



