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

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

$module = billing_sales_module('subscriptions');
if (!$module) {
    billing_redirect('dashboard.php?tab=dashboard');
}

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

$recordId = (int) ($_GET['id'] ?? 0);
$record = $recordId > 0 ? billing_get_subscription((int) $user['id'], (int) $organization['id'], $recordId) : null;
if ($recordId > 0 && !$record) {
    billing_flash('success', 'Subscription not found.');
    billing_redirect('subscriptions.php');
}

$customers = billing_sales_customer_options((int) $user['id'], (int) $organization['id']);
$products = billing_active_products((int) $user['id'], (int) $organization['id']);
$plans = billing_get_plans((int) $user['id'], (int) $organization['id'], 'active');
$planById = [];
foreach ($plans as $plan) {
    $planById[(int) $plan['id']] = $plan;
}

$customerById = [];
foreach ($customers as $customer) {
    $customerById[(int) $customer['id']] = $customer;
}

$customerUnpaidMap = [];
$invoiceRows = billing_fetch_all(
    'SELECT customer_name, status_label
     FROM invoices
     WHERE user_id = ? AND organization_id = ?',
    'ii',
    [(int) $user['id'], (int) $organization['id']]
);
foreach ($invoiceRows as $invoiceRow) {
    $nameKey = strtolower(trim((string) ($invoiceRow['customer_name'] ?? '')));
    if ($nameKey === '') {
        continue;
    }
    $status = strtolower(trim((string) ($invoiceRow['status_label'] ?? '')));
    if (in_array($status, ['overdue', 'sent', 'unpaid'], true)) {
        $customerUnpaidMap[$nameKey] = ($customerUnpaidMap[$nameKey] ?? 0) + 1;
    }
}

$today = date('Y-m-d');
$defaultStartDate = $today;
$defaultNextBillingDate = date('Y-m-d', strtotime('+1 week'));
$form = [
    'customer_id' => (int) ($_GET['customer_id'] ?? 0),
    'customer_name' => '',
    'subscription_number' => billing_next_document_number((int) $user['id'], (int) $organization['id'], 'subscriptions', 'subscription_number', 'SUB-'),
    'product_item_id' => '',
    'plan_id' => '',
    'plan_name' => '',
    'reference_number' => '',
    'salesperson_name' => '',
    'start_date' => $defaultStartDate,
    'next_billing_date' => $defaultNextBillingDate,
    'billing_frequency_value' => 1,
    'billing_frequency_unit' => 'week(s)',
    'expires_after_cycles' => '',
    'renews_forever' => 1,
    'payment_terms' => 'Due on Receipt',
    'payment_mode' => 'offline',
    'autocharge_enabled' => 0,
    'prorate_enabled' => 1,
    'generate_invoice_on_prorate' => 1,
    'status_label' => 'Live',
    'customer_notes' => 'Thanks for your business.',
    'terms_text' => '',
    'invoice_template_name' => 'Spreadsheet Template',
    'items' => [],
];

if ($record) {
    $form = array_merge($form, $record);
    $form['items'] = $record['items'] ?? [];
    $form['renews_forever'] = (int) ($record['renews_forever'] ?? 0);
    $form['autocharge_enabled'] = (int) ($record['autocharge_enabled'] ?? 0);
    $form['prorate_enabled'] = (int) ($record['prorate_enabled'] ?? 0);
    $form['generate_invoice_on_prorate'] = (int) ($record['generate_invoice_on_prorate'] ?? 0);
    if ($form['items'] !== []) {
        $form['plan_name'] = (string) ($form['items'][0]['item_name'] ?? $form['plan_name']);
        foreach ($plans as $plan) {
            if (strcasecmp((string) $plan['plan_name'], (string) $form['plan_name']) === 0) {
                $form['plan_id'] = (string) $plan['id'];
                $form['product_item_id'] = (string) $plan['product_item_id'];
                break;
            }
        }
    }
}

if ((int) $form['customer_id'] > 0 && isset($customerById[(int) $form['customer_id']])) {
    $form['customer_name'] = (string) $customerById[(int) $form['customer_id']]['customer_name'];
}

$salutationOptions = ['Mr.', 'Ms.', 'Mrs.', 'Dr.'];
$countryOptions = [
    'India',
    'Afghanistan',
    'Australia',
    'Bangladesh',
    'Bhutan',
    'Canada',
    'China',
    'Germany',
    'Japan',
    'Nepal',
    'Pakistan',
    'Singapore',
    'Sri Lanka',
    'United Arab Emirates',
    'United Kingdom',
    'United States',
];
$stateOptions = ['Tamil Nadu', 'Kerala', 'Karnataka', 'Maharashtra', 'Delhi', 'West Bengal'];
$modalCustomer = [
    'customer_type' => 'Business',
    'salutation' => '',
    'first_name' => '',
    'last_name' => '',
    'company_name' => '',
    'display_name' => '',
    'email' => '',
    'work_phone' => '',
    'mobile' => '',
    'customer_language' => 'English',
    'pan' => '',
    'currency' => 'INR- Indian Rupee',
    'payment_terms' => 'Due on Receipt',
    'enable_portal' => '',
    'billing_attention' => '',
    'billing_country' => '',
    'billing_address_1' => '',
    'billing_address_2' => '',
    'billing_city' => '',
    'billing_state' => '',
    'billing_pin' => '',
    'billing_phone' => '',
    'billing_fax' => '',
    'shipping_attention' => '',
    'shipping_country' => '',
    'shipping_address_1' => '',
    'shipping_address_2' => '',
    'shipping_city' => '',
    'shipping_state' => '',
    'shipping_pin' => '',
    'shipping_phone' => '',
    'shipping_fax' => '',
    'remarks' => '',
    'documents' => [],
];

$errors = [];
$modalErrors = [];
$showCustomerModal = isset($_GET['new_customer']);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string) ($_POST['action'] ?? '') === 'create_inline_customer') {
    foreach ($modalCustomer as $key => $value) {
        $modalCustomer[$key] = is_string($_POST[$key] ?? null) ? billing_clean((string) $_POST[$key]) : $value;
    }
    $modalCustomer['enable_portal'] = !empty($_POST['enable_portal']) ? '1' : '';
    $modalCustomer['documents'] = [];
    if ($modalCustomer['display_name'] === '') {
        $modalErrors['display_name'] = 'Enter the Display Name of your customer.';
    }

    if ($modalErrors === []) {
        $meta = billing_prepare_customer_meta($modalCustomer);
        $meta['documents'] = billing_store_uploaded_files('customer_documents', 'customer_docs');
        $customerId = billing_create_customer((int) $user['id'], (int) $organization['id'], $modalCustomer);
        if ($customerId) {
            billing_save_customer_meta($customerId, $meta);
            billing_flash('success', 'Customer created successfully.');
            billing_redirect('subscription_new.php?customer_id=' . $customerId);
        }
        $modalErrors['save'] = 'Unable to save the customer right now.';
    }
    $showCustomerModal = true;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string) ($_POST['action'] ?? '') === 'save_subscription') {
    $subscriptionMode = billing_clean((string) ($_POST['subscription_mode'] ?? 'plans'));
    $form['customer_id'] = (int) ($_POST['customer_id'] ?? 0);
    $form['customer_name'] = billing_clean((string) ($_POST['customer_name'] ?? ''));
    $form['subscription_number'] = billing_clean((string) ($_POST['subscription_number'] ?? ''));
    $form['product_item_id'] = billing_clean((string) ($_POST['product_item_id'] ?? ''));
    $form['plan_id'] = billing_clean((string) ($_POST['plan_id'] ?? ''));
    $form['plan_name'] = billing_clean((string) ($_POST['plan_name'] ?? ''));
    $form['reference_number'] = billing_clean((string) ($_POST['reference_number'] ?? ''));
    $form['salesperson_name'] = billing_clean((string) ($_POST['salesperson_name'] ?? ''));
    $form['start_date'] = billing_clean((string) ($_POST['start_date'] ?? $today));
    $form['next_billing_date'] = billing_clean((string) ($_POST['next_billing_date'] ?? ''));
    $form['billing_frequency_value'] = max(1, (int) ($_POST['billing_frequency_value'] ?? 1));
    $form['billing_frequency_unit'] = billing_clean((string) ($_POST['billing_frequency_unit'] ?? 'week(s)'));
    $form['payment_terms'] = billing_clean((string) ($_POST['payment_terms'] ?? 'Due on Receipt'));
    $form['renews_forever'] = !empty($_POST['renews_forever']) ? 1 : 0;
    $form['expires_after_cycles'] = $form['renews_forever'] ? '' : billing_clean((string) ($_POST['expires_after_cycles'] ?? ''));
    $form['payment_mode'] = !empty($_POST['payment_mode']) ? 'offline' : 'online';
    $form['autocharge_enabled'] = !empty($_POST['autocharge_enabled']) ? 1 : 0;
    $form['prorate_enabled'] = !empty($_POST['prorate_enabled']) ? 1 : 0;
    $form['generate_invoice_on_prorate'] = !empty($_POST['generate_invoice_on_prorate']) ? 1 : 0;
    $form['customer_notes'] = billing_clean((string) ($_POST['customer_notes'] ?? ''));
    $form['terms_text'] = billing_clean((string) ($_POST['terms_text'] ?? ''));
    $form['invoice_template_name'] = billing_clean((string) ($_POST['invoice_template_name'] ?? 'Spreadsheet Template'));

    $selectedPlan = $subscriptionMode === 'plans' && (int) $form['plan_id'] > 0 ? ($planById[(int) $form['plan_id']] ?? null) : null;
    if ($selectedPlan) {
        $form['plan_name'] = (string) $selectedPlan['plan_name'];
        $form['billing_frequency_value'] = (int) ($selectedPlan['billing_frequency_value'] ?? 1);
        $form['billing_frequency_unit'] = strtolower((string) ($selectedPlan['billing_frequency_unit'] ?? 'Week(s)'));
        $form['items'] = [[
            'item_id' => (int) $selectedPlan['product_item_id'],
            'item_name' => (string) $selectedPlan['plan_name'],
            'item_description' => (string) ($selectedPlan['plan_description'] ?? ''),
            'quantity' => 1,
            'unit_name' => (string) ($selectedPlan['unit_name'] ?? ''),
            'rate' => (float) ($selectedPlan['price'] ?? 0),
            'account_name' => 'Sales',
        ]];
    } else {
        $itemNames = $_POST['item_name'] ?? [];
        $itemDescriptions = $_POST['item_description'] ?? [];
        $quantities = $_POST['quantity'] ?? [];
        $rates = $_POST['rate'] ?? [];
        $units = $_POST['unit_name'] ?? [];
        $form['items'] = [];
        foreach ($itemNames as $index => $itemName) {
            $itemName = billing_clean((string) $itemName);
            $itemDescription = billing_clean((string) ($itemDescriptions[$index] ?? ''));
            $quantity = (float) ($quantities[$index] ?? 0);
            $rate = (float) ($rates[$index] ?? 0);
            $unitName = billing_clean((string) ($units[$index] ?? ''));
            if ($itemName === '' && $itemDescription === '' && $quantity <= 0 && $rate <= 0) {
                continue;
            }
            $matchedProductId = 0;
            foreach ($products as $product) {
                if (strcasecmp((string) ($product['item_name'] ?? ''), $itemName) === 0) {
                    $matchedProductId = (int) ($product['id'] ?? 0);
                    if ($unitName === '') {
                        $unitName = (string) ($product['unit_name'] ?? '');
                    }
                    break;
                }
            }
            $form['items'][] = [
                'item_id' => $matchedProductId > 0 ? $matchedProductId : null,
                'item_name' => $itemName,
                'item_description' => $itemDescription,
                'quantity' => $quantity > 0 ? $quantity : 1,
                'unit_name' => $unitName,
                'rate' => $rate,
                'account_name' => 'Sales',
            ];
        }
    }

    if ($form['customer_name'] === '' && (int) $form['customer_id'] > 0 && isset($customerById[(int) $form['customer_id']])) {
        $form['customer_name'] = (string) $customerById[(int) $form['customer_id']]['customer_name'];
    }

    if ($form['next_billing_date'] === '') {
        $frequencyValue = max(1, (int) ($form['billing_frequency_value'] ?? 1));
        $frequencyUnit = strtolower(str_replace('(s)', '', (string) ($form['billing_frequency_unit'] ?? 'week(s)')));
        $form['next_billing_date'] = date('Y-m-d', strtotime('+' . $frequencyValue . ' ' . $frequencyUnit, strtotime($form['start_date'] ?: $today)));
    }

    if ($form['customer_name'] === '') {
        $errors[] = 'Select a customer.';
    }
    if ($subscriptionMode === 'plans') {
        if ((int) $form['product_item_id'] <= 0) {
            $errors[] = 'Select a product.';
        }
        if (!$selectedPlan) {
            $errors[] = 'Select a plan.';
        }
    } else {
        if ($form['plan_name'] === '') {
            $errors[] = 'Enter a profile name.';
        }
        if ($form['items'] === []) {
            $errors[] = 'Add at least one item.';
        }
    }
    if ($form['subscription_number'] === '') {
        $errors[] = 'Enter a subscription number.';
    }

    if ($errors === []) {
        $savedId = billing_save_subscription((int) $user['id'], (int) $organization['id'], $form, $recordId > 0 ? $recordId : null);
        if ($savedId) {
            billing_flash('success', $recordId > 0 ? 'Subscription updated successfully.' : 'New Subscription saved successfully.');
            billing_redirect('subscriptions.php?id=' . $savedId);
        }
        $errors[] = 'Unable to save the subscription right now.';
    }
}

