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

billing_require_auth();
billing_ensure_product_catalog_support();

$user = billing_current_user();
$organization = billing_current_organization();
if (!$user) {
    billing_redirect('signin.php');
}
if (!$organization || empty($organization['onboarding_completed_at'])) {
    billing_redirect('onboarding.php?step=1');
}

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

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

$form = [
    'product_item_id' => (string) ($existing['product_item_id'] ?? ($_GET['product_id'] ?? '')),
    'plan_name' => (string) ($existing['plan_name'] ?? ''),
    'plan_code' => (string) ($existing['plan_code'] ?? ''),
    'billing_frequency_value' => (string) ($existing['billing_frequency_value'] ?? '1'),
    'billing_frequency_unit' => (string) ($existing['billing_frequency_unit'] ?? 'Month(s)'),
    'billing_cycles_mode' => (string) ($existing['billing_cycles_mode'] ?? 'Auto-renews until cancelled'),
    'billing_cycles_value' => (string) ($existing['billing_cycles_value'] ?? ''),
    'plan_description' => (string) ($existing['plan_description'] ?? ''),
    'pricing_model' => (string) ($existing['pricing_model'] ?? 'Per Unit'),
    'unit_name' => (string) ($existing['unit_name'] ?? ''),
    'price' => (string) ($existing['price'] ?? ''),
    'trial_days' => (string) ($existing['trial_days'] ?? ''),
    'setup_fee' => (string) ($existing['setup_fee'] ?? ''),
    'item_type' => strtolower((string) ($existing['item_type'] ?? 'Service')) === 'goods' ? 'goods' : 'service',
    'plan_account' => (string) ($existing['plan_account'] ?? 'Sales'),
    'setup_fee_account' => (string) ($existing['setup_fee_account'] ?? 'Sales'),
    'pricing_widget_enabled' => !empty($existing['pricing_widget_enabled']) ? '1' : '',
];
$errors = [];

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

    if ((int) $form['product_item_id'] <= 0) {
        $errors['product_item_id'] = 'Select a product.';
    }
    if ($form['plan_name'] === '') {
        $errors['plan_name'] = 'Enter the plan name.';
    }
    if ($form['price'] === '' || !is_numeric($form['price'])) {
        $errors['price'] = 'Enter a valid price.';
    }

    if ($errors === []) {
        $savedId = billing_save_plan((int) $user['id'], (int) $organization['id'], $form, $existing ? $planId : null);
        if ($savedId) {
            billing_flash('success', $existing ? 'Plan updated successfully.' : 'Plan created successfully.');
            billing_redirect('plans.php');
        }
        $errors['save'] = 'Unable to save the plan right now.';
    }
}

