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

$addonId = (int) ($_GET['id'] ?? 0);
$existing = $addonId > 0 ? billing_get_addon((int) $user['id'], (int) $organization['id'], $addonId) : null;
$products = billing_active_products((int) $user['id'], (int) $organization['id']);
$units = billing_catalog_units();
$accounts = billing_catalog_accounts();
$planModeOptions = ['All Plans', 'None', 'Selected Plans'];
$intervalOptions = ['Week(s)', 'Month(s)', 'Year(s)'];

$form = [
    'product_item_id' => (string) ($existing['product_item_id'] ?? ''),
    'addon_name' => (string) ($existing['addon_name'] ?? ''),
    'addon_code' => (string) ($existing['addon_code'] ?? ''),
    'addon_description' => (string) ($existing['addon_description'] ?? ''),
    'addon_type' => (string) ($existing['addon_type'] ?? 'Recurring'),
    'billing_frequency_value' => (string) ($existing['billing_frequency_value'] ?? '1'),
    'billing_frequency_unit' => (string) ($existing['billing_frequency_unit'] ?? 'Month(s)'),
    'pricing_model' => (string) ($existing['pricing_model'] ?? 'Per Unit'),
    'unit_name' => (string) ($existing['unit_name'] ?? ''),
    'price' => (string) ($existing['price'] ?? ''),
    'item_type' => strtolower((string) ($existing['item_type'] ?? 'Service')) === 'goods' ? 'goods' : 'service',
    'associate_plans_mode' => (string) ($existing['associate_plans_mode'] ?? 'All Plans'),
    'display_in_widgets' => !empty($existing['display_in_widgets']) ? '1' : '',
    'allow_portal_associate' => !empty($existing['allow_portal_associate']) ? '1' : '',
    'account_name' => (string) ($existing['account_name'] ?? 'Sales'),
];
$selectedPlanIds = array_map('intval', (array) ($existing['associate_plan_ids'] ?? []));
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach (array_keys($form) as $field) {
        $form[$field] = billing_clean((string) ($_POST[$field] ?? ''));
    }
    $form['display_in_widgets'] = !empty($_POST['display_in_widgets']) ? '1' : '';
    $form['allow_portal_associate'] = !empty($_POST['allow_portal_associate']) ? '1' : '';
    $selectedPlanIds = array_values(array_map('intval', (array) ($_POST['associate_plan_ids'] ?? [])));

    if ((int) $form['product_item_id'] <= 0) {
        $errors['product_item_id'] = 'Select a product.';
    }
    if ($form['addon_name'] === '') {
        $errors['addon_name'] = 'Enter the addon name.';
    }
    if ($form['price'] === '' || !is_numeric($form['price']) || (float) $form['price'] < 0) {
        $errors['price'] = 'Enter a valid price.';
    }
    if (!in_array($form['billing_frequency_unit'], $intervalOptions, true)) {
        $form['billing_frequency_unit'] = 'Month(s)';
    }
    if ($form['pricing_model'] === 'Per Unit' && $form['unit_name'] === '') {
        $errors['unit_name'] = 'Select the unit name.';
    }
    if (!in_array($form['associate_plans_mode'], $planModeOptions, true)) {
        $form['associate_plans_mode'] = 'All Plans';
    }
    if ($form['associate_plans_mode'] === 'Selected Plans' && $selectedPlanIds === []) {
        $errors['associate_plan_ids'] = 'Select at least one plan.';
    }

    if ($errors === []) {
        $payload = $form;
        $payload['associate_plan_ids'] = $selectedPlanIds;
        $payload['billing_frequency_value'] = $form['addon_type'] === 'One Time' ? '' : '1';
        $savedId = billing_save_addon((int) $user['id'], (int) $organization['id'], $payload, $existing ? $addonId : null);
        if ($savedId) {
            billing_flash('success', $existing ? 'Addon updated successfully.' : 'Addon created successfully.');
            billing_redirect('addons.php');
        }
        $errors['save'] = 'Unable to save the addon right now.';
    }
}