$selectedCustomer = (int) $form['customer_id'] > 0 ? ($customerById[(int) $form['customer_id']] ?? null) : null;
$selectedProductId = (int) $form['product_item_id'];
$selectedPlanId = (int) $form['plan_id'];
$selectedPlan = $selectedPlanId > 0 ? ($planById[$selectedPlanId] ?? null) : null;
$selectedCustomerSnapshot = $selectedCustomer ? billing_sales_customer_snapshot((int) $user['id'], (int) $organization['id'], (int) $selectedCustomer['id']) : null;
$subscriptionMode = (string) ($_POST['subscription_mode'] ?? ($selectedPlanId > 0 ? 'plans' : 'items'));
$showSaveFooter = $subscriptionMode === 'items' || ($subscriptionMode === 'plans' && $selectedPlanId > 0);
$paymentTermOptions = ['Due on Receipt', 'Net 15', 'Net 30', 'Net 45', 'Net 60'];
$billingFrequencyOptions = ['day(s)' => 'Day(s)', 'week(s)' => 'Week(s)', 'month(s)' => 'Month(s)', 'year(s)' => 'Year(s)'];
$salespersonOptions = ['Balachandar', 'Arun', 'Priya', 'Vikram'];
$subscriptionProjects = billing_fetch_all(
    'SELECT id, project_name
     FROM projects
     WHERE user_id = ? AND organization_id = ?
     ORDER BY project_name ASC, id ASC',
    'ii',
    [(int) $user['id'], (int) $organization['id']]
);

