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

$couponId = (int) ($_GET['id'] ?? 0);
$existing = $couponId > 0 ? billing_get_coupon((int) $user['id'], (int) $organization['id'], $couponId) : null;
$products = billing_active_products((int) $user['id'], (int) $organization['id']);

$planModeOptions = ['All Plans', 'None', 'Selected Plans'];
$addonModeOptions = ['All Addons', 'All Recurring Addons', 'All One-time Addons', 'None', 'Selected Addons'];
$redemptionTypeOptions = ['One-Time', 'Multiple'];
$discountByOptions = ['Flat', 'Percentage'];

$form = [
    'product_item_id' => (string) ($existing['product_item_id'] ?? ''),
    'coupon_name' => (string) ($existing['coupon_name'] ?? ''),
    'coupon_code' => (string) ($existing['coupon_code'] ?? ''),
    'discount_value' => (string) ($existing['discount_value'] ?? ''),
    'discount_by' => (string) ($existing['discount_by'] ?? 'Flat'),
    'redemption_type' => (string) ($existing['redemption_type'] ?? 'One-Time'),
    'associate_plans_mode' => (string) ($existing['associate_plans_mode'] ?? 'All Plans'),
    'associate_addons_mode' => (string) ($existing['associate_addons_mode'] ?? 'All Recurring Addons'),
    'expiration_date' => (string) ($existing['expiration_date'] ?? ''),
    'maximum_redemptions' => (string) ($existing['maximum_redemptions'] ?? ''),
];
$selectedPlanIds = array_map('intval', (array) ($existing['associate_plan_ids'] ?? []));
$selectedAddonIds = array_map('intval', (array) ($existing['associate_addon_ids'] ?? []));
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach (array_keys($form) as $field) {
        $form[$field] = billing_clean((string) ($_POST[$field] ?? ''));
    }

    $selectedPlanIds = array_values(array_map('intval', (array) ($_POST['associate_plan_ids'] ?? [])));
    $selectedAddonIds = array_values(array_map('intval', (array) ($_POST['associate_addon_ids'] ?? [])));

    if ((int) $form['product_item_id'] <= 0) {
        $errors['product_item_id'] = 'Select a product.';
    }
    if ($form['coupon_name'] === '') {
        $errors['coupon_name'] = 'Enter the coupon name.';
    }
    if ($form['coupon_code'] === '') {
        $errors['coupon_code'] = 'Enter the coupon code.';
    }
    if ($form['discount_value'] === '' || !is_numeric($form['discount_value']) || (float) $form['discount_value'] <= 0) {
        $errors['discount_value'] = 'Enter a valid discount value.';
    }
    if (!in_array($form['discount_by'], $discountByOptions, true)) {
        $form['discount_by'] = 'Flat';
    }
    if (!in_array($form['redemption_type'], $redemptionTypeOptions, true)) {
        $form['redemption_type'] = 'One-Time';
    }
    if (!in_array($form['associate_plans_mode'], $planModeOptions, true)) {
        $form['associate_plans_mode'] = 'All Plans';
    }
    if (!in_array($form['associate_addons_mode'], $addonModeOptions, true)) {
        $form['associate_addons_mode'] = 'All Recurring Addons';
    }
    if ($form['maximum_redemptions'] !== '' && (!ctype_digit($form['maximum_redemptions']) || (int) $form['maximum_redemptions'] <= 0)) {
        $errors['maximum_redemptions'] = 'Maximum redemptions must be a positive number.';
    }
    if ($form['associate_plans_mode'] === 'Selected Plans' && $selectedPlanIds === []) {
        $errors['associate_plan_ids'] = 'Select at least one plan.';
    }
    if ($form['associate_addons_mode'] === 'Selected Addons' && $selectedAddonIds === []) {
        $errors['associate_addon_ids'] = 'Select at least one addon.';
    }

    if ($errors === []) {
        $payload = $form;
        $payload['associate_plan_ids'] = $selectedPlanIds;
        $payload['associate_addon_ids'] = $selectedAddonIds;
        $savedId = billing_save_coupon((int) $user['id'], (int) $organization['id'], $payload, $existing ? $couponId : null);
        if ($savedId) {
            billing_flash('success', $existing ? 'Coupon updated successfully.' : 'Coupon created successfully.');
            billing_redirect('coupons.php?id=' . $savedId);
        }
        $errors['save'] = 'Unable to save the coupon right now.';
    }
}