$selectedProductId = (int) $form['product_item_id'];
$availablePlans = billing_get_plans((int) $user['id'], (int) $organization['id'], 'active');
?>
<!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 $existing ? 'Edit Addon' : 'Add Addon'; ?> | 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-addon-2">
<style>
.addon-top-grid {
    display: grid;
    grid-template-columns: minmax(0, 1fr) 280px;
    gap: 26px;
    padding: 22px 26px 0;
}

.addon-form-grid,
.addon-tab-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 18px 28px;
}

.addon-field {
    display: grid;
    gap: 10px;
}

.addon-field label {
    color: #0f172a;
    font-size: 14px;
    font-weight: 600;
}

.addon-field input,
.addon-field select,
.addon-field textarea {
    width: 100%;
    min-height: 46px;
    border: 1px solid #d6dfeb;
    border-radius: 12px;
    background: #fff;
    color: #0f172a;
    font: inherit;
    padding: 10px 14px;
}

.addon-field textarea {
    min-height: 74px;
    resize: vertical;
}

.addon-field input:focus,
.addon-field select:focus,
.addon-field textarea:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.12);
}

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

.addon-tabs a {
    padding: 14px 24px;
    border: 1px solid #dce5ef;
    border-bottom: 0;
    border-radius: 14px 14px 0 0;
    margin-right: 8px;
    text-decoration: none;
    color: #111827;
    font-weight: 700;
    background: #fff;
}

.addon-tabs a.is-active {
    box-shadow: inset 0 3px 0 #29ba69;
}

.addon-tab-panel {
    display: none;
    padding: 22px 26px 0;
}

.addon-tab-panel.is-active {
    display: block;
}

.addon-inline-suffix {
    min-height: 46px;
    display: inline-flex;
    align-items: center;
    padding: 0 14px;
    border: 1px solid #d6dfeb;
    border-left: 0;
    border-radius: 0 12px 12px 0;
    color: #475569;
    background: #f8fafc;
    white-space: nowrap;
}

.addon-price-row {
    display: grid;
    grid-template-columns: minmax(0, 1fr) 1fr;
    gap: 22px 28px;
}

.addon-price-combo {
    display: flex;
}

.addon-price-combo .customer-prefix-field {
    flex: 1;
}

.addon-price-combo .customer-prefix-field input {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
}

.addon-plan-list {
    display: grid;
    gap: 10px;
    padding: 14px 16px;
    border: 1px solid #dce5ef;
    border-radius: 14px;
    background: #fbfdff;
}

.addon-plan-row {
    display: flex;
    align-items: center;
    gap: 10px;
}

.addon-empty-box {
    padding: 14px 16px;
    border: 1px dashed #d3dce8;
    border-radius: 14px;
    color: #64748b;
    background: #fbfdff;
}

.is-hidden {
    display: none;
}