function billing_subscription_address_lines(?array $snapshot, string $key): array
{
    $segment = is_array($snapshot[$key] ?? null) ? $snapshot[$key] : [];
    $lines = [];
    foreach (['attention', 'address_1', 'address_2', 'city', 'state', 'pin', 'country'] as $field) {
        $value = trim((string) ($segment[$field] ?? ''));
        if ($value !== '') {
            $lines[] = $value;
        }
    }
    $phone = trim((string) ($segment['phone'] ?? ''));
    if ($phone !== '') {
        $lines[] = 'Phone: ' . $phone;
    }
    return $lines;
}
?>
<!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 billing_escape($record ? 'Edit Subscription' : 'New Subscription'); ?> | 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>
.sub-page{padding:0;background:#fff}
.sub-card{border-top:1px solid #e7edf4}
.sub-form{display:grid;gap:0}
.sub-top{padding:34px 26px 18px;display:grid;grid-template-columns:190px minmax(0,660px) 44px;gap:18px;align-items:start}
.sub-label{padding-top:14px;color:#ef4444;font-size:15px;font-weight:600}
.sub-label.sub-label-optional{color:#9ca3af;font-weight:500}
.sub-control{width:100%;min-height:44px;border:1px solid #d6dfeb;border-radius:12px;background:#fff;color:#0f172a;font:inherit;padding:10px 14px}
.sub-control:focus{outline:none;border-color:#3b82f6;box-shadow:0 0 0 3px rgba(59,130,246,.12)}
.sub-search-btn{width:44px;height:44px;border:0;border-radius:8px;background:#22c55e;color:#fff;font-size:19px}
.sub-picker{position:relative}
.sub-picker-display{display:flex;align-items:center;justify-content:space-between;gap:12px}
.sub-picker-menu{position:absolute;top:52px;left:0;width:620px;max-width:100%;background:#fff;border:1px solid #dde6f1;border-radius:14px;box-shadow:0 20px 40px rgba(15,23,42,.14);padding:8px;z-index:30}
.sub-picker-search{margin-bottom:4px}
.sub-picker-option{display:flex;align-items:center;gap:14px;padding:12px;border-radius:12px;text-decoration:none;color:#0f172a}
.sub-picker-option:hover,.sub-picker-option.is-active{background:#4f8df0;color:#fff}
.sub-picker-avatar{width:50px;height:50px;border-radius:50%;background:#eaf1ff;color:#64748b;display:flex;align-items:center;justify-content:center;font-size:24px}
.sub-picker-meta{display:grid;gap:4px}
.sub-picker-meta strong{font-size:15px}
.sub-picker-meta span{font-size:13px;opacity:.92}
.sub-picker-create{display:flex;align-items:center;gap:10px;padding:14px 12px;text-decoration:none;color:#3b82f6;font-weight:600}
.sub-body{padding:0 26px 26px}
.sub-layout{display:grid;grid-template-columns:minmax(0,1fr) 280px;gap:24px}
.sub-main{border:1px solid #eef2f7;border-radius:16px;min-height:460px;background:#fff}
.sub-inline-row{display:grid;grid-template-columns:190px minmax(0,1fr);gap:18px;padding:24px}
.sub-inline-muted{padding-top:14px;color:#9ca3af;font-size:15px}
.sub-product-select{max-width:330px}
.sub-empty-state{min-height:300px;display:grid;place-items:center;padding:32px;text-align:center;color:#c0c7d4}
.sub-empty-state p{margin:0 0 14px}
.sub-empty-state .customer-btn{pointer-events:auto}
.sub-plan-list{display:grid;gap:0}
.sub-plan-row{display:grid;grid-template-columns:1fr auto;gap:18px;padding:18px 24px;border-top:1px solid #edf2f7;cursor:pointer}
.sub-plan-row:first-child{border-top:0}
.sub-plan-row.is-active{background:#f5f9ff}
.sub-plan-row strong{display:block;margin-bottom:4px}
.sub-plan-row span{color:#64748b;font-size:13px}
.sub-plan-price{font-weight:700;color:#0f172a;align-self:center}
.sub-side-card{background:#2c3348;color:#fff;border-radius:14px;padding:18px 16px;align-self:start}
.sub-side-card strong{display:block;font-size:18px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.sub-side-card span{display:block;margin-top:8px;color:rgba(255,255,255,.78)}
.sub-details{display:grid;gap:18px;padding:24px;border-top:1px solid #edf2f7}
.sub-detail-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px 24px}
.sub-detail-field{display:grid;gap:8px}
.sub-detail-field label{font-weight:700;color:#334155}
.sub-detail-field label.is-required,
.sub-customer-grid > label.is-required{color:#ef4444}
.sub-check-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px 18px}
.sub-check-card{display:flex;align-items:center;gap:10px;border:1px solid #d9e2ef;border-radius:14px;padding:12px 14px}
.sub-footer{padding:0 26px 26px}
.sub-modal-backdrop{position:fixed;inset:0;background:rgba(15,23,42,.42);display:grid;place-items:center;padding:18px;z-index:80}
.sub-modal{width:min(1050px,calc(100vw - 30px));max-height:calc(100vh - 40px);overflow:auto;background:#fff;border-radius:18px;border:1px solid #e3eaf4;box-shadow:0 18px 48px rgba(15,23,42,.18)}
.sub-modal-head{display:flex;align-items:center;justify-content:space-between;padding:18px 24px;border-bottom:1px solid #e7edf4}
.sub-modal-head h2{margin:0;font-size:21px}
.sub-modal-close{border:0;background:none;color:#ef4444;font-size:20px}
.sub-customer-grid{display:grid;grid-template-columns:190px minmax(0,1fr);gap:18px 18px;padding:24px}
.sub-customer-grid>label{padding-top:12px;color:#374151;font-weight:600}
.sub-radio-row,.sub-three-col,.sub-phone-row{display:flex;gap:12px;align-items:center}
.sub-three-col>*{flex:1}
.sub-phone-box{display:flex;min-width:0}
.sub-phone-box span{min-width:74px;border:1px solid #d6dfeb;border-right:0;border-radius:12px 0 0 12px;padding:10px 12px;background:#f8fafc;color:#475569}
.sub-phone-box input{border-radius:0 12px 12px 0}
.sub-tabs{display:flex;gap:34px;padding:0 24px 0;border-bottom:1px solid #e7edf4}
.sub-tabs button{border:0;background:none;padding:14px 0;color:#374151;font-weight:600}
.sub-tabs button.is-active{color:#1f2937;box-shadow:inset 0 -3px 0 #4f8df0}
.sub-tab-panel{display:none;padding:24px}
.sub-tab-panel.is-active{display:block}
.sub-address-grid{display:grid;grid-template-columns:1fr 1fr;gap:34px}
.sub-address-col h3{margin:0 0 18px;font-size:18px}
.sub-address-note{margin-top:24px;padding:0 0 0 18px;border-left:3px solid #f59e0b;color:#374151;line-height:1.55}
.sub-empty-panel{min-height:240px;display:grid;place-items:center;text-align:center;color:#7c88a3;line-height:1.5}
.sub-remarks-box{width:100%;min-height:92px;border:1px solid #d6dfeb;border-radius:12px;padding:12px 14px;font:inherit}
.sub-modal-foot{display:flex;gap:10px;padding:18px 24px 24px;border-top:1px solid #eef2f7}
.helper-text{margin-top:8px;color:#7c88a3;font-size:13px}
.is-hidden{display:none!important}
@media (max-width:1100px){.sub-layout,.sub-address-grid,.sub-detail-grid,.sub-check-grid{grid-template-columns:1fr}.sub-top,.sub-inline-row,.sub-customer-grid{grid-template-columns:1fr}.sub-label,.sub-inline-muted,.sub-customer-grid>label{padding-top:0}.sub-picker-menu{width:100%}}
.sub-page--zoho{background:#fff}
.sub-form--zoho{border-top:0;background:#fff}
.sub-form--zoho .customer-error-banner{margin:0 24px 18px}
.sub-hero-head{padding:22px 28px;border-bottom:1px solid #edf2f7}
.sub-hero-head h1{margin:0;font-size:26px;font-weight:700}
.sub-hero{padding:0 24px 12px}
.sub-hero-grid{display:grid;grid-template-columns:190px minmax(0,1fr) 250px;gap:18px;padding:24px 18px 28px;background:#fbfbfd;border-bottom:1px solid #edf2f7}
.sub-hero-label,.sub-form-grid>label{color:#ef4444;font-size:15px;font-weight:500}
.sub-mode-label{color:#111827;font-size:15px;font-weight:500}
.sub-hero-main{display:grid;gap:18px}
.sub-hero-picker-row{display:flex;align-items:center;gap:12px;flex-wrap:wrap}
.sub-picker--hero{width:min(620px,100%)}
.sub-picker--hero .sub-control{min-height:42px;border-radius:10px}
.sub-picker--hero .sub-picker-menu{top:48px;width:min(620px,100%)}
.sub-search-btn{flex:0 0 44px}
.sub-currency-pill{min-height:42px;padding:0 14px;border:1px solid #d7ddeb;border-radius:10px;display:inline-flex;align-items:center;gap:8px;background:#fff}
.sub-currency-pill i{color:#10b981}
.sub-address-pair{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:34px}
.sub-address-title{margin-bottom:8px;color:#546784;font-size:13px;letter-spacing:.02em}
.sub-address-title button{border:0;background:none;color:#546784;font-size:12px;cursor:pointer;padding:0}
.sub-address-lines{min-height:72px;color:#111827;line-height:1.4}
.sub-address-lines:empty::before{content:"No address available";color:#94a3b8}
.sub-email-row{display:grid;grid-template-columns:190px minmax(0,1fr);gap:18px}
.sub-email-label{color:#546784;font-size:15px;padding-top:10px}
.sub-email-actions{display:flex;align-items:center;gap:12px;flex-wrap:wrap}
.sub-email-add{min-height:42px;padding:0 16px;border:1px dashed #d5deeb;border-radius:10px;background:#fff;color:#1e3a8a;font:inherit}
.sub-email-chip{display:inline-flex;align-items:center;gap:10px;min-height:42px;padding:0 14px;border:1px solid #dce3ef;border-radius:10px;background:#fff}
.sub-email-chip input{accent-color:#4f8df0}
.sub-contact-modal-backdrop{position:fixed;inset:0;background:rgba(33,39,52,.58);display:none;align-items:flex-start;justify-content:center;padding:42px 24px;z-index:95}
.sub-contact-modal-backdrop.is-visible{display:flex}
.sub-contact-modal{width:min(1280px,calc(100vw - 64px));background:#fff;border-radius:14px;box-shadow:0 28px 60px rgba(15,23,42,.24);overflow:hidden}
.sub-contact-head{display:flex;align-items:center;justify-content:space-between;padding:22px 26px;border-bottom:1px solid #e8edf4}
.sub-contact-head h2{margin:0;font-size:18px;font-weight:600}
.sub-contact-close{border:0;background:none;color:#ff4b4b;font-size:24px;cursor:pointer}
.sub-contact-body{display:grid;grid-template-columns:minmax(0,1fr) 300px;gap:28px;padding:26px}
.sub-contact-grid{display:grid;grid-template-columns:220px minmax(0,1fr);gap:16px 22px;align-items:start}
.sub-contact-grid label{padding-top:12px;color:#3b4558;font-size:15px}
.sub-contact-fields{display:grid;gap:14px}
.sub-contact-name-row,.sub-contact-other-row,.sub-contact-phone-row{display:grid;gap:14px}
.sub-contact-name-row{grid-template-columns:126px 1fr 1fr}
.sub-contact-other-row{grid-template-columns:1fr 1fr}
.sub-contact-phone-row{grid-template-columns:84px 1fr}
.sub-contact-suffix{display:flex;align-items:center;justify-content:center;border:1px solid #d7dfeb;border-right:0;border-radius:10px 0 0 10px;background:#f8fafc;color:#475569}
.sub-contact-phone-row .sub-control{border-radius:0 10px 10px 0}
.sub-contact-icon-input{display:grid;grid-template-columns:44px minmax(0,1fr)}
.sub-contact-icon-box{display:flex;align-items:center;justify-content:center;border:1px solid #d7dfeb;border-right:0;border-radius:10px 0 0 10px;background:#f8fafc;color:#0ea5e9;font-weight:700}
.sub-contact-icon-input .sub-control{border-radius:0 10px 10px 0}
.sub-contact-upload{border:1px dashed #d5deea;border-radius:12px;min-height:300px;padding:20px;display:grid;place-items:center;text-align:center;color:#64748b}
.sub-contact-upload i{font-size:28px;color:#4f8df0;margin-bottom:12px}
.sub-contact-upload strong{display:block;margin-bottom:8px;color:#334155;font-size:16px;font-weight:500}
.sub-contact-upload a{color:#111827;text-decoration:underline}
.sub-contact-upload-note{line-height:1.45}
.sub-contact-footer{display:flex;gap:8px;padding:16px 24px 28px;border-top:1px solid #eef2f7}
.sub-contact-footer .customer-btn{min-width:64px}
.sub-address-modal-backdrop{position:fixed;inset:0;background:rgba(33,39,52,.58);display:none;align-items:center;justify-content:center;padding:24px;z-index:94}
.sub-address-modal-backdrop.is-visible{display:flex}
.sub-address-modal{width:min(760px,calc(100vw - 60px));max-height:calc(100vh - 48px);background:#fff;border-radius:14px;box-shadow:0 28px 60px rgba(15,23,42,.24);overflow:auto}
.sub-address-modal-head{display:flex;align-items:center;justify-content:space-between;padding:18px 24px;border-bottom:1px solid #e8edf4}
.sub-address-modal-head h2{margin:0;font-size:18px;font-weight:500}
.sub-address-modal-close{border:0;background:none;color:#ff4b4b;font-size:22px;cursor:pointer}
.sub-address-modal-body{padding:22px 24px 18px;display:grid;gap:16px}
.sub-address-copy{display:inline-flex;align-items:center;gap:8px;color:#2563eb;text-decoration:none}
.sub-address-form-grid{display:grid;gap:14px}
.sub-address-form-grid label{color:#374151;font-size:15px}
.sub-address-two-col{display:grid;grid-template-columns:1fr 1fr;gap:18px}
.sub-address-three-col{display:grid;grid-template-columns:88px minmax(0,1fr) minmax(0,1fr);gap:12px}
.sub-address-note-line{color:#66758a;line-height:1.5}
.sub-address-modal-foot{display:flex;gap:10px;padding:18px 24px 28px;border-top:1px solid #eef2f7}
@media (max-height: 820px){
    .sub-address-modal-backdrop{align-items:flex-start}
}
@media (max-width:1100px){
    .sub-contact-body{grid-template-columns:1fr}
    .sub-contact-grid{grid-template-columns:1fr}
    .sub-contact-grid label{padding-top:0}
}
.sub-side-card{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px 12px;align-self:start;margin-top:12px;background:#4a4f6c}
.sub-side-card strong,.sub-side-card span{grid-column:1}
.sub-side-card i{grid-column:2;grid-row:1 / span 2;align-self:center;color:#fff}
.sub-mode-section,.sub-term-section,.sub-preferences{padding:0 24px}
.sub-mode-row{display:grid;grid-template-columns:190px minmax(0,1fr);gap:18px;padding:28px 0 26px;border-bottom:1px solid #edf2f7}
.sub-mode-tabs{display:flex;gap:14px;flex-wrap:wrap}
.sub-mode-tab{min-height:54px;padding:0 18px;border:1px solid #d9e2ef;border-radius:14px;background:#fff;color:#0f172a;font:inherit;font-size:16px;display:inline-flex;align-items:center;gap:10px;cursor:pointer}
.sub-mode-tab i{color:#94a3b8}
.sub-mode-tab.is-active{border-color:#4f8df0;color:#0f172a;box-shadow:0 0 0 1px rgba(79,141,240,.12) inset;background:#fbfdff}
.sub-mode-tab.is-active i{color:#4f8df0}
.sub-mode-panel{display:none;padding:26px 0 18px}
.sub-mode-panel.is-active{display:block}
.sub-product-picker{display:grid;gap:14px}
.sub-product-picker.is-hidden{display:none}
.sub-product-shell{max-width:720px}
.sub-product-shell.is-hidden{display:none}
.sub-product-summary{display:none;align-items:center;justify-content:space-between;gap:14px;max-width:720px;min-height:52px;padding:0 16px;border:1px solid #d9e2ef;border-radius:10px;background:#fff}
.sub-product-summary.is-visible{display:flex}
.sub-product-summary strong{font-size:16px;color:#0f172a}
.sub-product-summary button{border:0;background:none;color:#2563eb;font:inherit;font-weight:700;cursor:pointer}
.sub-product-select-input{min-height:44px;border-radius:8px}
.sub-empty-state{min-height:180px;border:1px solid #e6edf5;border-radius:10px;color:#334155;background:#fff}
.sub-empty-state p{margin:0;font-size:15px;color:#111827}
.sub-empty-state .customer-btn{margin-top:14px}
.sub-plan-list{border:1px solid #e6edf5;border-radius:12px;overflow:hidden}
.sub-plan-row{align-items:center}
.sub-plan-row.is-active{background:#eef5ff}
.sub-item-shell{gap:20px}
.sub-item-table-meta{display:flex;align-items:center;gap:26px;padding:10px 14px;border-top:1px solid #edf2f7;color:#64748b}
.sub-section-title{padding:18px 0 20px;border-top:1px solid #edf2f7;color:#334155;font-size:18px}
.sub-form-grid{display:grid;grid-template-columns:190px minmax(0,412px);gap:18px 36px;padding-bottom:18px;border-bottom:1px solid #edf2f7}
.sub-form-grid>label{padding-top:10px}
.sub-form-grid>label.is-required{color:#ef4444}
.sub-bill-row{display:grid;grid-template-columns:74px minmax(0,1fr);gap:14px}
.sub-bill-count{text-align:center}
.sub-expires-shell{display:grid;grid-template-columns:minmax(0,1fr) 76px}
.sub-expires-shell .sub-control{border-radius:10px 0 0 10px}
.sub-expires-shell span{min-height:44px;border:1px solid #d6dfeb;border-left:0;border-radius:0 10px 10px 0;display:flex;align-items:center;justify-content:center;background:#f8fafc;color:#334155}
.sub-check-inline{display:inline-flex;align-items:center;gap:10px;padding-top:8px;color:#0f172a}
.sub-check-inline input{accent-color:#4f8df0}
.sub-gateway-note{display:grid;gap:6px;color:#66758a;line-height:1.5}
.sub-gateway-note a{color:#2563eb;text-decoration:none}
.sub-gateway-logos{color:#1e3a8a}
.sub-pref-toggle{display:inline-flex;align-items:center;gap:12px;padding:18px 0 14px;border:0;background:none;color:#2563eb;font:inherit;font-size:17px;cursor:pointer}
.sub-pref-toggle i{transition:transform .15s ease}
.sub-pref-toggle[aria-expanded="true"] i{transform:rotate(90deg)}
.sub-pref-panel{padding:0 0 18px}
.sub-pref-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px 18px;margin-bottom:18px}
.sub-pref-notes{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}
.sub-field-stack{display:grid;gap:8px}
.sub-field-stack textarea{min-height:88px}
.sub-footer--sticky{position:sticky;bottom:0;z-index:10;display:flex;gap:10px;padding:18px 18px 20px;background:#fff;border-top:1px solid #e7edf4}
.sub-footer--sticky .customer-btn{min-width:96px}
@media (max-width:1180px){
    .sub-hero-grid{grid-template-columns:1fr}
    .sub-email-row,.sub-mode-row,.sub-form-grid{grid-template-columns:1fr}
    .sub-address-pair,.sub-pref-grid,.sub-pref-notes{grid-template-columns:1fr}
    .sub-hero-label,.sub-mode-label,.sub-form-grid>label,.sub-email-label{padding-top: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="sub-page sub-page--zoho">
            <form method="post" class="sub-card sub-form sub-form--zoho">
                <input type="hidden" name="action" value="save_subscription">
                <input type="hidden" name="subscription_mode" id="subscriptionMode" value="<?php echo billing_escape($subscriptionMode); ?>">
                <input type="hidden" name="invoice_template_name" value="<?php echo billing_escape((string) $form['invoice_template_name']); ?>">
                <input type="hidden" name="status_label" value="<?php echo billing_escape((string) $form['status_label']); ?>">

                <div class="sub-hero-head">
                    <h1><?php echo billing_escape($record ? 'Edit Subscription' : 'New Subscription'); ?></h1>
                </div>
                <?php if ($errors !== []): ?>
                    <div class="customer-error-banner"><span><?php echo billing_escape(implode(' ', $errors)); ?></span></div>
                <?php endif; ?>

                <section class="sub-hero">
                    <div class="sub-hero-grid">
                        <div class="sub-hero-label">Customer Name*</div>
                        <div class="sub-hero-main">
                            <div class="sub-hero-picker-row">
                                <div class="sub-picker sub-picker--hero">
                                    <button class="sub-control sub-picker-display" type="button" id="customerPickerToggle">
                                        <span id="customerPickerLabel"><?php echo $selectedCustomer ? billing_escape((string) $selectedCustomer['customer_name']) : 'Select or add a customer'; ?></span>
                                        <i class="fa-solid fa-angle-down"></i>
                                    </button>
                                    <div class="sub-picker-menu<?php echo $selectedCustomer ? ' is-hidden' : ''; ?>" id="customerPickerMenu">
                                        <input class="sub-control sub-picker-search" type="search" id="customerPickerSearch" placeholder="Search">
                                        <div id="customerPickerList">
                                            <?php foreach ($customers as $customer): ?>
                                                <a href="#" class="sub-picker-option<?php echo (int) $customer['id'] === (int) $form['customer_id'] ? ' is-active' : ''; ?>"
                                                   data-customer-id="<?php echo (int) $customer['id']; ?>"
                                                   data-customer-name="<?php echo billing_escape((string) $customer['customer_name']); ?>"
                                                   data-customer-email="<?php echo billing_escape((string) ($customer['email'] ?? '')); ?>"
                                                   data-billing-lines="<?php echo billing_escape(json_encode(billing_subscription_address_lines(billing_sales_customer_snapshot((int) $user['id'], (int) $organization['id'], (int) $customer['id']), 'billing'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?: '[]'); ?>"
                                                   data-shipping-lines="<?php echo billing_escape(json_encode(billing_subscription_address_lines(billing_sales_customer_snapshot((int) $user['id'], (int) $organization['id'], (int) $customer['id']), 'shipping'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?: '[]'); ?>"
                                                   data-unpaid-count="<?php echo (int) ($customerUnpaidMap[strtolower(trim((string) $customer['customer_name']))] ?? 0); ?>">
                                                    <span class="sub-picker-avatar"><?php echo billing_escape(strtoupper(substr((string) $customer['customer_name'], 0, 1))); ?></span>
                                                    <span class="sub-picker-meta">
                                                        <strong><?php echo billing_escape((string) $customer['customer_name']); ?></strong>
                                                        <span><?php echo billing_escape((string) ($customer['email'] ?? '')); ?></span>
                                                    </span>
                                                </a>
                                            <?php endforeach; ?>
                                        </div>
                                        <a href="#" class="sub-picker-create" id="openNewCustomerModal"><i class="fa-solid fa-circle-plus"></i> New Customer</a>
                                    </div>
                                    <input type="hidden" name="customer_id" id="customerIdField" value="<?php echo (int) $form['customer_id']; ?>">
                                    <input type="hidden" name="customer_name" id="customerNameField" value="<?php echo billing_escape((string) $form['customer_name']); ?>">
                                </div>
                                <button class="sub-search-btn" type="button" aria-label="Search"><i class="fa-solid fa-magnifying-glass"></i></button>
                                <div class="sub-currency-pill"><i class="fa-solid fa-circle-check"></i> INR</div>
                            </div>

                            <div class="sub-address-pair">
                                <div class="sub-address-card">
                                    <div class="sub-address-title">BILLING ADDRESS <button type="button" data-address-trigger="billing" aria-label="Edit billing address"><i class="fa-solid fa-pen"></i></button></div>
                                    <div class="sub-address-lines" id="subscriptionBillingAddress">
                                        <?php foreach (billing_subscription_address_lines($selectedCustomerSnapshot, 'billing') as $line): ?>
                                            <div><?php echo billing_escape($line); ?></div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <div class="sub-address-card">
                                    <div class="sub-address-title">SHIPPING ADDRESS <button type="button" data-address-trigger="shipping" aria-label="Edit shipping address"><i class="fa-solid fa-pen"></i></button></div>
                                    <div class="sub-address-lines" id="subscriptionShippingAddress">
                                        <?php foreach (billing_subscription_address_lines($selectedCustomerSnapshot, 'shipping') as $line): ?>
                                            <div><?php echo billing_escape($line); ?></div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>

                            <div class="sub-email-row">
                                <div class="sub-email-label">E-MAIL TO</div>
                                <div class="sub-email-actions">
                                    <button class="sub-email-add" type="button" id="openContactPersonModal"><i class="fa-solid fa-circle-plus"></i> New Contact Person</button>
                                    <label class="sub-email-chip<?php echo $selectedCustomer && !empty($selectedCustomer['email']) ? '' : ' is-hidden'; ?>" id="selectedCustomerEmailChip">
                                        <input type="checkbox" checked>
                                        <span id="selectedCustomerEmail"><?php echo billing_escape((string) ($selectedCustomer['email'] ?? '')); ?></span>
                                    </label>
                                </div>
                            </div>
                        </div>
                        <?php $unpaidCount = $selectedCustomer ? (int) ($customerUnpaidMap[strtolower(trim((string) $selectedCustomer['customer_name']))] ?? 0) : 0; ?>
                        <aside class="sub-side-card<?php echo $selectedCustomer ? '' : ' is-hidden'; ?>" id="selectedCustomerCard">
                            <strong id="selectedCustomerCardName"><?php echo $selectedCustomer ? billing_escape((string) $selectedCustomer['customer_name']) : ''; ?></strong>
                            <span id="selectedCustomerCardInvoice"><?php echo $unpaidCount > 0 ? $unpaidCount . ' Unpaid Invoices' : 'No unpaid invoices'; ?></span>
                            <i class="fa-solid fa-angle-right"></i>
                        </aside>
                    </div>
                </section>

                <section class="sub-mode-section">
                    <div class="sub-mode-row">
                        <div class="sub-mode-label">Create Subscription For</div>
                        <div class="sub-mode-tabs">
                            <button class="sub-mode-tab<?php echo $subscriptionMode === 'plans' ? ' is-active' : ''; ?>" type="button" data-subscription-mode="plans">
                                <i class="fa-regular fa-circle-dot"></i> Product (Plan &amp; Addons)
                            </button>
                            <button class="sub-mode-tab<?php echo $subscriptionMode === 'items' ? ' is-active' : ''; ?>" type="button" data-subscription-mode="items">
                                <i class="fa-regular fa-circle-dot"></i> Items
                            </button>
                        </div>
                    </div>

                    <div class="sub-mode-panel<?php echo $subscriptionMode === 'plans' ? ' is-active' : ''; ?>" id="subscriptionPlansPanel">
                        <div class="sub-product-picker<?php echo $selectedPlanId > 0 ? ' is-hidden' : ''; ?>" id="subscriptionProductPicker">
                            <div class="sub-product-shell" id="subscriptionProductShell">
                                <select class="sub-control sub-product-select-input" name="product_item_id" id="subscriptionProduct">
                                    <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>
                            </div>
                            <div class="sub-product-summary<?php echo $selectedProductId > 0 ? ' is-visible' : ''; ?>" id="subscriptionProductSummary">
                                <strong id="subscriptionProductSummaryLabel">
                                    <?php
                                    $selectedProductName = '';
                                    foreach ($products as $product) {
                                        if ((int) $product['id'] === $selectedProductId) {
                                            $selectedProductName = (string) $product['item_name'];
                                            break;
                                        }
                                    }
                                    echo billing_escape($selectedProductName);
                                    ?>
                                </strong>
                                <button type="button" id="subscriptionProductChange">Change Product</button>
                            </div>
                        </div>
                        <div id="subscriptionEmptyState" class="sub-empty-state<?php echo $selectedProductId > 0 && $selectedPlan ? ' is-hidden' : ''; ?>">
                            <div>
                                <p id="subscriptionEmptyText"><?php echo $selectedProductId > 0 ? "You haven't added any plans yet for this product." : 'Select a product to view plans for subscription.'; ?></p>
                                <a class="customer-btn customer-btn--green" href="plan_new.php<?php echo $selectedProductId > 0 ? '?product_id=' . $selectedProductId : ''; ?>" id="createPlanButton">Create a Plan</a>
                            </div>
                        </div>
                        <div class="sub-plan-list<?php echo $selectedProductId > 0 ? '' : ' is-hidden'; ?>" id="subscriptionPlanList">
                            <?php foreach ($plans as $plan): ?>
                                <label class="sub-plan-row<?php echo (int) $plan['product_item_id'] !== $selectedProductId ? ' is-hidden' : ''; ?><?php echo (int) $plan['id'] === $selectedPlanId ? ' is-active' : ''; ?>" data-product-id="<?php echo (int) $plan['product_item_id']; ?>">
                                    <span>
                                        <input type="radio" name="plan_id" value="<?php echo (int) $plan['id']; ?>" data-plan-name="<?php echo billing_escape((string) $plan['plan_name']); ?>" data-plan-frequency-value="<?php echo (int) ($plan['billing_frequency_value'] ?? 1); ?>" data-plan-frequency-unit="<?php echo billing_escape(strtolower((string) ($plan['billing_frequency_unit'] ?? 'week(s)'))); ?>" <?php echo (int) $plan['id'] === $selectedPlanId ? 'checked' : ''; ?> hidden>
                                        <strong><?php echo billing_escape((string) $plan['plan_name']); ?></strong>
                                        <span><?php echo billing_escape((string) ($plan['plan_description'] ?? 'No description')); ?></span>
                                    </span>
                                    <span class="sub-plan-price"><?php echo '&#8377;' . billing_escape(number_format((float) $plan['price'], 2)); ?></span>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <div class="sub-mode-panel<?php echo $subscriptionMode === 'items' ? ' is-active' : ''; ?>" id="subscriptionItemsPanel">
                        <div class="sales-item-shell sub-item-shell">
                            <div class="sales-items-card">
                                <div class="sales-items-head">
                                    <h2>Item Table</h2>
                                    <a class="sales-bulk-actions" href="#" onclick="return false;"><i class="fa-regular fa-circle-check"></i> Bulk Actions</a>
                                </div>
                                <table class="sales-items-table">
                                    <thead>
                                        <tr>
                                            <th style="width: 50%;">ITEM DETAILS</th>
                                            <th style="width: 17%;">QUANTITY</th>
                                            <th style="width: 17%;">PRICE</th>
                                            <th style="width: 16%;">AMOUNT</th>
                                        </tr>
                                    </thead>
                                    <tbody id="subscriptionItemsBody">
                                        <?php $subscriptionItems = $form['items'] !== [] ? $form['items'] : [['item_name' => '', 'item_description' => '', 'quantity' => 1, 'rate' => 0, 'unit_name' => '']]; ?>
                                        <?php foreach ($subscriptionItems as $item): ?>
                                            <?php $rowAmount = ((float) ($item['quantity'] ?? 0) * (float) ($item['rate'] ?? 0)); ?>
                                            <tr>
                                                <td>
                                                    <div class="sales-item-cell sales-item-cell--details">
                                                        <span class="sales-item-thumb"><i class="fa-regular fa-image"></i></span>
                                                        <div class="sales-field-stack sales-field-stack--spaced">
                                                            <input class="sales-form-control" type="text" name="item_name[]" list="subscriptionItemsList" value="<?php echo billing_escape((string) ($item['item_name'] ?? '')); ?>" placeholder="Type or click to select an item.">
                                                            <input class="sales-form-control" type="text" name="item_description[]" value="<?php echo billing_escape((string) ($item['item_description'] ?? '')); ?>" placeholder="Description">
                                                            <input type="hidden" name="unit_name[]" value="<?php echo billing_escape((string) ($item['unit_name'] ?? '')); ?>">
                                                        </div>
                                                    </div>
                                                </td>
                                                <td><div class="sales-item-cell"><input class="sales-form-control" type="number" step="0.01" min="0" name="quantity[]" value="<?php echo billing_escape((string) ($item['quantity'] ?? 1)); ?>"></div></td>
                                                <td><div class="sales-item-cell"><input class="sales-form-control" type="number" step="0.01" min="0" name="rate[]" value="<?php echo billing_escape((string) ($item['rate'] ?? 0)); ?>"></div></td>
                                                <td><div class="sales-item-cell sales-item-plain"><strong data-row-amount><?php echo billing_escape(number_format($rowAmount, 2)); ?></strong></div></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                                <div class="sub-item-table-meta">
                                    <span><i class="fa-solid fa-trash-can"></i> Select an account <i class="fa-solid fa-caret-down"></i></span>
                                    <span><i class="fa-solid fa-tag"></i> Reporting Tags <i class="fa-solid fa-caret-down"></i></span>
                                </div>
                            </div>
                            <div class="sales-item-actions">
                                <button class="sales-btn-light" type="button" id="subscriptionAddRow"><i class="fa-solid fa-circle-plus"></i> Add New Row <i class="fa-solid fa-caret-down"></i></button>
                                <button class="sales-btn-light" type="button"><i class="fa-solid fa-circle-plus"></i> Add Items in Bulk</button>
                            </div>
                            <datalist id="subscriptionItemsList">
                                <?php foreach ($products as $product): ?>
                                    <option value="<?php echo billing_escape((string) $product['item_name']); ?>"></option>
                                <?php endforeach; ?>
                            </datalist>
                        </div>
                    </div>
                </section>

                <section class="sub-term-section<?php echo $subscriptionMode === 'items' ? '' : ' is-hidden'; ?>" id="subscriptionTermSection">
                    <div class="sub-section-title">Subscription Term</div>
                    <div class="sub-form-grid">
                        <label class="is-required">Subscription Number*</label>
                        <input class="sub-control" type="text" name="subscription_number" value="<?php echo billing_escape((string) $form['subscription_number']); ?>">

                        <label class="is-required">Profile Name*</label>
                        <input class="sub-control" type="text" name="plan_name" id="selectedPlanName" value="<?php echo billing_escape((string) $form['plan_name']); ?>" <?php echo $subscriptionMode === 'plans' ? 'readonly' : ''; ?>>

                        <label class="is-required">Bill Every*</label>
                        <div class="sub-bill-row">
                            <input class="sub-control sub-bill-count" type="number" min="1" name="billing_frequency_value" id="billingFrequencyValue" value="<?php echo billing_escape((string) ($form['billing_frequency_value'] ?? 1)); ?>">
                            <select class="sub-control" name="billing_frequency_unit" id="billingFrequencyUnit">
                                <?php foreach ($billingFrequencyOptions as $value => $label): ?>
                                    <option value="<?php echo billing_escape($value); ?>" <?php echo strtolower((string) ($form['billing_frequency_unit'] ?? 'week(s)')) === $value ? 'selected' : ''; ?>><?php echo billing_escape($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <label>Start Date</label>
                        <input class="sub-control" type="date" name="start_date" value="<?php echo billing_escape((string) $form['start_date']); ?>">

                        <label>Expires After</label>
                        <div class="sub-expires-shell">
                            <input class="sub-control" type="number" min="1" name="expires_after_cycles" value="<?php echo billing_escape((string) $form['expires_after_cycles']); ?>" <?php echo !empty($form['renews_forever']) ? 'disabled' : ''; ?>>
                            <span>cycles</span>
                        </div>

                        <label></label>
                        <label class="sub-check-inline"><input type="checkbox" name="renews_forever" value="1" <?php echo !empty($form['renews_forever']) ? 'checked' : ''; ?>> Never Expires</label>

                        <label>Reference Number</label>
                        <input class="sub-control" type="text" name="reference_number" value="<?php echo billing_escape((string) $form['reference_number']); ?>">

                        <label>Salesperson</label>
                        <select class="sub-control" name="salesperson_name">
                            <option value="">Select a salesperson</option>
                            <?php foreach ($salespersonOptions as $option): ?>
                                <option value="<?php echo billing_escape($option); ?>" <?php echo (string) ($form['salesperson_name'] ?? '') === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                            <?php endforeach; ?>
                        </select>

                        <label>Associate Project(s)<br>Hours</label>
                        <select class="sub-control" name="project_name">
                            <option value="">Select a project</option>
                            <?php foreach ($subscriptionProjects as $project): ?>
                                <option value="<?php echo billing_escape((string) $project['project_name']); ?>"><?php echo billing_escape((string) $project['project_name']); ?></option>
                            <?php endforeach; ?>
                        </select>

                        <label>Payment Mode</label>
                        <label class="sub-check-inline"><input type="checkbox" name="payment_mode" value="offline" <?php echo (string) ($form['payment_mode'] ?? 'offline') === 'offline' ? 'checked' : ''; ?>> Collect payment offline</label>

                        <label>Payment Terms</label>
                        <select class="sub-control" name="payment_terms">
                            <?php foreach ($paymentTermOptions as $option): ?>
                                <option value="<?php echo billing_escape($option); ?>" <?php echo (string) ($form['payment_terms'] ?? 'Due on Receipt') === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                            <?php endforeach; ?>
                        </select>

                        <label>Want to get paid faster?</label>
                        <div class="sub-gateway-note">
                            <div><strong><span class="sub-gateway-logos">Mastercard Visa</span></strong></div>
                            <div>Configure payment gateways and receive payments online. <a href="#" onclick="return false;">Set up Payment Gateway</a></div>
                        </div>
                    </div>
                </section>

                <section class="sub-preferences<?php echo $subscriptionMode === 'items' ? '' : ' is-hidden'; ?>" id="subscriptionPreferencesSection">
                    <button class="sub-pref-toggle" type="button" id="subscriptionPreferencesToggle" aria-expanded="false">
                        <span>Other Preferences</span>
                        <i class="fa-solid fa-caret-right"></i>
                    </button>
                    <div class="sub-pref-panel is-hidden" id="subscriptionPreferencesPanel">
                        <div class="sub-pref-grid">
                            <label class="sub-check-card"><input type="checkbox" name="autocharge_enabled" value="1" <?php echo !empty($form['autocharge_enabled']) ? 'checked' : ''; ?>> <span>Enable autocharge</span></label>
                            <label class="sub-check-card"><input type="checkbox" name="prorate_enabled" value="1" <?php echo !empty($form['prorate_enabled']) ? 'checked' : ''; ?>> <span>Prorate charges and credits</span></label>
                            <label class="sub-check-card"><input type="checkbox" name="generate_invoice_on_prorate" value="1" <?php echo !empty($form['generate_invoice_on_prorate']) ? 'checked' : ''; ?>> <span>Generate invoices on prorate</span></label>
                        </div>
                        <div class="sub-pref-notes">
                            <div class="sub-field-stack">
                                <label>Customer Notes</label>
                                <textarea class="sub-control" name="customer_notes"><?php echo billing_escape((string) $form['customer_notes']); ?></textarea>
                            </div>
                            <div class="sub-field-stack">
                                <label>Terms &amp; Conditions</label>
                                <textarea class="sub-control" name="terms_text"><?php echo billing_escape((string) $form['terms_text']); ?></textarea>
                            </div>
                        </div>
                    </div>
                </section>

                <div class="sub-footer sub-footer--sticky<?php echo $showSaveFooter ? '' : ' is-hidden'; ?>" id="subscriptionFooter">
                    <button class="customer-btn customer-btn--green" type="submit">Save</button>
                    <a class="customer-btn" href="subscriptions.php">Cancel</a>
                </div>
            </form>
        </main>
    </div>
</div>

<div class="sub-address-modal-backdrop" id="addressModal" aria-hidden="true">
    <div class="sub-address-modal">
        <div class="sub-address-modal-head">
            <h2 id="addressModalTitle">Additional Address</h2>
            <button class="sub-address-modal-close" type="button" id="closeAddressModal" aria-label="Close"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <div class="sub-address-modal-body">
            <a href="#" class="sub-address-copy is-hidden" id="copyBillingToShipping"><i class="fa-solid fa-arrow-down"></i> Copy billing address</a>
            <div class="sub-address-form-grid">
                <div>
                    <label for="addressAttention">Attention</label>
                    <input class="sub-control" type="text" id="addressAttention">
                </div>
                <div>
                    <label for="addressCountry">Country/Region</label>
                    <select class="sub-control" id="addressCountry">
                        <option value="">Select</option>
                        <?php foreach ($countryOptions as $option): ?>
                            <option value="<?php echo billing_escape($option); ?>"><?php echo billing_escape($option); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label for="addressStreet1">Address</label>
                    <textarea class="sub-control" id="addressStreet1" placeholder="Street 1" style="min-height:68px"></textarea>
                </div>
                <div>
                    <textarea class="sub-control" id="addressStreet2" placeholder="Street 2" style="min-height:68px"></textarea>
                </div>
                <div>
                    <label for="addressCity">City</label>
                    <input class="sub-control" type="text" id="addressCity">
                </div>
                <div class="sub-address-two-col">
                    <div>
                        <label for="addressState">State</label>
                        <select class="sub-control" id="addressState">
                            <option value="">Select or type to add</option>
                            <?php foreach ($stateOptions as $option): ?>
                                <option value="<?php echo billing_escape($option); ?>"><?php echo billing_escape($option); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label for="addressPin">Pin Code</label>
                        <input class="sub-control" type="text" id="addressPin">
                    </div>
                </div>
                <div class="sub-address-two-col">
                    <div>
                        <label for="addressPhone">Phone</label>
                        <div class="sub-address-three-col">
                            <select class="sub-control" id="addressPhoneCountry">
                                <option value="+91">+91</option>
                            </select>
                            <input class="sub-control" type="text" id="addressPhone">
                            <div></div>
                        </div>
                    </div>
                    <div>
                        <label for="addressFax">Fax Number</label>
                        <input class="sub-control" type="text" id="addressFax">
                    </div>
                </div>
            </div>
            <div class="sub-address-note-line"><strong>Note:</strong> Changes made here will be updated for this customer.</div>
        </div>
        <div class="sub-address-modal-foot">
            <button class="customer-btn customer-btn--green" type="button" id="saveAddressModal">Save</button>
            <button class="customer-btn" type="button" id="cancelAddressModal">Cancel</button>
        </div>
    </div>
</div>

<div class="sub-contact-modal-backdrop" id="contactPersonModal" aria-hidden="true">
    <div class="sub-contact-modal">
        <div class="sub-contact-head">
            <h2>Add Contact Person</h2>
            <button class="sub-contact-close" type="button" id="closeContactPersonModal" aria-label="Close"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <div class="sub-contact-body">
            <div class="sub-contact-grid">
                <label>Name</label>
                <div class="sub-contact-fields">
                    <div class="sub-contact-name-row">
                        <select class="sub-control" id="contactSalutation">
                            <option value="">Salutation</option>
                            <option value="Mr.">Mr.</option>
                            <option value="Ms.">Ms.</option>
                            <option value="Mrs.">Mrs.</option>
                            <option value="Dr.">Dr.</option>
                        </select>
                        <input class="sub-control" type="text" id="contactFirstName" placeholder="First Name">
                        <input class="sub-control" type="text" id="contactLastName" placeholder="Last Name">
                    </div>
                </div>

                <label>Email Address</label>
                <div class="sub-contact-fields">
                    <input class="sub-control" type="email" id="contactEmail">
                </div>

                <label>Phone</label>
                <div class="sub-contact-fields">
                    <div class="sub-contact-phone-row">
                        <select class="sub-control" id="contactWorkCountry">
                            <option value="+91">+91</option>
                        </select>
                        <input class="sub-control" type="text" id="contactWorkPhone" placeholder="Work Phone">
                    </div>
                    <div class="sub-contact-phone-row">
                        <select class="sub-control" id="contactMobileCountry">
                            <option value="+91">+91</option>
                        </select>
                        <input class="sub-control" type="text" id="contactMobile" placeholder="Mobile">
                    </div>
                </div>

                <label>Skype Name/Number</label>
                <div class="sub-contact-fields">
                    <div class="sub-contact-icon-input">
                        <div class="sub-contact-icon-box"><i class="fa-brands fa-skype"></i></div>
                        <input class="sub-control" type="text" id="contactSkype" placeholder="Skype Name/Number">
                    </div>
                </div>

                <label>Other Details</label>
                <div class="sub-contact-fields">
                    <div class="sub-contact-other-row">
                        <input class="sub-control" type="text" id="contactDesignation" placeholder="Designation">
                        <input class="sub-control" type="text" id="contactDepartment" placeholder="Department">
                    </div>
                </div>
            </div>

            <div class="sub-contact-upload">
                <div>
                    <i class="fa-solid fa-circle-arrow-up"></i>
                    <strong>Drag &amp; Drop Profile Image</strong>
                    <div class="sub-contact-upload-note">Supported Files: jpg, jpeg, png, gif, bmp</div>
                    <div class="sub-contact-upload-note">Maximum File Size: 5MB</div>
                    <div style="margin-top:22px;"><a href="#" id="contactUploadLink">Upload File</a></div>
                    <input type="file" id="contactProfileImage" accept=".jpg,.jpeg,.png,.gif,.bmp" hidden>
                </div>
            </div>
        </div>
        <div class="sub-contact-footer">
            <button class="customer-btn customer-btn--green" type="button" id="saveContactPerson">Save</button>
            <button class="customer-btn" type="button" id="cancelContactPerson">Cancel</button>
        </div>
    </div>
</div>

<?php if ($showCustomerModal): ?>
<div class="sub-modal-backdrop" id="newCustomerModal">
    <div class="sub-modal">
        <form method="post" enctype="multipart/form-data">
            <input type="hidden" name="action" value="create_inline_customer">
            <div class="sub-modal-head">
                <h2>New Customer</h2>
                <button class="sub-modal-close" type="button" id="closeCustomerModal"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <?php if ($modalErrors !== []): ?>
                <div class="customer-error-banner" style="margin:16px 24px 0;"><span><?php echo billing_escape(implode(' ', $modalErrors)); ?></span></div>
            <?php endif; ?>

            <div class="sub-customer-grid">
                <label>Customer Type <i class="fa-solid fa-circle-info customer-label-hint"></i></label>
                <div class="sub-radio-row">
                    <label><input type="radio" name="customer_type" value="Business" <?php echo $modalCustomer['customer_type'] === 'Business' ? 'checked' : ''; ?>> Business</label>
                    <label><input type="radio" name="customer_type" value="Individual" <?php echo $modalCustomer['customer_type'] === 'Individual' ? 'checked' : ''; ?>> Individual</label>
                </div>

                <label>Primary Contact <i class="fa-solid fa-circle-info customer-label-hint"></i></label>
                <div class="sub-three-col">
                    <select class="sub-control" name="salutation">
                        <option value="">Salutation</option>
                        <?php foreach ($salutationOptions as $option): ?>
                            <option value="<?php echo billing_escape($option); ?>" <?php echo $modalCustomer['salutation'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <input class="sub-control" type="text" name="first_name" placeholder="First Name" value="<?php echo billing_escape($modalCustomer['first_name']); ?>">
                    <input class="sub-control" type="text" name="last_name" placeholder="Last Name" value="<?php echo billing_escape($modalCustomer['last_name']); ?>">
                </div>

                <label>Company Name</label>
                <input class="sub-control" type="text" name="company_name" value="<?php echo billing_escape($modalCustomer['company_name']); ?>">

                <label class="is-required">Display Name* <i class="fa-solid fa-circle-info customer-label-hint"></i></label>
                <div>
                    <input class="sub-control" type="text" name="display_name" placeholder="Select or type to add" value="<?php echo billing_escape($modalCustomer['display_name']); ?>">
                    <?php if (isset($modalErrors['display_name'])): ?><div class="field-error"><?php echo billing_escape($modalErrors['display_name']); ?></div><?php endif; ?>
                </div>

                <label>Email Address <i class="fa-solid fa-circle-info customer-label-hint"></i></label>
                <div class="customer-prefix-field">
                    <span><i class="fa-regular fa-envelope"></i></span>
                    <input type="email" name="email" value="<?php echo billing_escape($modalCustomer['email']); ?>">
                </div>

                <label>Phone <i class="fa-solid fa-circle-info customer-label-hint"></i></label>
                <div class="sub-phone-row">
                    <div class="sub-phone-box"><span>+91</span><input class="sub-control" type="text" name="work_phone" placeholder="Work Phone" value="<?php echo billing_escape($modalCustomer['work_phone']); ?>"></div>
                    <div class="sub-phone-box"><span>+91</span><input class="sub-control" type="text" name="mobile" placeholder="Mobile" value="<?php echo billing_escape($modalCustomer['mobile']); ?>"></div>
                </div>

                <label>Customer Language <i class="fa-solid fa-circle-info customer-label-hint"></i></label>
                <select class="sub-control" name="customer_language">
                    <option value="English" <?php echo $modalCustomer['customer_language'] === 'English' ? 'selected' : ''; ?>>English</option>
                </select>
            </div>

            <div class="sub-tabs">
                <button class="is-active" type="button" data-customer-tab="other">Other Details</button>
                <button type="button" data-customer-tab="address">Address</button>
                <button type="button" data-customer-tab="custom">Custom Fields</button>
                <button type="button" data-customer-tab="reporting">Reporting Tags</button>
                <button type="button" data-customer-tab="remarks">Remarks</button>
            </div>

            <section class="sub-tab-panel is-active" data-customer-panel="other">
                <div class="sub-customer-grid" style="padding:0">
                    <label>PAN <i class="fa-solid fa-circle-info customer-label-hint"></i></label>
                    <input class="sub-control" type="text" name="pan" value="<?php echo billing_escape($modalCustomer['pan']); ?>">

                    <label>Currency</label>
                    <select class="sub-control" name="currency">
                        <option value="INR- Indian Rupee" <?php echo $modalCustomer['currency'] === 'INR- Indian Rupee' ? 'selected' : ''; ?>>INR- Indian Rupee</option>
                    </select>

                    <label>Payment Terms</label>
                    <select class="sub-control" name="payment_terms">
                        <option value="Due on Receipt" <?php echo $modalCustomer['payment_terms'] === 'Due on Receipt' ? 'selected' : ''; ?>>Due on Receipt</option>
                    </select>

                    <label>Enable Portal? <i class="fa-solid fa-circle-info customer-label-hint"></i></label>
                    <label class="checkbox-row"><input type="checkbox" name="enable_portal" value="1" <?php echo $modalCustomer['enable_portal'] === '1' ? 'checked' : ''; ?>> Allow portal access for this customer</label>

                    <label>Documents</label>
                    <div>
                        <input type="file" name="customer_documents[]" id="inlineCustomerDocuments" accept="image/*,.pdf,.doc,.docx,.xls,.xlsx" multiple hidden>
                        <button class="upload-btn" type="button" data-file-trigger="inlineCustomerDocuments"><i class="fa-solid fa-arrow-up-from-bracket"></i> Upload File <i class="fa-solid fa-angle-down"></i></button>
                        <div class="helper-text">You can upload a maximum of 10 files, 10MB each</div>
                        <div class="helper-text" id="inlineCustomerDocumentsList"></div>
                    </div>
                </div>
                <a class="customer-add-more" href="#" style="margin-left:24px">Add more details</a>
            </section>

            <section class="sub-tab-panel" data-customer-panel="address">
                <div class="sub-address-grid">
                    <div class="sub-address-col">
                        <h3>Billing Address</h3>
                        <div class="sub-customer-grid" style="padding:0;grid-template-columns:140px minmax(0,1fr);">
                            <label>Attention</label><input class="sub-control" type="text" name="billing_attention" value="<?php echo billing_escape($modalCustomer['billing_attention']); ?>">
                            <label>Country/Region</label>
                            <select class="sub-control" name="billing_country">
                                <option value="">Select</option>
                                <?php foreach ($countryOptions as $option): ?><option value="<?php echo billing_escape($option); ?>" <?php echo $modalCustomer['billing_country'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option><?php endforeach; ?>
                            </select>
                            <label>Address</label><textarea class="sub-control" name="billing_address_1" placeholder="Street 1" style="min-height:68px"><?php echo billing_escape($modalCustomer['billing_address_1']); ?></textarea>
                            <label></label><textarea class="sub-control" name="billing_address_2" placeholder="Street 2" style="min-height:68px"><?php echo billing_escape($modalCustomer['billing_address_2']); ?></textarea>
                            <label>City</label><input class="sub-control" type="text" name="billing_city" value="<?php echo billing_escape($modalCustomer['billing_city']); ?>">
                            <label>State</label>
                            <select class="sub-control" name="billing_state">
                                <option value="">Select or type to add</option>
                                <?php foreach ($stateOptions as $option): ?><option value="<?php echo billing_escape($option); ?>" <?php echo $modalCustomer['billing_state'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option><?php endforeach; ?>
                            </select>
                            <label>Pin Code</label><input class="sub-control" type="text" name="billing_pin" value="<?php echo billing_escape($modalCustomer['billing_pin']); ?>">
                            <label>Phone</label><div class="sub-phone-box"><span>+91</span><input class="sub-control" type="text" name="billing_phone" value="<?php echo billing_escape($modalCustomer['billing_phone']); ?>"></div>
                            <label>Fax Number</label><input class="sub-control" type="text" name="billing_fax" value="<?php echo billing_escape($modalCustomer['billing_fax']); ?>">
                        </div>
                    </div>
                    <div class="sub-address-col">
                        <h3>Shipping Address ( <a href="#" data-copy-billing-address><i class="fa-solid fa-arrow-down"></i> Copy billing address</a> )</h3>
                        <div class="sub-customer-grid" style="padding:0;grid-template-columns:140px minmax(0,1fr);">
                            <label>Attention</label><input class="sub-control" type="text" name="shipping_attention" value="<?php echo billing_escape($modalCustomer['shipping_attention']); ?>">
                            <label>Country/Region</label>
                            <select class="sub-control" name="shipping_country">
                                <option value="">Select</option>
                                <?php foreach ($countryOptions as $option): ?><option value="<?php echo billing_escape($option); ?>" <?php echo $modalCustomer['shipping_country'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option><?php endforeach; ?>
                            </select>
                            <label>Address</label><textarea class="sub-control" name="shipping_address_1" placeholder="Street 1" style="min-height:68px"><?php echo billing_escape($modalCustomer['shipping_address_1']); ?></textarea>
                            <label></label><textarea class="sub-control" name="shipping_address_2" placeholder="Street 2" style="min-height:68px"><?php echo billing_escape($modalCustomer['shipping_address_2']); ?></textarea>
                            <label>City</label><input class="sub-control" type="text" name="shipping_city" value="<?php echo billing_escape($modalCustomer['shipping_city']); ?>">
                            <label>State</label>
                            <select class="sub-control" name="shipping_state">
                                <option value="">Select or type to add</option>
                                <?php foreach ($stateOptions as $option): ?><option value="<?php echo billing_escape($option); ?>" <?php echo $modalCustomer['shipping_state'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option><?php endforeach; ?>
                            </select>
                            <label>Pin Code</label><input class="sub-control" type="text" name="shipping_pin" value="<?php echo billing_escape($modalCustomer['shipping_pin']); ?>">
                            <label>Phone</label><div class="sub-phone-box"><span>+91</span><input class="sub-control" type="text" name="shipping_phone" value="<?php echo billing_escape($modalCustomer['shipping_phone']); ?>"></div>
                            <label>Fax Number</label><input class="sub-control" type="text" name="shipping_fax" value="<?php echo billing_escape($modalCustomer['shipping_fax']); ?>">
                        </div>
                    </div>
                </div>
                <div class="sub-address-note">
                    <strong>Note:</strong>
                    <div>Add and manage additional addresses from this Customers details section.</div>
                    <div>You can customise how customers' addresses are displayed in transaction PDFs. To do this, go to Settings &gt; Preferences &gt; Customers, and navigate to the Address Format sections.</div>
                </div>
            </section>

            <section class="sub-tab-panel sub-empty-panel" data-customer-panel="custom">
                <p>Start adding custom fields for your Customers by going to <em>Settings âž¡ Preferences âž¡ Customers</em>. You can also refine the address format of your Customers from there.</p>
            </section>

            <section class="sub-tab-panel sub-empty-panel" data-customer-panel="reporting">
                <p>You've not created any Reporting Tags.<br>Start creating reporting tags by going to <em>More Settings âž¡ Reporting Tags</em></p>
            </section>

            <section class="sub-tab-panel" data-customer-panel="remarks">
                <label class="remarks-label">Remarks <span>(For Internal Use)</span></label>
                <textarea name="remarks" class="sub-remarks-box"><?php echo billing_escape($modalCustomer['remarks']); ?></textarea>
            </section>

            <div class="sub-modal-foot">
                <button class="customer-btn customer-btn--green" type="submit">Save</button>
                <button class="customer-btn" type="button" id="cancelCustomerModal">Cancel</button>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<script src="assets/billing.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    var pickerToggle = document.getElementById('customerPickerToggle');
    var pickerMenu = document.getElementById('customerPickerMenu');
    var pickerSearch = document.getElementById('customerPickerSearch');
    var pickerLabel = document.getElementById('customerPickerLabel');
    var customerIdField = document.getElementById('customerIdField');
    var customerNameField = document.getElementById('customerNameField');
    var customerCard = document.getElementById('selectedCustomerCard');
    var customerCardName = document.getElementById('selectedCustomerCardName');
    var customerCardInvoice = document.getElementById('selectedCustomerCardInvoice');
    var customerEmailChip = document.getElementById('selectedCustomerEmailChip');
    var customerEmail = document.getElementById('selectedCustomerEmail');
    var billingAddress = document.getElementById('subscriptionBillingAddress');
    var shippingAddress = document.getElementById('subscriptionShippingAddress');
    var addressModal = document.getElementById('addressModal');
    var addressModalTitle = document.getElementById('addressModalTitle');
    var closeAddressModal = document.getElementById('closeAddressModal');
    var cancelAddressModal = document.getElementById('cancelAddressModal');
    var saveAddressModal = document.getElementById('saveAddressModal');
    var copyBillingToShipping = document.getElementById('copyBillingToShipping');
    var addressAttention = document.getElementById('addressAttention');
    var addressCountry = document.getElementById('addressCountry');
    var addressStreet1 = document.getElementById('addressStreet1');
    var addressStreet2 = document.getElementById('addressStreet2');
    var addressCity = document.getElementById('addressCity');
    var addressState = document.getElementById('addressState');
    var addressPin = document.getElementById('addressPin');
    var addressPhone = document.getElementById('addressPhone');
    var addressFax = document.getElementById('addressFax');
    var productSelect = document.getElementById('subscriptionProduct');
    var productPicker = document.getElementById('subscriptionProductPicker');
    var productShell = document.getElementById('subscriptionProductShell');
    var productSummary = document.getElementById('subscriptionProductSummary');
    var productSummaryLabel = document.getElementById('subscriptionProductSummaryLabel');
    var productChangeButton = document.getElementById('subscriptionProductChange');
    var planRows = Array.from(document.querySelectorAll('.sub-plan-row'));
    var emptyState = document.getElementById('subscriptionEmptyState');
    var emptyText = document.getElementById('subscriptionEmptyText');
    var planList = document.getElementById('subscriptionPlanList');
    var createPlanButton = document.getElementById('createPlanButton');
    var selectedPlanName = document.getElementById('selectedPlanName');
    var subscriptionMode = document.getElementById('subscriptionMode');
    var modeButtons = Array.from(document.querySelectorAll('[data-subscription-mode]'));
    var plansPanel = document.getElementById('subscriptionPlansPanel');
    var itemsPanel = document.getElementById('subscriptionItemsPanel');
    var billingFrequencyValue = document.getElementById('billingFrequencyValue');
    var billingFrequencyUnit = document.getElementById('billingFrequencyUnit');
    var renewsForever = document.querySelector('input[name="renews_forever"]');
    var expiresField = document.querySelector('input[name="expires_after_cycles"]');
    var preferencesToggle = document.getElementById('subscriptionPreferencesToggle');
    var preferencesPanel = document.getElementById('subscriptionPreferencesPanel');
    var preferencesSection = document.getElementById('subscriptionPreferencesSection');
    var termSection = document.getElementById('subscriptionTermSection');
    var subscriptionFooter = document.getElementById('subscriptionFooter');
    var itemsBody = document.getElementById('subscriptionItemsBody');
    var addRowButton = document.getElementById('subscriptionAddRow');
    var openContactPersonModal = document.getElementById('openContactPersonModal');
    var contactPersonModal = document.getElementById('contactPersonModal');
    var closeContactPersonModal = document.getElementById('closeContactPersonModal');
    var cancelContactPerson = document.getElementById('cancelContactPerson');
    var saveContactPerson = document.getElementById('saveContactPerson');
    var contactUploadLink = document.getElementById('contactUploadLink');
    var contactProfileImage = document.getElementById('contactProfileImage');
    var contactSalutation = document.getElementById('contactSalutation');
    var contactFirstName = document.getElementById('contactFirstName');
    var contactLastName = document.getElementById('contactLastName');
    var contactEmail = document.getElementById('contactEmail');
    var contactWorkPhone = document.getElementById('contactWorkPhone');
    var contactMobile = document.getElementById('contactMobile');
    var contactSkype = document.getElementById('contactSkype');
    var contactDesignation = document.getElementById('contactDesignation');
    var contactDepartment = document.getElementById('contactDepartment');
    var currentAddressType = 'billing';
    var addressStateData = {
        billing: {
            attention: <?php echo json_encode((string) ($selectedCustomerSnapshot['billing']['attention'] ?? ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>,
            country: <?php echo json_encode((string) ($selectedCustomerSnapshot['billing']['country'] ?? ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>,
            address1: <?php echo json_encode((string) ($selectedCustomerSnapshot['billing']['address_1'] ?? ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>,
            address2: <?php echo json_encode((string) ($selectedCustomerSnapshot['billing']['address_2'] ?? ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>,
            city: <?php echo json_encode((string) ($selectedCustomerSnapshot['billing']['city'] ?? ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>,
            state: <?php echo json_encode((string) ($selectedCustomerSnapshot['billing']['state'] ?? ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>,
            pin: <?php echo json_encode((string) ($selectedCustomerSnapshot['billing']['pin'] ?? ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>,
            phone: <?php echo json_encode((string) ($selectedCustomerSnapshot['billing']['phone'] ?? ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>,
            fax: ''
        },
        shipping: {
            attention: <?php echo json_encode((string) ($selectedCustomerSnapshot['shipping']['attention'] ?? ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>,
            country: <?php echo json_encode((string) ($selectedCustomerSnapshot['shipping']['country'] ?? ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>,
            address1: <?php echo json_encode((string) ($selectedCustomerSnapshot['shipping']['address_1'] ?? ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>,
            address2: <?php echo json_encode((string) ($selectedCustomerSnapshot['shipping']['address_2'] ?? ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>,
            city: <?php echo json_encode((string) ($selectedCustomerSnapshot['shipping']['city'] ?? ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>,
            state: <?php echo json_encode((string) ($selectedCustomerSnapshot['shipping']['state'] ?? ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>,
            pin: <?php echo json_encode((string) ($selectedCustomerSnapshot['shipping']['pin'] ?? ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>,
            phone: <?php echo json_encode((string) ($selectedCustomerSnapshot['shipping']['phone'] ?? ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>,
            fax: ''
        }
    };

    function renderLines(container, lines) {
        if (!container) {
            return;
        }
        container.innerHTML = '';
        (lines || []).forEach(function (line) {
            var row = document.createElement('div');
            row.textContent = line;
            container.appendChild(row);
        });
    }

    function addressDataToLines(data) {
        var lines = [];
        ['attention', 'address1', 'address2', 'city', 'state', 'pin', 'country'].forEach(function (key) {
            var value = (data[key] || '').trim();
            if (value !== '') {
                lines.push(value);
            }
        });
        if ((data.phone || '').trim() !== '') {
            lines.push('Phone: ' + data.phone.trim());
        }
        return lines;
    }

    function hydrateAddressModal(type) {
        currentAddressType = type;
        var data = addressStateData[type] || {};
        if (addressModalTitle) {
            addressModalTitle.textContent = type === 'billing' ? 'Additional Address' : 'Additional Address';
        }
        if (copyBillingToShipping) {
            copyBillingToShipping.classList.toggle('is-hidden', type !== 'shipping');
        }
        if (addressAttention) addressAttention.value = data.attention || '';
        if (addressCountry) addressCountry.value = data.country || '';
        if (addressStreet1) addressStreet1.value = data.address1 || '';
        if (addressStreet2) addressStreet2.value = data.address2 || '';
        if (addressCity) addressCity.value = data.city || '';
        if (addressState) addressState.value = data.state || '';
        if (addressPin) addressPin.value = data.pin || '';
        if (addressPhone) addressPhone.value = data.phone || '';
        if (addressFax) addressFax.value = data.fax || '';
    }

    function openAddressEditor(type) {
        if (!addressModal) {
            return;
        }
        hydrateAddressModal(type);
        addressModal.classList.add('is-visible');
        addressModal.setAttribute('aria-hidden', 'false');
        if (addressAttention) {
            addressAttention.focus();
        }
    }

    function closeAddressEditor() {
        if (!addressModal) {
            return;
        }
        addressModal.classList.remove('is-visible');
        addressModal.setAttribute('aria-hidden', 'true');
    }

    function parseLines(value) {
        try {
            return JSON.parse(value || '[]');
        } catch (error) {
            return [];
        }
    }

    function updateModeUi() {
        var mode = subscriptionMode ? subscriptionMode.value : 'plans';
        var showSaveFooter = mode === 'items' || (mode === 'plans' && hasSelectedPlan());
        modeButtons.forEach(function (button) {
            button.classList.toggle('is-active', button.getAttribute('data-subscription-mode') === mode);
        });
        if (plansPanel) {
            plansPanel.classList.toggle('is-active', mode === 'plans');
        }
        if (itemsPanel) {
            itemsPanel.classList.toggle('is-active', mode === 'items');
        }
        if (selectedPlanName) {
            selectedPlanName.readOnly = mode === 'plans';
        }
        if (termSection) {
            termSection.classList.toggle('is-hidden', mode !== 'items');
        }
        if (preferencesSection) {
            preferencesSection.classList.toggle('is-hidden', mode !== 'items');
        }
        if (subscriptionFooter) {
            subscriptionFooter.classList.toggle('is-hidden', !showSaveFooter);
        }
        syncProductPickerVisibility();
    }

    function resetContactPersonForm() {
        [contactSalutation, contactFirstName, contactLastName, contactEmail, contactWorkPhone, contactMobile, contactSkype, contactDesignation, contactDepartment].forEach(function (field) {
            if (field) {
                field.value = '';
            }
        });
        if (contactProfileImage) {
            contactProfileImage.value = '';
        }
    }

    function openContactModal() {
        if (!contactPersonModal) {
            return;
        }
        contactPersonModal.classList.add('is-visible');
        contactPersonModal.setAttribute('aria-hidden', 'false');
        if (contactFirstName) {
            contactFirstName.focus();
        }
    }

    function closeContactModal() {
        if (!contactPersonModal) {
            return;
        }
        contactPersonModal.classList.remove('is-visible');
        contactPersonModal.setAttribute('aria-hidden', 'true');
    }

    function createEmailChip(emailValue, checked) {
        var chip = document.createElement('label');
        chip.className = 'sub-email-chip';
        chip.innerHTML = '<input type="checkbox"' + (checked ? ' checked' : '') + '><span></span>';
        chip.querySelector('span').textContent = emailValue;
        return chip;
    }

    function syncProductSummary() {
        if (!productSelect || !productSummary || !productShell || !productSummaryLabel) {
            return;
        }
        var hasProduct = productSelect.value !== '';
        var option = productSelect.options[productSelect.selectedIndex];
        productSummaryLabel.textContent = hasProduct && option ? option.textContent.trim() : '';
        productSummary.classList.toggle('is-visible', hasProduct);
        productShell.classList.toggle('is-hidden', hasProduct);
    }

    function hasSelectedPlan() {
        return planRows.some(function (row) {
            var radio = row.querySelector('input[type="radio"]');
            return !!(radio && radio.checked);
        });
    }

    function syncProductPickerVisibility() {
        if (!productPicker || !subscriptionMode) {
            return;
        }
        var shouldHide = subscriptionMode.value === 'plans' && hasSelectedPlan();
        productPicker.classList.toggle('is-hidden', shouldHide);
    }

    if (pickerToggle && pickerMenu) {
        pickerToggle.addEventListener('click', function () {
            pickerMenu.classList.toggle('is-hidden');
            if (!pickerMenu.classList.contains('is-hidden') && pickerSearch) {
                pickerSearch.focus();
            }
        });
    }

    document.querySelectorAll('.sub-search-btn').forEach(function (button) {
        button.addEventListener('click', function () {
            if (!pickerMenu) {
                return;
            }
            pickerMenu.classList.remove('is-hidden');
            if (pickerSearch) {
                pickerSearch.focus();
            }
        });
    });

    if (pickerSearch) {
        pickerSearch.addEventListener('input', function () {
            var query = pickerSearch.value.trim().toLowerCase();
            document.querySelectorAll('.sub-picker-option').forEach(function (option) {
                var text = ((option.getAttribute('data-customer-name') || '') + ' ' + (option.getAttribute('data-customer-email') || '')).toLowerCase();
                option.classList.toggle('is-hidden', query !== '' && text.indexOf(query) === -1);
            });
        });
    }

    document.querySelectorAll('.sub-picker-option').forEach(function (option) {
        option.addEventListener('click', function (event) {
            event.preventDefault();
            customerIdField.value = option.getAttribute('data-customer-id') || '';
            customerNameField.value = option.getAttribute('data-customer-name') || '';
            pickerLabel.textContent = option.getAttribute('data-customer-name') || 'Select or add a customer';
            if (customerCard) {
                customerCard.classList.remove('is-hidden');
                if (customerCardName) customerCardName.textContent = option.getAttribute('data-customer-name') || '';
                if (customerCardInvoice) {
                    var unpaidCount = parseInt(option.getAttribute('data-unpaid-count') || '0', 10);
                    customerCardInvoice.textContent = unpaidCount > 0 ? unpaidCount + ' Unpaid Invoices' : 'No unpaid invoices';
                }
            }
            if (customerEmailChip && customerEmail) {
                var emailValue = option.getAttribute('data-customer-email') || '';
                customerEmail.textContent = emailValue;
                customerEmailChip.classList.toggle('is-hidden', emailValue === '');
            }
            renderLines(billingAddress, parseLines(option.getAttribute('data-billing-lines')));
            renderLines(shippingAddress, parseLines(option.getAttribute('data-shipping-lines')));
            addressStateData.billing = { attention: '', country: '', address1: '', address2: '', city: '', state: '', pin: '', phone: '', fax: '' };
            addressStateData.shipping = { attention: '', country: '', address1: '', address2: '', city: '', state: '', pin: '', phone: '', fax: '' };
            document.querySelectorAll('.sub-picker-option').forEach(function (row) {
                row.classList.toggle('is-active', row === option);
            });
            pickerMenu.classList.add('is-hidden');
        });
    });

    function syncPlanRows() {
        if (!productSelect) {
            return;
        }
        var productId = productSelect.value;
        var visibleCount = 0;
        planRows.forEach(function (row) {
            var show = productId !== '' && row.getAttribute('data-product-id') === productId;
            row.classList.toggle('is-hidden', !show);
            if (show) visibleCount += 1;
            if (!show) {
                var input = row.querySelector('input[type="radio"]');
                if (input) input.checked = false;
                row.classList.remove('is-active');
            }
        });
        if (planList) {
            planList.classList.toggle('is-hidden', productId === '');
        }
        if (emptyState) {
            emptyState.classList.toggle('is-hidden', productId !== '' && visibleCount > 0);
        }
        if (emptyText) {
            emptyText.textContent = productId === '' ? 'Select a product to view plans for subscription.' : "You haven't added any plans yet for this product.";
        }
        if (createPlanButton) {
            createPlanButton.href = productId !== '' ? 'plan_new.php?product_id=' + productId : 'plan_new.php';
        }
        if (visibleCount === 0 && selectedPlanName) {
            selectedPlanName.value = '';
        }
        syncProductPickerVisibility();
    }

    planRows.forEach(function (row) {
        row.addEventListener('click', function () {
            var radio = row.querySelector('input[type="radio"]');
            if (!radio) return;
            radio.checked = true;
            planRows.forEach(function (other) {
                other.classList.toggle('is-active', other === row);
            });
            if (selectedPlanName) {
                selectedPlanName.value = radio.getAttribute('data-plan-name') || '';
            }
            if (billingFrequencyValue) {
                billingFrequencyValue.value = radio.getAttribute('data-plan-frequency-value') || '1';
            }
            if (billingFrequencyUnit) {
                billingFrequencyUnit.value = radio.getAttribute('data-plan-frequency-unit') || 'week(s)';
            }
            syncProductPickerVisibility();
        });
    });

    if (productSelect) {
        productSelect.addEventListener('change', syncPlanRows);
        productSelect.addEventListener('change', syncProductSummary);
        syncPlanRows();
        syncProductSummary();
    }

    if (productChangeButton && productSelect) {
        productChangeButton.addEventListener('click', function () {
            productSelect.value = '';
            planRows.forEach(function (row) {
                var radio = row.querySelector('input[type="radio"]');
                if (radio) {
                    radio.checked = false;
                }
                row.classList.remove('is-active');
            });
            syncPlanRows();
            syncProductSummary();
            syncProductPickerVisibility();
            productSelect.focus();
        });
    }

    if (renewsForever && expiresField) {
        var syncExpires = function () {
            expiresField.disabled = renewsForever.checked;
            if (renewsForever.checked) {
                expiresField.value = '';
            }
        };
        renewsForever.addEventListener('change', syncExpires);
        syncExpires();
    }

    modeButtons.forEach(function (button) {
        button.addEventListener('click', function () {
            if (subscriptionMode) {
                subscriptionMode.value = button.getAttribute('data-subscription-mode') || 'plans';
            }
            if (selectedPlanName && subscriptionMode && subscriptionMode.value === 'items' && selectedPlanName.value === '') {
                selectedPlanName.focus();
            }
            updateModeUi();
        });
    });

    if (preferencesToggle && preferencesPanel) {
        preferencesToggle.addEventListener('click', function () {
            var willOpen = preferencesPanel.classList.contains('is-hidden');
            preferencesPanel.classList.toggle('is-hidden', !willOpen);
            preferencesToggle.setAttribute('aria-expanded', willOpen ? 'true' : 'false');
        });
    }

    document.querySelectorAll('[data-address-trigger]').forEach(function (button) {
        button.addEventListener('click', function () {
            openAddressEditor(button.getAttribute('data-address-trigger') || 'billing');
        });
    });

    if (copyBillingToShipping) {
        copyBillingToShipping.addEventListener('click', function (event) {
            event.preventDefault();
            var source = addressStateData.billing || {};
            if (addressAttention) addressAttention.value = source.attention || '';
            if (addressCountry) addressCountry.value = source.country || '';
            if (addressStreet1) addressStreet1.value = source.address1 || '';
            if (addressStreet2) addressStreet2.value = source.address2 || '';
            if (addressCity) addressCity.value = source.city || '';
            if (addressState) addressState.value = source.state || '';
            if (addressPin) addressPin.value = source.pin || '';
            if (addressPhone) addressPhone.value = source.phone || '';
            if (addressFax) addressFax.value = source.fax || '';
        });
    }

    if (saveAddressModal) {
        saveAddressModal.addEventListener('click', function () {
            var target = currentAddressType === 'shipping' ? 'shipping' : 'billing';
            addressStateData[target] = {
                attention: addressAttention ? addressAttention.value.trim() : '',
                country: addressCountry ? addressCountry.value.trim() : '',
                address1: addressStreet1 ? addressStreet1.value.trim() : '',
                address2: addressStreet2 ? addressStreet2.value.trim() : '',
                city: addressCity ? addressCity.value.trim() : '',
                state: addressState ? addressState.value.trim() : '',
                pin: addressPin ? addressPin.value.trim() : '',
                phone: addressPhone ? addressPhone.value.trim() : '',
                fax: addressFax ? addressFax.value.trim() : ''
            };
            renderLines(target === 'billing' ? billingAddress : shippingAddress, addressDataToLines(addressStateData[target]));
            closeAddressEditor();
        });
    }

    if (closeAddressModal) {
        closeAddressModal.addEventListener('click', closeAddressEditor);
    }
    if (cancelAddressModal) {
        cancelAddressModal.addEventListener('click', closeAddressEditor);
    }
    if (addressModal) {
        addressModal.addEventListener('click', function (event) {
            if (event.target === addressModal) {
                closeAddressEditor();
            }
        });
    }

    function formatAmount(value) {
        return Number(value || 0).toFixed(2);
    }

    function syncRowAmount(row) {
        var qty = row.querySelector('input[name="quantity[]"]');
        var rate = row.querySelector('input[name="rate[]"]');
        var amount = row.querySelector('[data-row-amount]');
        if (!qty || !rate || !amount) {
            return;
        }
        amount.textContent = formatAmount((parseFloat(qty.value || '0') || 0) * (parseFloat(rate.value || '0') || 0));
    }

    function bindItemRow(row) {
        row.querySelectorAll('input[name="quantity[]"], input[name="rate[]"]').forEach(function (input) {
            input.addEventListener('input', function () {
                syncRowAmount(row);
            });
        });
        syncRowAmount(row);
    }

    if (itemsBody) {
        itemsBody.querySelectorAll('tr').forEach(bindItemRow);
    }

    if (addRowButton && itemsBody) {
        addRowButton.addEventListener('click', function () {
            var row = document.createElement('tr');
            row.innerHTML = '<td><div class="sales-item-cell sales-item-cell--details"><span class="sales-item-thumb"><i class="fa-regular fa-image"></i></span><div class="sales-field-stack sales-field-stack--spaced"><input class="sales-form-control" type="text" name="item_name[]" list="subscriptionItemsList" placeholder="Type or click to select an item."><input class="sales-form-control" type="text" name="item_description[]" placeholder="Description"><input type="hidden" name="unit_name[]" value=""></div></div></td><td><div class="sales-item-cell"><input class="sales-form-control" type="number" step="0.01" min="0" name="quantity[]" value="1"></div></td><td><div class="sales-item-cell"><input class="sales-form-control" type="number" step="0.01" min="0" name="rate[]" value="0"></div></td><td><div class="sales-item-cell sales-item-plain"><strong data-row-amount>0.00</strong></div></td>';
            itemsBody.appendChild(row);
            bindItemRow(row);
        });
    }

    if (openContactPersonModal) {
        openContactPersonModal.addEventListener('click', openContactModal);
    }
    if (closeContactPersonModal) {
        closeContactPersonModal.addEventListener('click', closeContactModal);
    }
    if (cancelContactPerson) {
        cancelContactPerson.addEventListener('click', closeContactModal);
    }
    if (contactUploadLink && contactProfileImage) {
        contactUploadLink.addEventListener('click', function (event) {
            event.preventDefault();
            contactProfileImage.click();
        });
    }
    if (contactPersonModal) {
        contactPersonModal.addEventListener('click', function (event) {
            if (event.target === contactPersonModal) {
                closeContactModal();
            }
        });
    }
    if (saveContactPerson) {
        saveContactPerson.addEventListener('click', function () {
            var emailValue = contactEmail && contactEmail.value ? contactEmail.value.trim() : '';
            if (emailValue === '') {
                if (contactEmail) {
                    contactEmail.focus();
                }
                return;
            }
            var existing = Array.from(document.querySelectorAll('.sub-email-actions .sub-email-chip span')).some(function (span) {
                return span.textContent.trim().toLowerCase() === emailValue.toLowerCase();
            });
            if (!existing) {
                var chip = createEmailChip(emailValue, true);
                var actions = document.querySelector('.sub-email-actions');
                if (actions) {
                    actions.appendChild(chip);
                }
            }
            resetContactPersonForm();
            closeContactModal();
        });
    }

    updateModeUi();

    var openNewCustomerModal = document.getElementById('openNewCustomerModal');
    if (openNewCustomerModal) {
        openNewCustomerModal.addEventListener('click', function (event) {
            event.preventDefault();
            window.location.href = 'subscription_new.php?new_customer=1';
        });
    }

    var closeCustomerModal = document.getElementById('closeCustomerModal');
    var cancelCustomerModal = document.getElementById('cancelCustomerModal');
    function closeModal() {
        window.location.href = 'subscription_new.php<?php echo $selectedCustomer ? '?customer_id=' . (int) $selectedCustomer['id'] : ''; ?>';
    }
    if (closeCustomerModal) {
        closeCustomerModal.addEventListener('click', closeModal);
    }
    if (cancelCustomerModal) {
        cancelCustomerModal.addEventListener('click', closeModal);
    }

    document.querySelectorAll('[data-file-trigger]').forEach(function (button) {
        button.addEventListener('click', function () {
            var input = document.getElementById(button.getAttribute('data-file-trigger'));
            if (input) {
                input.click();
            }
        });
    });

    var inlineDocs = document.getElementById('inlineCustomerDocuments');
    var inlineDocsList = document.getElementById('inlineCustomerDocumentsList');
    if (inlineDocs && inlineDocsList) {
        inlineDocs.addEventListener('change', function () {
            var names = Array.from(inlineDocs.files || []).map(function (file) { return file.name; });
            inlineDocsList.textContent = names.length ? names.join(', ') : '';
        });
    }

    document.addEventListener('click', function (event) {
        if (pickerMenu && pickerToggle && !pickerMenu.contains(event.target) && !pickerToggle.contains(event.target)) {
            pickerMenu.classList.add('is-hidden');
        }
    });

    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape' && addressModal && addressModal.classList.contains('is-visible')) {
            closeAddressEditor();
        }
        if (event.key === 'Escape' && contactPersonModal && contactPersonModal.classList.contains('is-visible')) {
            closeContactModal();
        }
    });
});
</script>
</body>
</html>



