<?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 = 'addons';

$addons = billing_get_addons((int) $user['id'], (int) $organization['id'], 'active');
$flashSuccess = billing_flash('success');
$selectedAddonId = (int) ($_GET['id'] ?? 0);
$selectedAddon = null;

if ($selectedAddonId > 0) {
    $selectedAddon = billing_get_addon((int) $user['id'], (int) $organization['id'], $selectedAddonId);
}

if (!$selectedAddon && $addons !== []) {
    $selectedAddon = billing_get_addon((int) $user['id'], (int) $organization['id'], (int) $addons[0]['id']);
    $selectedAddonId = $selectedAddon ? (int) $selectedAddon['id'] : 0;
}

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

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

$selectedPlanNames = [];
if ($selectedAddon && strtolower((string) ($selectedAddon['associate_plans_mode'] ?? '')) === 'selected plans') {
    $availablePlans = billing_active_plans_for_product(
        (int) $user['id'],
        (int) $organization['id'],
        (int) ($selectedAddon['product_item_id'] ?? 0)
    );
    $selectedIds = array_map('intval', is_array($selectedAddon['associate_plan_ids'] ?? null) ? $selectedAddon['associate_plan_ids'] : []);
    foreach ($availablePlans as $plan) {
        if (in_array((int) ($plan['id'] ?? 0), $selectedIds, true)) {
            $selectedPlanNames[] = (string) ($plan['plan_name'] ?? '');
        }
    }
}

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

    $timestamp = strtotime($value);
    if ($timestamp === false) {
        return $value;
    }

    return date('d/m/Y', $timestamp);
};

$detailRows = [];
if ($selectedAddon) {
    $detailRows = [
        ['label' => 'Addon Name', 'value' => (string) ($selectedAddon['addon_name'] ?? '-')],
        ['label' => 'Addon Code', 'value' => (string) ($selectedAddon['addon_code'] ?? '-')],
        ['label' => 'Addon Type', 'value' => (string) ($selectedAddon['addon_type'] ?? '-')],
        ['label' => 'Created On', 'value' => $formatDate((string) ($selectedAddon['created_at'] ?? ''))],
        ['label' => 'Product Name', 'value' => (string) ($selectedAddon['product_name'] ?? '-')],
        ['label' => 'Associated Plans', 'value' => strtolower((string) ($selectedAddon['associate_plans_mode'] ?? 'all plans')) === 'selected plans' ? ($selectedPlanNames !== [] ? implode(', ', $selectedPlanNames) : 'Selected Plans') : 'All Plans'],
        ['label' => 'Pricing Interval', 'value' => strtolower((string) ($selectedAddon['addon_type'] ?? '')) === 'one time' ? 'One Time' : (string) ($selectedAddon['billing_frequency_unit'] ?? '-')],
        ['label' => 'Unit name', 'value' => (string) ($selectedAddon['unit_name'] ?? '-')],
    ];
}
?>
<!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>Addons | 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=20260507-css-recovery-2">
<style>
.addon-detail-shell {
    padding: 0;
}

.addon-layout {
    background: #fff;
}

.addon-list-table td,
.addon-list-table th {
    white-space: nowrap;
}

.addon-list-table .is-name-cell {
    min-width: 220px;
}

.addon-list-link {
    display: grid;
    gap: 6px;
    color: inherit;
    text-decoration: none;
}

.addon-list-link strong {
    color: #17233b;
    font-size: 17px;
}

.addon-list-link span {
    color: #5f7090;
}

.addon-status-text {
    color: #17a460;
    font-weight: 700;
}

.addon-side-name {
    margin: 0;
    font-size: 18px;
}

.addon-detail-tabs {
    display: flex;
    gap: 34px;
    padding: 0 18px;
    border-bottom: 1px solid #e8edf5;
}

.addon-detail-tabs a {
    min-height: 56px;
    display: inline-flex;
    align-items: center;
    text-decoration: none;
    color: #2b3953;
    font-size: 15px;
}

.addon-detail-tabs a.is-active {
    color: #111b2d;
    font-weight: 800;
    box-shadow: inset 0 -3px 0 #3b82f6;
}

.addon-detail-body {
    padding: 26px 26px 28px;
}

.addon-detail-main {
    display: grid;
    grid-template-columns: minmax(0, 1.2fr) 320px;
    gap: 38px;
    align-items: start;
}

.addon-kv-grid {
    display: grid;
    grid-template-columns: 140px minmax(0, 1fr);
    gap: 18px 26px;
}

