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

$products = billing_active_products((int) $user['id'], (int) $organization['id']);
$widgets = billing_get_pricing_widgets((int) $user['id'], (int) $organization['id']);
$showModal = isset($_GET['new']) || $_SERVER['REQUEST_METHOD'] === 'POST';
$warning = '';
$errors = [];
$form = [
    'widget_name' => '',
    'product_item_id' => '',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $form['widget_name'] = billing_clean((string) ($_POST['widget_name'] ?? ''));
    $form['product_item_id'] = billing_clean((string) ($_POST['product_item_id'] ?? ''));

    if ($form['widget_name'] === '') {
        $errors[] = 'Enter the widget name.';
    }
    if ((int) $form['product_item_id'] <= 0) {
        $errors[] = 'Select a product.';
    }

    if ($errors === [] && !billing_product_has_pricing_widget_plan((int) $user['id'], (int) $organization['id'], (int) $form['product_item_id'])) {
        $warning = "The selected product does not have plans for which pricing widget is enabled. To create a pricing widget, go to the required plan's edit page and mark the pricing widget checkbox.";
    } elseif ($errors === []) {
        $widgetId = billing_create_pricing_widget((int) $user['id'], (int) $organization['id'], $form['widget_name'], (int) $form['product_item_id']);
        if ($widgetId) {
            billing_flash('success', 'Pricing widget created successfully.');
            billing_redirect('pricing_widgets.php');
        }
        $errors[] = 'Unable to create the pricing widget right now.';
    }
}

$flashSuccess = billing_flash('success');
?>
<!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>Pricing Widgets | 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">
</head>
<body>
<div class="dashboard-shell customer-shell">
    <?php include dirname(__DIR__) . '/includes/app_sidebar.php'; ?>
    <div class="dashboard-main customer-main">
        <?php include dirname(__DIR__) . '/includes/topbar.php'; ?>
        <main class="catalog-page">
            <?php if ($flashSuccess): ?><div class="customer-flash"><?php echo billing_escape($flashSuccess); ?></div><?php endif; ?>
            <section class="customer-views-card catalog-widget-card">
                <div class="catalog-list-head">
                    <div class="catalog-view-links">
                        <a class="is-active" href="pricing_widgets.php">Pricing Widgets</a>
                    </div>
                    <div class="customer-view-actions">
                        <a class="customer-btn customer-btn--green" href="pricing_widgets.php?new=1"><i class="fa-solid fa-plus"></i> New</a>
                    </div>
                </div>

                <?php if ($widgets === []): ?>
                    <div class="catalog-empty-state catalog-empty-state--wide">
                        <h2>Create Your First Pricing Widget</h2>
                        <p>Display your plans and their features in an embeddable widget on your website or web app.</p>
                    </div>
                <?php else: ?>
                    <div class="customer-table-wrap">
                        <table class="customer-table-view">
                            <thead><tr><th>NAME</th><th>PRODUCT</th><th>STATUS</th><th>CREATED</th></tr></thead>
                            <tbody>
                                <?php foreach ($widgets as $widget): ?>
                                    <tr>
                                        <td><?php echo billing_escape((string) $widget['widget_name']); ?></td>
                                        <td><?php echo billing_escape((string) $widget['product_name']); ?></td>
                                        <td><?php echo billing_escape((string) $widget['status_label']); ?></td>
                                        <td><?php echo billing_escape(date('d/m/Y', strtotime((string) $widget['created_at']))); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </section>

            <?php if ($showModal): ?>
                <section class="catalog-modal-backdrop">
                    <div class="catalog-modal-card">
                        <?php if ($warning !== ''): ?>
                            <div class="catalog-warning-box">
                                <i class="fa-solid fa-triangle-exclamation"></i>
                                <div>
                                    <p><?php echo billing_escape($warning); ?></p>
                                    <div class="catalog-warning-actions">
                                        <a class="customer-btn customer-btn--green" href="pricing_widgets.php">Got It</a>
                                        <a class="customer-btn" href="plans.php">Go to the product's edit page</a>
                                    </div>
                                </div>
                            </div>
                        <?php else: ?>
                            <form method="post">
                                <div class="customer-form-header"><h1>New Pricing Widget</h1></div>
                                <?php if ($errors !== []): ?><div class="customer-error-banner"><span><?php echo billing_escape(implode(' ', $errors)); ?></span></div><?php endif; ?>
                                <div class="catalog-form-grid">
                                    <label class="is-required">Name*</label>
                                    <input type="text" name="widget_name" value="<?php echo billing_escape($form['widget_name']); ?>">
                                    <label class="is-required">Product*</label>
                                    <select name="product_item_id">
                                        <option value="">Select a 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="customer-form-footer">
                                    <button class="customer-btn customer-btn--green" type="submit">Proceed</button>
                                    <a class="customer-btn" href="pricing_widgets.php">Cancel</a>
                                </div>
                            </form>
                        <?php endif; ?>
                    </div>
                </section>
            <?php endif; ?>
        </main>
    </div>
</div>
<script src="assets/billing.js"></script>
</body>
</html>