$selectedProductId = (int) $form['product_item_id'];
$availablePlans = billing_get_plans((int) $user['id'], (int) $organization['id'], 'active');
$availableAddons = billing_get_addons((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 Coupon' : 'New Coupon'; ?> | 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-1">
<style>
.coupon-form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 22px 28px;
    padding: 22px 26px 4px;
}

.coupon-field,
.coupon-section-grid {
    display: grid;
    gap: 10px;
}

.coupon-field label,
.coupon-section-grid label {
    color: #0f172a;
    font-size: 14px;
    font-weight: 600;
}

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

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

.coupon-split-input {
    display: grid;
    grid-template-columns: minmax(0, 1fr) 120px;
    gap: 0;
}

.coupon-split-input input {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
}

.coupon-split-input select {
    border-left: 0;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}

.coupon-section {
    padding: 22px 26px 4px;
    border-top: 1px solid #e7edf4;
    display: grid;
    gap: 18px;
}

.coupon-section h2 {
    margin: 0;
    font-size: 18px;
}

.coupon-section-grid {
    grid-template-columns: 1fr 1fr;
    gap: 22px 28px;
}

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

.coupon-checklist label {
    display: flex;
    align-items: center;
    gap: 10px;
    font-weight: 500;
}

.coupon-help {
    color: #64748b;
    font-size: 13px;
}

.coupon-inline-note {
    color: #64748b;
    font-size: 13px;
    margin-top: -2px;
}

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

.is-hidden,
.coupon-option-row.is-hidden {
    display: none;
}

@media (max-width: 980px) {
    .coupon-form-grid,
    .coupon-section-grid,
    .coupon-split-input {
        grid-template-columns: 1fr;
    }

    .coupon-split-input select {
        border-left: 1px solid #d6dfeb;
        border-top: 0;
        border-top-left-radius: 0;
        border-bottom-left-radius: 12px;
        border-top-right-radius: 0;
        border-bottom-right-radius: 12px;
    }

    .coupon-split-input input {
        border-bottom-left-radius: 0;
        border-bottom-right-radius: 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 Coupon' : 'New Coupon'; ?></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="coupon-form-grid">
                    <div class="coupon-field">
                        <label class="is-required">Product*</label>
                        <select name="product_item_id" id="couponProduct">
                            <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="coupon-field">
                        <label class="is-required">Coupon Name*</label>
                        <input type="text" name="coupon_name" value="<?php echo billing_escape($form['coupon_name']); ?>">
                        <?php if (isset($errors['coupon_name'])): ?><div class="field-error"><?php echo billing_escape($errors['coupon_name']); ?></div><?php endif; ?>
                    </div>

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

                    <div class="coupon-field">
                        <label class="is-required">Discount (INR)*</label>
                        <div class="coupon-split-input">
                            <input type="text" name="discount_value" value="<?php echo billing_escape($form['discount_value']); ?>">
                            <select name="discount_by">
                                <?php foreach ($discountByOptions as $option): ?>
                                    <option value="<?php echo billing_escape($option); ?>" <?php echo $form['discount_by'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <?php if (isset($errors['discount_value'])): ?><div class="field-error"><?php echo billing_escape($errors['discount_value']); ?></div><?php endif; ?>
                    </div>

                    <div class="coupon-field">
                        <label class="is-required">Redemption Type*</label>
                        <select name="redemption_type">
                            <?php foreach ($redemptionTypeOptions as $option): ?>
                                <option value="<?php echo billing_escape($option); ?>" <?php echo $form['redemption_type'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <section class="coupon-section">
                    <h2>Applicability</h2>
                    <div class="coupon-section-grid">
                        <div class="coupon-field">
                            <label class="is-required">Associate Plans*</label>
                            <select name="associate_plans_mode" id="associatePlansMode">
                                <?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 class="coupon-inline-note">Choose whether the coupon applies to every plan or only selected ones.</div>
                        </div>

                        <div class="coupon-field">
                            <label class="is-required">Associate Addons*</label>
                            <select name="associate_addons_mode" id="associateAddonsMode">
                                <?php foreach ($addonModeOptions as $option): ?>
                                    <option value="<?php echo billing_escape($option); ?>" <?php echo $form['associate_addons_mode'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <div class="coupon-inline-note">You can limit this coupon to recurring, one-time, or selected addons.</div>
                        </div>

                        <div class="coupon-field" id="selectedPlansWrap">
                            <label>Selected Plans</label>
                            <div class="coupon-checklist" id="couponPlansList">
                                <?php foreach ($availablePlans as $plan): ?>
                                    <label class="coupon-option-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="coupon-empty-box<?php echo $selectedProductId > 0 ? '' : ' is-hidden'; ?>" id="couponPlansEmpty">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>

                        <div class="coupon-field" id="selectedAddonsWrap">
                            <label>Selected Addons</label>
                            <div class="coupon-checklist" id="couponAddonsList">
                                <?php foreach ($availableAddons as $addon): ?>
                                    <label class="coupon-option-row<?php echo $selectedProductId > 0 && (int) $addon['product_item_id'] !== $selectedProductId ? ' is-hidden' : ''; ?>" data-product-id="<?php echo (int) $addon['product_item_id']; ?>">
                                        <input type="checkbox" name="associate_addon_ids[]" value="<?php echo (int) $addon['id']; ?>" <?php echo in_array((int) $addon['id'], $selectedAddonIds, true) ? 'checked' : ''; ?>>
                                        <span><?php echo billing_escape((string) $addon['addon_name']); ?><?php echo $addon['addon_code'] !== '' ? ' (' . billing_escape((string) $addon['addon_code']) . ')' : ''; ?></span>
                                    </label>
                                <?php endforeach; ?>
                                <div class="coupon-empty-box<?php echo $selectedProductId > 0 ? '' : ' is-hidden'; ?>" id="couponAddonsEmpty">No active addons found for the selected product.</div>
                            </div>
                            <?php if (isset($errors['associate_addon_ids'])): ?><div class="field-error"><?php echo billing_escape($errors['associate_addon_ids']); ?></div><?php endif; ?>
                        </div>
                    </div>
                </section>

                <section class="coupon-section">
                    <h2>Validity</h2>
                    <div class="coupon-section-grid">
                        <div class="coupon-field">
                            <label>Expiration Date</label>
                            <input type="date" name="expiration_date" value="<?php echo billing_escape($form['expiration_date']); ?>">
                            <div class="coupon-help">Leave this empty if the coupon should remain valid until you deactivate it.</div>
                        </div>

                        <div class="coupon-field">
                            <label>Maximum Redemptions</label>
                            <input type="number" min="1" name="maximum_redemptions" value="<?php echo billing_escape($form['maximum_redemptions']); ?>" placeholder="Enter a number">
                            <?php if (isset($errors['maximum_redemptions'])): ?><div class="field-error"><?php echo billing_escape($errors['maximum_redemptions']); ?></div><?php endif; ?>
                        </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="coupons.php<?php echo $existing ? '?id=' . $couponId : ''; ?>">Cancel</a>
                </div>
            </form>
        </main>
    </div>
</div>
<script>
function toggleCouponSelection() {
    var planMode = document.getElementById('associatePlansMode');
    var addonMode = document.getElementById('associateAddonsMode');
    var product = document.getElementById('couponProduct');
    var planWrap = document.getElementById('selectedPlansWrap');
    var addonWrap = document.getElementById('selectedAddonsWrap');
    var selectedProductId = product ? product.value : '';

    if (planWrap) {
        planWrap.style.display = planMode && planMode.value === 'Selected Plans' ? 'grid' : 'none';
    }
    if (addonWrap) {
        addonWrap.style.display = addonMode && addonMode.value === 'Selected Addons' ? 'grid' : 'none';
    }

    syncCouponOptions('couponPlansList', 'couponPlansEmpty', selectedProductId);
    syncCouponOptions('couponAddonsList', 'couponAddonsEmpty', selectedProductId);
}

function syncCouponOptions(listId, emptyId, productId) {
    var list = document.getElementById(listId);
    var empty = document.getElementById(emptyId);
    if (!list) {
        return;
    }

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

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

var planModeEl = document.getElementById('associatePlansMode');
var addonModeEl = document.getElementById('associateAddonsMode');
var productEl = document.getElementById('couponProduct');

if (planModeEl) {
    planModeEl.addEventListener('change', toggleCouponSelection);
}
if (addonModeEl) {
    addonModeEl.addEventListener('change', toggleCouponSelection);
}
if (productEl) {
    productEl.addEventListener('change', toggleCouponSelection);
}

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