$units = billing_catalog_units();
$accounts = billing_catalog_accounts();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="<?php echo billing_escape(billing_base_href()); ?>">
<title><?php echo $existing ? 'Edit Plan' : 'Add Plan'; ?> | 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=20260505-catalog-plan-1">
</head>
<body>
<div class="dashboard-shell customer-shell">
    <?php include dirname(__DIR__) . '/includes/app_sidebar.php'; ?>
    <div class="dashboard-main customer-main">
        <?php include dirname(__DIR__) . '/includes/topbar.php'; ?>
        <main class="catalog-form-page">
            <form method="post" class="catalog-form-card">
                <div class="customer-form-header"><h1><?php echo $existing ? 'Edit Plan' : 'Add Plan'; ?></h1></div>
                <?php if (isset($errors['save'])): ?><div class="customer-error-banner"><span><?php echo billing_escape($errors['save']); ?></span></div><?php endif; ?>

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

                            <div class="catalog-plan-field catalog-plan-field--empty" aria-hidden="true"></div>

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

                            <div class="catalog-plan-field catalog-plan-field--hint">
                                <label class="is-required" for="plan_code">Plan Code*</label>
                                <div class="catalog-plan-field-inline">
                                    <input id="plan_code" type="text" name="plan_code" value="<?php echo billing_escape($form['plan_code']); ?>">
                                    <span class="catalog-plan-info"><i class="fa-regular fa-circle-question"></i></span>
                                </div>
                            </div>

                            <div class="catalog-plan-field">
                                <label class="is-required">Billing Frequency*</label>
                                <div class="catalog-plan-split">
                                    <input class="catalog-plan-split-count" type="number" min="1" name="billing_frequency_value" value="<?php echo billing_escape($form['billing_frequency_value']); ?>">
                                    <select name="billing_frequency_unit">
                                        <option value="Month(s)" <?php echo $form['billing_frequency_unit'] === 'Month(s)' ? 'selected' : ''; ?>>Month(s)</option>
                                        <option value="Year(s)" <?php echo $form['billing_frequency_unit'] === 'Year(s)' ? 'selected' : ''; ?>>Year(s)</option>
                                        <option value="Week(s)" <?php echo $form['billing_frequency_unit'] === 'Week(s)' ? 'selected' : ''; ?>>Week(s)</option>
                                    </select>
                                </div>
                            </div>

                            <div class="catalog-plan-field catalog-plan-field--hint">
                                <label class="is-required">Billing Cycles*</label>
                                <div class="catalog-plan-field-inline">
                                    <div class="catalog-plan-split">
                                        <select name="billing_cycles_mode">
                                            <option value="Auto-renews until cancelled" <?php echo $form['billing_cycles_mode'] === 'Auto-renews until cancelled' ? 'selected' : ''; ?>>Auto-renews until cancelled</option>
                                            <option value="Expires after fixed cycles" <?php echo $form['billing_cycles_mode'] === 'Expires after fixed cycles' ? 'selected' : ''; ?>>Expires after fixed cycles</option>
                                        </select>
                                        <input class="catalog-plan-split-count" type="number" min="1" name="billing_cycles_value" value="<?php echo billing_escape($form['billing_cycles_value']); ?>">
                                    </div>
                                    <span class="catalog-plan-info"><i class="fa-regular fa-circle-question"></i></span>
                                </div>
                            </div>

                            <div class="catalog-plan-field catalog-plan-field--wide">
                                <label for="plan_description">Plan Description</label>
                                <textarea id="plan_description" name="plan_description"><?php echo billing_escape($form['plan_description']); ?></textarea>
                            </div>
                        </div>
                    </div>

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

                <div class="catalog-plan-tabs" role="tablist" aria-label="Plan sections">
                    <button class="is-active" type="button" data-customer-tab="pricing">Pricing</button>
                    <button type="button" data-customer-tab="widgets">Hosted Payment Pages &amp; Portal</button>
                    <button type="button" data-customer-tab="details">Other Details</button>
                </div>

                <div class="catalog-plan-panel customer-tab-panel is-active" data-customer-panel="pricing">
                    <div class="catalog-plan-section-grid">
                        <div class="catalog-plan-field">
                            <label class="is-required" for="pricing_model">Pricing Model*</label>
                            <select id="pricing_model" name="pricing_model">
                                <option value="Per Unit" <?php echo $form['pricing_model'] === 'Per Unit' ? 'selected' : ''; ?>>Per Unit</option>
                                <option value="Flat Fee" <?php echo $form['pricing_model'] === 'Flat Fee' ? 'selected' : ''; ?>>Flat Fee</option>
                            </select>
                        </div>

                        <div class="catalog-plan-field catalog-plan-field--hint">
                            <label for="unit_name">Unit Name</label>
                            <div class="catalog-plan-field-inline">
                                <select id="unit_name" name="unit_name">
                                    <option value="">Select</option>
                                    <?php foreach ($units as $unit): ?>
                                        <option value="<?php echo billing_escape($unit); ?>" <?php echo $form['unit_name'] === $unit ? 'selected' : ''; ?>><?php echo billing_escape($unit); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <span class="catalog-plan-info"><i class="fa-regular fa-circle-question"></i></span>
                            </div>
                        </div>

                        <div class="catalog-plan-field">
                            <label class="is-required" for="price">Price*</label>
                            <div class="catalog-plan-composite">
                                <span>INR</span>
                                <input id="price" type="text" name="price" value="<?php echo billing_escape($form['price']); ?>">
                                <small>/unit /month</small>
                            </div>
                            <?php if (isset($errors['price'])): ?><div class="field-error"><?php echo billing_escape($errors['price']); ?></div><?php endif; ?>
                        </div>

                        <div class="catalog-plan-field">
                            <label for="trial_days">Free Trial</label>
                            <div class="catalog-plan-composite catalog-plan-composite--short">
                                <input id="trial_days" type="number" min="0" name="trial_days" value="<?php echo billing_escape($form['trial_days']); ?>">
                                <small>Days</small>
                            </div>
                        </div>

                        <div class="catalog-plan-field">
                            <label for="setup_fee">Setup Fee</label>
                            <div class="catalog-plan-composite">
                                <span>INR</span>
                                <input id="setup_fee" type="text" name="setup_fee" value="<?php echo billing_escape($form['setup_fee']); ?>">
                            </div>
                        </div>

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

                <div class="catalog-plan-panel customer-tab-panel" data-customer-panel="widgets">
                    <div class="catalog-plan-option-list">
                        <div class="catalog-plan-option-row">
                            <div class="catalog-plan-option-label">Widgets Preference</div>
                            <label class="checkbox-row"><input type="checkbox" name="pricing_widget_enabled" value="1" <?php echo $form['pricing_widget_enabled'] === '1' ? 'checked' : ''; ?>> Display this plan in the pricing and checkout widgets. <a href="#">Learn more</a></label>
                        </div>
                        <div class="catalog-plan-option-row">
                            <div class="catalog-plan-option-label">Plan Change</div>
                            <label class="checkbox-row"><input type="checkbox" disabled> Allow customers to switch to this plan from the portal <span class="catalog-plan-inline-info"><i class="fa-regular fa-circle-question"></i></span></label>
                        </div>
                    </div>
                </div>

                <div class="catalog-plan-panel customer-tab-panel" data-customer-panel="details">
                    <div class="catalog-plan-section-grid">
                        <div class="catalog-plan-field catalog-plan-field--hint">
                            <label for="plan_account">Plan Account</label>
                            <div class="catalog-plan-field-inline">
                                <select id="plan_account" name="plan_account">
                                    <?php foreach ($accounts as $account): ?>
                                        <option value="<?php echo billing_escape($account); ?>" <?php echo $form['plan_account'] === $account ? 'selected' : ''; ?>><?php echo billing_escape($account); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <span class="catalog-plan-info"><i class="fa-regular fa-circle-question"></i></span>
                            </div>
                        </div>

                        <div class="catalog-plan-field catalog-plan-field--hint">
                            <label for="setup_fee_account">Setup Fee Account</label>
                            <div class="catalog-plan-field-inline">
                                <select id="setup_fee_account" name="setup_fee_account">
                                    <?php foreach ($accounts as $account): ?>
                                        <option value="<?php echo billing_escape($account); ?>" <?php echo $form['setup_fee_account'] === $account ? 'selected' : ''; ?>><?php echo billing_escape($account); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <span class="catalog-plan-info"><i class="fa-regular fa-circle-question"></i></span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="customer-form-footer">
                    <button class="customer-btn customer-btn--green" type="submit">Save</button>
                    <a class="customer-btn" href="plans.php">Cancel</a>
                </div>
            </form>
        </main>
    </div>
</div>
<script src="assets/billing.js"></script>
</body>
</html>