.addon-kv-grid dt,
.addon-section-grid dt {
    color: #667799;
}

.addon-kv-grid dd,
.addon-section-grid dd {
    margin: 0;
    color: #111b2d;
}

.addon-image-box {
    min-height: 240px;
    justify-content: flex-end;
}

.addon-divider {
    margin: 30px 0;
    border: 0;
    border-top: 1px solid #e8edf5;
}

.addon-section-block + .addon-section-block {
    margin-top: 28px;
}

.addon-section-block h3 {
    margin: 0 0 18px;
    font-size: 18px;
    font-weight: 500;
}

.addon-section-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(220px, 1fr));
    gap: 22px 60px;
}

.addon-section-grid > div {
    display: grid;
    gap: 8px;
}

.addon-list-price {
    text-align: right;
    color: #17233b;
    font-weight: 700;
}

.addon-list-frequency {
    color: #5f7090;
}

.addon-actions-more {
    padding-right: 12px;
}

.addon-close-link {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    border: 1px solid #dce5ef;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    color: #6c7a92;
    text-decoration: none;
    background: #fff;
}

@media (max-width: 1280px) {
    .addon-detail-main,
    .addon-section-grid {
        grid-template-columns: 1fr 1fr;
    }
}

@media (max-width: 900px) {
    .addon-detail-main,
    .addon-section-grid {
        grid-template-columns: 1fr;
    }

    .addon-detail-tabs {
        overflow-x: auto;
        gap: 22px;
    }

    .addon-kv-grid {
        grid-template-columns: 1fr;
    }
}
</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 addon-detail-shell">
            <?php if ($flashSuccess): ?><div class="customer-flash"><?php echo billing_escape($flashSuccess); ?></div><?php endif; ?>

            <section class="catalog-split-card addon-layout<?php echo $selectedAddon ? '' : ' catalog-split-card--list-only'; ?>">
                <div class="catalog-list-pane<?php echo $selectedAddon ? '' : ' catalog-list-pane--empty'; ?>">
                    <div class="catalog-list-head">
                        <div class="catalog-view-links">
                            <a class="is-active" href="addons.php">All Addons</a>
                        </div>
                        <div class="customer-view-actions">
                            <a class="customer-btn customer-btn--green" href="addon_new.php"><i class="fa-solid fa-plus"></i> New</a>
                            <div class="customer-menu-wrap customer-menu-wrap--table">
                                <button class="customer-btn customer-btn--icon" type="button" data-menu-toggle="addonTableMenu"><i class="fa-solid fa-ellipsis"></i></button>
                                <div class="customer-pop-menu customer-pop-menu--table" id="addonTableMenu" hidden>
                                    <button class="menu-item" type="button" data-customer-note="Import addons can be added next."><i class="fa-solid fa-file-import"></i><span>Import Addons</span></button>
                                    <button class="menu-item" type="button" data-customer-note="Export addons can be added next."><i class="fa-solid fa-file-export"></i><span>Export</span></button>
                                    <a class="menu-item" href="<?php echo billing_escape($buildAddonsUrl()); ?>"><i class="fa-solid fa-rotate"></i><span>Refresh List</span></a>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="customer-table-wrap">
                        <table class="customer-table-view addon-list-table">
                            <thead>
                                <tr>
                                    <th class="customer-table-filter-col"><input type="checkbox" aria-label="Select all addons"></th>
                                    <th>NAME</th>
                                    <th>RATE</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($addons === []): ?>
                                    <tr><td colspan="3" class="customer-table-empty">There aren't any addons yet.</td></tr>
                                <?php else: ?>
                                    <?php foreach ($addons as $addon): ?>
                                        <?php
                                        $addonId = (int) ($addon['id'] ?? 0);
                                        $isSelected = $selectedAddonId === $addonId;
                                        ?>
                                        <tr<?php echo $isSelected ? ' style="background:#f5f8ff;"' : ''; ?>>
                                            <td><input type="checkbox" aria-label="Select addon"></td>
                                            <td class="is-name-cell">
                                                <a class="addon-list-link" href="<?php echo billing_escape($buildAddonsUrl(['id' => $addonId])); ?>">
                                                    <strong><?php echo billing_escape((string) $addon['addon_name']); ?></strong>
                                                    <span><?php echo billing_escape((string) $addon['addon_code']); ?></span>
                                                    <span class="addon-status-text"><?php echo billing_escape(strtoupper((string) $addon['status_label'])); ?></span>
                                                </a>
                                            </td>
                                            <td class="addon-list-price"><?php echo billing_escape('₹' . number_format((float) ($addon['price'] ?? 0), 2)); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <?php if ($selectedAddon): ?>
                    <div class="catalog-detail-pane">
                        <div class="catalog-detail-head">
                            <h1 class="addon-side-name"><?php echo billing_escape((string) $selectedAddon['addon_name']); ?></h1>
                            <div class="catalog-detail-actions">
                                <a class="customer-btn" href="addon_new.php?id=<?php echo (int) $selectedAddon['id']; ?>"><i class="fa-regular fa-pen-to-square"></i> Edit</a>
                                <div class="customer-menu-wrap">
                                    <button class="customer-btn addon-actions-more" type="button" data-menu-toggle="addonDetailMenu">More <i class="fa-solid fa-angle-down"></i></button>
                                    <div class="customer-pop-menu" id="addonDetailMenu" hidden>
                                        <a class="menu-item" href="addon_new.php?id=<?php echo (int) $selectedAddon['id']; ?>"><span>Edit Addon</span></a>
                                    </div>
                                </div>
                                <a class="addon-close-link" href="addons.php" aria-label="Close"><i class="fa-solid fa-xmark"></i></a>
                            </div>
                        </div>

                        <div class="addon-detail-tabs">
                            <a class="is-active" href="#">Overview</a>
                            <a href="#">Plans</a>
                            <a href="#">Price Lists</a>
                            <a href="#">Activity Logs</a>
                        </div>

                        <div class="addon-detail-body">
                            <div class="addon-detail-main">
                                <div>
                                    <dl class="addon-kv-grid">
                                        <?php foreach ($detailRows as $row): ?>
                                            <dt><?php echo billing_escape((string) $row['label']); ?></dt>
                                            <dd>
                                                <?php if ((string) $row['label'] === 'Product Name'): ?>
                                                    <a class="customer-name-link" href="items.php"><?php echo billing_escape((string) $row['value']); ?></a>
                                                <?php else: ?>
                                                    <?php echo billing_escape((string) $row['value']); ?>
                                                <?php endif; ?>
                                            </dd>
                                        <?php endforeach; ?>
                                    </dl>
                                </div>

                                <div class="catalog-image-box addon-image-box">
                                    <div class="catalog-image-placeholder"><i class="fa-regular fa-image"></i></div>
                                    <a href="addon_new.php?id=<?php echo (int) $selectedAddon['id']; ?>">Change Image</a>
                                </div>
                            </div>

                            <hr class="addon-divider">

                            <section class="addon-section-block">
                                <h3>Hosted Payment Pages &amp; Portal Preferences</h3>
                                <div class="addon-section-grid">
                                    <div>
                                        <dt>Include in Widget</dt>
                                        <dd><?php echo !empty($selectedAddon['display_in_widgets']) ? 'true' : 'false'; ?></dd>
                                    </div>
                                    <div>
                                        <dt>Show in Portal</dt>
                                        <dd><?php echo !empty($selectedAddon['allow_portal_associate']) ? 'true' : 'false'; ?></dd>
                                    </div>
                                </div>
                            </section>

                            <section class="addon-section-block">
                                <h3>Pricing Details</h3>
                                <div class="addon-section-grid">
                                    <div>
                                        <dt>Pricing Model</dt>
                                        <dd><?php echo billing_escape((string) $selectedAddon['pricing_model']); ?></dd>
                                    </div>
                                    <div>
                                        <dt>Price</dt>
                                        <dd><?php echo billing_escape('₹' . number_format((float) ($selectedAddon['price'] ?? 0), 2)); ?></dd>
                                    </div>
                                </div>
                            </section>

                            <section class="addon-section-block">
                                <h3>Other Details</h3>
                                <div class="addon-section-grid">
                                    <div>
                                        <dt>Account Name</dt>
                                        <dd><?php echo billing_escape((string) ($selectedAddon['account_name'] ?? '-')); ?></dd>
                                    </div>
                                    <div>
                                        <dt>Type</dt>
                                        <dd><?php echo billing_escape((string) ($selectedAddon['item_type'] ?? '-')); ?></dd>
                                    </div>
                                </div>
                            </section>
                        </div>
                    </div>
                <?php endif; ?>
            </section>
        </main>
    </div>
</div>
<script src="assets/billing.js"></script>
</body>
</html>