@media (max-width: 1100px) {
    .addon-top-grid,
    .addon-form-grid,
    .addon-tab-grid,
    .addon-price-row {
        grid-template-columns: 1fr;
    }

    .addon-tabs {
        flex-wrap: wrap;
        gap: 8px;
    }

    .addon-tabs a {
        border-bottom: 1px solid #dce5ef;
        border-radius: 12px;
        margin-right: 0;
    }
}
</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-form-page">
            <form method="post" class="catalog-form-card">
                <div class="customer-form-header"><h1><?php echo $existing ? 'Edit Addon' : 'Add Addon'; ?></h1></div>
                <?php if (isset($errors['save'])): ?><div class="customer-error-banner"><span><?php echo billing_escape($errors['save']); ?></span></div><?php endif; ?>

                <div class="addon-top-grid">
                    <div class="addon-form-grid">
                        <div class="addon-field">
                            <label class="is-required">Product*</label>
                            <select name="product_item_id" id="addonProduct">
                                <option value="">Select Product</option>
                                <?php foreach ($products as $product): ?>
                                    <option value="<?php echo (int) $product['id']; ?>" <?php echo (int) $form['product_item_id'] === (int) $product['id'] ? 'selected' : ''; ?>><?php echo billing_escape((string) $product['item_name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <?php if (isset($errors['product_item_id'])): ?><div class="field-error"><?php echo billing_escape($errors['product_item_id']); ?></div><?php endif; ?>
                        </div>
                        <div></div>

                        <div class="addon-field">
                            <label class="is-required">Addon Name*</label>
                            <input type="text" name="addon_name" value="<?php echo billing_escape($form['addon_name']); ?>">
                            <?php if (isset($errors['addon_name'])): ?><div class="field-error"><?php echo billing_escape($errors['addon_name']); ?></div><?php endif; ?>
                        </div>

                        <div class="addon-field">
                            <label>Addon Code</label>
                            <input type="text" name="addon_code" value="<?php echo billing_escape($form['addon_code']); ?>">
                        </div>

                        <div class="addon-field">
                            <label>Addon Description</label>
                            <textarea name="addon_description"><?php echo billing_escape($form['addon_description']); ?></textarea>
                        </div>

                        <div class="addon-field">
                            <label class="is-required">Addon Type*</label>
                            <div class="customer-radio-row">
                                <label><input type="radio" name="addon_type" value="One Time" <?php echo $form['addon_type'] === 'One Time' ? 'checked' : ''; ?>> One-time</label>
                                <label><input type="radio" name="addon_type" value="Recurring" <?php echo $form['addon_type'] === 'Recurring' ? 'checked' : ''; ?>> Recurring</label>
                            </div>
                        </div>

                        <div class="addon-field">
                            <label class="is-required">Pricing Interval*</label>
                            <select name="billing_frequency_unit" id="addonInterval">
                                <?php foreach ($intervalOptions as $option): ?>
                                    <option value="<?php echo billing_escape($option); ?>" <?php echo $form['billing_frequency_unit'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="catalog-image-box catalog-image-box--form">
                        <div class="catalog-image-placeholder"><i class="fa-regular fa-image"></i></div>
                        <span>Drag image(s) here or <strong>Browse images</strong></span>
                    </div>
                </div>

                <div class="addon-tabs">
                    <a class="is-active" href="#addonPricing" data-addon-tab="addonPricing">Pricing</a>
                    <a href="#addonPlans" data-addon-tab="addonPlans">Plans</a>
                    <a href="#addonHosted" data-addon-tab="addonHosted">Hosted Payment Pages &amp; Portal</a>
                    <a href="#addonOther" data-addon-tab="addonOther">Other Details</a>
                </div>

                <section class="addon-tab-panel is-active" id="addonPricing">
                    <div class="addon-tab-grid">
                        <div class="addon-field">
                            <label class="is-required">Pricing Model*</label>
                            <select name="pricing_model">
                                <option value="Per Unit" <?php echo $form['pricing_model'] === 'Per Unit' ? 'selected' : ''; ?>>Per Unit</option>
                                <option value="Package" <?php echo $form['pricing_model'] === 'Package' ? 'selected' : ''; ?>>Package</option>
                            </select>
                        </div>

                        <div class="addon-field">
                            <label class="is-required">Unit Name*</label>
                            <select name="unit_name">
                                <option value="">Select</option>
                                <?php foreach ($units as $unit): ?>
                                    <option value="<?php echo billing_escape($unit); ?>" <?php echo $form['unit_name'] === $unit ? 'selected' : ''; ?>><?php echo billing_escape($unit); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <?php if (isset($errors['unit_name'])): ?><div class="field-error"><?php echo billing_escape($errors['unit_name']); ?></div><?php endif; ?>
                        </div>
                    </div>

                    <div class="addon-price-row" style="margin-top: 18px;">
                        <div class="addon-field">
                            <label class="is-required">Price*</label>
                            <div class="addon-price-combo">
                                <div class="customer-prefix-field">
                                    <span>INR</span>
                                    <input type="text" name="price" value="<?php echo billing_escape($form['price']); ?>">
                                </div>
                                <span class="addon-inline-suffix" id="addonPriceSuffix">/unit/month</span>
                            </div>
                            <?php if (isset($errors['price'])): ?><div class="field-error"><?php echo billing_escape($errors['price']); ?></div><?php endif; ?>
                        </div>

                        <div class="addon-field">
                            <label class="is-required">Type*</label>
                            <div class="customer-radio-row">
                                <label><input type="radio" name="item_type" value="goods" <?php echo $form['item_type'] === 'goods' ? 'checked' : ''; ?>> Goods</label>
                                <label><input type="radio" name="item_type" value="service" <?php echo $form['item_type'] === 'service' ? 'checked' : ''; ?>> Service</label>
                            </div>
                        </div>
                    </div>
                </section>

                <section class="addon-tab-panel" id="addonPlans">
                    <div class="addon-tab-grid">
                        <div class="addon-field">
                            <label class="is-required">Associated Plans*</label>
                            <select name="associate_plans_mode" id="addonPlansMode">
                                <?php foreach ($planModeOptions as $option): ?>
                                    <option value="<?php echo billing_escape($option); ?>" <?php echo $form['associate_plans_mode'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="addon-field<?php echo $form['associate_plans_mode'] === 'Selected Plans' ? '' : ' is-hidden'; ?>" id="addonSelectedPlans" style="margin-top: 18px;">
                        <label>Selected Plans</label>
                        <div class="addon-plan-list" id="addonPlanList">
                            <?php foreach ($availablePlans as $plan): ?>
                                <label class="addon-plan-row<?php echo $selectedProductId > 0 && (int) $plan['product_item_id'] !== $selectedProductId ? ' is-hidden' : ''; ?>" data-product-id="<?php echo (int) $plan['product_item_id']; ?>">
                                    <input type="checkbox" name="associate_plan_ids[]" value="<?php echo (int) $plan['id']; ?>" <?php echo in_array((int) $plan['id'], $selectedPlanIds, true) ? 'checked' : ''; ?>>
                                    <span><?php echo billing_escape((string) $plan['plan_name']); ?><?php echo $plan['plan_code'] !== '' ? ' (' . billing_escape((string) $plan['plan_code']) . ')' : ''; ?></span>
                                </label>
                            <?php endforeach; ?>
                            <div class="addon-empty-box<?php echo $selectedProductId > 0 ? '' : ' is-hidden'; ?>" id="addonPlansEmpty">No active plans found for the selected product.</div>
                        </div>
                        <?php if (isset($errors['associate_plan_ids'])): ?><div class="field-error"><?php echo billing_escape($errors['associate_plan_ids']); ?></div><?php endif; ?>
                    </div>
                </section>

                <section class="addon-tab-panel" id="addonHosted">
                    <label class="checkbox-row"><input type="checkbox" name="display_in_widgets" value="1" <?php echo $form['display_in_widgets'] === '1' ? 'checked' : ''; ?>> Display this addon in the pricing and checkout widgets.</label>
                    <label class="checkbox-row"><input type="checkbox" name="allow_portal_associate" value="1" <?php echo $form['allow_portal_associate'] === '1' ? 'checked' : ''; ?>> Allow customers to associate this addon with subscriptions in the portal.</label>
                </section>

                <section class="addon-tab-panel" id="addonOther">
                    <div class="addon-tab-grid">
                        <div class="addon-field">
                            <label>Account</label>
                            <select name="account_name">
                                <?php foreach ($accounts as $account): ?>
                                    <option value="<?php echo billing_escape($account); ?>" <?php echo $form['account_name'] === $account ? 'selected' : ''; ?>><?php echo billing_escape($account); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </section>

                <div class="customer-form-footer" style="padding: 18px 26px 0;">
                    <button class="customer-btn customer-btn--green" type="submit">Save</button>
                    <a class="customer-btn" href="addons.php">Cancel</a>
                </div>
            </form>
        </main>
    </div>
</div>
<script>
function syncAddonPlanChoices() {
    var product = document.getElementById('addonProduct');
    var mode = document.getElementById('addonPlansMode');
    var selectedWrap = document.getElementById('addonSelectedPlans');
    var list = document.getElementById('addonPlanList');
    var empty = document.getElementById('addonPlansEmpty');
    var productId = product ? product.value : '';
    var visibleCount = 0;

    if (selectedWrap) {
        selectedWrap.classList.toggle('is-hidden', !mode || mode.value !== 'Selected Plans');
    }
    if (!list) {
        return;
    }

    list.querySelectorAll('.addon-plan-row').forEach(function (row) {
        var show = productId !== '' && row.getAttribute('data-product-id') === productId;
        row.classList.toggle('is-hidden', !show);
        if (!show) {
            var input = row.querySelector('input[type="checkbox"]');
            if (input) {
                input.checked = false;
            }
        } else {
            visibleCount += 1;
        }
    });

    if (empty) {
        empty.classList.toggle('is-hidden', productId === '' || visibleCount > 0);
    }
}

function syncAddonPriceSuffix() {
    var interval = document.getElementById('addonInterval');
    var suffix = document.getElementById('addonPriceSuffix');
    var pricingModel = document.querySelector('select[name="pricing_model"]');
    var addonType = document.querySelector('input[name="addon_type"]:checked');
    if (!interval || !suffix) {
        return;
    }
    var pricingValue = pricingModel ? pricingModel.value : 'Per Unit';
    var typeValue = addonType ? addonType.value : 'Recurring';
    var suffixParts = [];

    if (pricingValue === 'Per Unit') {
        suffixParts.push('unit');
    }
    if (typeValue !== 'One Time') {
        suffixParts.push(interval.value.toLowerCase().replace('(s)', '').trim());
    }

    suffix.textContent = suffixParts.length ? '/' + suffixParts.join('/') : '';
}

function syncAddonRecurringState() {
    var addonType = document.querySelector('input[name="addon_type"]:checked');
    var interval = document.getElementById('addonInterval');
    var plansTab = document.querySelector('[data-addon-tab="addonPlans"]');
    var plansPanel = document.getElementById('addonPlans');
    var isRecurring = !addonType || addonType.value !== 'One Time';

    if (interval) {
        interval.disabled = !isRecurring;
    }
    if (plansTab) {
        plansTab.classList.toggle('is-hidden', !isRecurring);
    }
    if (!isRecurring && plansPanel && plansPanel.classList.contains('is-active')) {
        activateAddonTab('addonPricing');
    }
    syncAddonPriceSuffix();
}

function activateAddonTab(panelId) {
    document.querySelectorAll('[data-addon-tab]').forEach(function (tab) {
        var isActive = tab.getAttribute('data-addon-tab') === panelId;
        tab.classList.toggle('is-active', isActive);
    });
    document.querySelectorAll('.addon-tab-panel').forEach(function (panel) {
        panel.classList.toggle('is-active', panel.id === panelId);
    });
}

var addonProduct = document.getElementById('addonProduct');
var addonPlansMode = document.getElementById('addonPlansMode');
var addonInterval = document.getElementById('addonInterval');
var addonPricingModel = document.querySelector('select[name="pricing_model"]');

document.querySelectorAll('[data-addon-tab]').forEach(function (tab) {
    tab.addEventListener('click', function (event) {
        event.preventDefault();
        activateAddonTab(tab.getAttribute('data-addon-tab'));
    });
});

if (addonProduct) {
    addonProduct.addEventListener('change', syncAddonPlanChoices);
}
if (addonPlansMode) {
    addonPlansMode.addEventListener('change', syncAddonPlanChoices);
}
if (addonInterval) {
    addonInterval.addEventListener('change', syncAddonPriceSuffix);
}
if (addonPricingModel) {
    addonPricingModel.addEventListener('change', syncAddonPriceSuffix);
}
document.querySelectorAll('input[name="addon_type"]').forEach(function (input) {
    input.addEventListener('change', syncAddonRecurringState);
});

syncAddonPlanChoices();
syncAddonRecurringState();
syncAddonPriceSuffix();
</script>
<script src="assets/billing.js"></script>
</body>
</html>



