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

billing_require_auth();

$user = billing_current_user();
$organization = billing_current_organization();

if (!$user) {
    billing_redirect('signin.php');
}

if ($organization && !empty($organization['onboarding_completed_at'])) {
    billing_redirect('dashboard.php?tab=dashboard');
}

$step = max(1, min(3, (int) ($_GET['step'] ?? 1)));
$fiscalYears = billing_fiscal_years();
$languages = billing_languages();
$billingModes = billing_billing_modes();
$billingSources = billing_billing_sources();
$countryOptions = ['India', 'United States', 'United Kingdom', 'United Arab Emirates', 'Singapore'];
$stateOptions = ['Tamil Nadu', 'Kerala', 'Karnataka', 'Maharashtra', 'Delhi', 'West Bengal', 'Telangana', 'Andhra Pradesh'];

$form = [
    'organization_name' => (string) ($organization['organization_name'] ?? $user['business_name'] ?? ''),
    'country' => (string) ($organization['location_country'] ?? 'India'),
    'state' => (string) ($organization['state_name'] ?? ''),
    'base_currency' => (string) ($organization['base_currency'] ?? 'INR - Indian Rupee'),
    'fiscal_year' => (string) ($organization['fiscal_year'] ?? 'April - March'),
    'language' => (string) ($organization['language_pref'] ?? 'English'),
    'timezone_label' => (string) ($organization['timezone_label'] ?? '(GMT 5:30) India Standard Time (Asia/Kolkata)'),
    'gst_registered' => !empty($organization['gst_registered']) ? '1' : '',
    'industry_type' => (string) ($organization['industry_type'] ?? ''),
    'billing_mode' => (string) ($organization['billing_mode'] ?? 'hybrid'),
    'billing_source' => (string) ($organization['billing_source'] ?? ''),
    'wants_import' => array_key_exists('wants_import', (array) $organization) ? (!empty($organization['wants_import']) ? '1' : '') : '1',
];

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postedStep = max(1, min(3, (int) ($_POST['current_step'] ?? $step)));
    $step = $postedStep;

    $form['organization_name'] = billing_clean((string) ($_POST['organization_name'] ?? $form['organization_name']));
    $form['country'] = billing_clean((string) ($_POST['country'] ?? $form['country']));
    $form['state'] = billing_clean((string) ($_POST['state'] ?? $form['state']));
    $form['base_currency'] = billing_clean((string) ($_POST['base_currency'] ?? $form['base_currency']));
    $form['fiscal_year'] = billing_clean((string) ($_POST['fiscal_year'] ?? $form['fiscal_year']));
    $form['language'] = billing_clean((string) ($_POST['language'] ?? $form['language']));
    $form['timezone_label'] = billing_clean((string) ($_POST['timezone_label'] ?? $form['timezone_label']));
    $form['gst_registered'] = !empty($_POST['gst_registered']) ? '1' : '';
    $form['industry_type'] = billing_clean((string) ($_POST['industry_type'] ?? $form['industry_type']));
    $form['billing_mode'] = billing_clean((string) ($_POST['billing_mode'] ?? $form['billing_mode']));
    $form['billing_source'] = billing_clean((string) ($_POST['billing_source'] ?? $form['billing_source']));
    $form['wants_import'] = !empty($_POST['wants_import']) ? '1' : '';

    if ($postedStep === 1) {
        if ($form['organization_name'] === '' || $form['country'] === '' || $form['state'] === '') {
            $message = 'Please complete your organization details.';
        } else {
            billing_upsert_organization((int) $user['id'], [
                'organization_name' => $form['organization_name'],
                'country' => $form['country'],
                'state' => $form['state'],
                'base_currency' => $form['base_currency'],
                'fiscal_year' => $form['fiscal_year'],
                'language' => $form['language'],
                'timezone_label' => $form['timezone_label'],
                'gst_registered' => $form['gst_registered'] === '1',
                'industry_type' => $form['industry_type'],
                'billing_mode' => $form['billing_mode'],
                'billing_source' => $form['billing_source'],
                'wants_import' => $form['wants_import'] === '1',
            ]);
            billing_redirect('onboarding.php?step=2');
        }
    } elseif ($postedStep === 2) {
        if ($form['billing_mode'] === '' || !isset($billingModes[$form['billing_mode']])) {
            $message = 'Please choose a billing mode.';
        } else {
            billing_upsert_organization((int) $user['id'], [
                'organization_name' => $form['organization_name'],
                'country' => $form['country'],
                'state' => $form['state'],
                'base_currency' => $form['base_currency'],
                'fiscal_year' => $form['fiscal_year'],
                'language' => $form['language'],
                'timezone_label' => $form['timezone_label'],
                'gst_registered' => $form['gst_registered'] === '1',
                'industry_type' => $form['industry_type'],
                'billing_mode' => $form['billing_mode'],
                'billing_source' => $form['billing_source'],
                'wants_import' => $form['wants_import'] === '1',
            ]);
            billing_redirect('onboarding.php?step=3');
        }
    } elseif ($postedStep === 3) {
        if ($form['billing_source'] === '') {
            $message = 'Please tell us what you used before.';
        } else {
            $organizationId = billing_upsert_organization((int) $user['id'], [
                'organization_name' => $form['organization_name'],
                'country' => $form['country'],
                'state' => $form['state'],
                'base_currency' => $form['base_currency'],
                'fiscal_year' => $form['fiscal_year'],
                'language' => $form['language'],
                'timezone_label' => $form['timezone_label'],
                'gst_registered' => $form['gst_registered'] === '1',
                'industry_type' => $form['industry_type'],
                'billing_mode' => $form['billing_mode'],
                'billing_source' => $form['billing_source'],
                'wants_import' => $form['wants_import'] === '1',
            ]);
            if ($organizationId > 0) {
                billing_seed_demo_data((int) $user['id'], $organizationId);
            }
            billing_redirect('dashboard.php?tab=dashboard');
        }
    }
}
?>
<!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>Onboarding</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;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>
<main class="setup-shell">
    <section class="setup-main">
        <div class="billing-logo setup-brand">
            <span class="billing-logo-mark"><i class="fa-solid fa-bolt"></i></span>
            <span class="billing-logo-copy">b2lmobitech Billing<small>Customer-ready billing</small></span>
        </div>

        <div class="setup-progress" aria-hidden="true">
            <span class="<?php echo $step >= 1 ? 'is-active' : ''; ?>"></span>
            <span class="<?php echo $step >= 2 ? 'is-active' : ''; ?>"></span>
            <span class="<?php echo $step >= 3 ? 'is-active' : ''; ?>"></span>
        </div>

        <div class="setup-card">
            <?php if ($message !== ''): ?>
                <div style="margin:0 0 18px; padding:14px 16px; border-radius:14px; background:#fff3f3; border:1px solid #f2caca; color:#a12626; font-weight:600;">
                    <?php echo billing_escape($message); ?>
                </div>
            <?php endif; ?>

            <form method="post">
                <input type="hidden" name="current_step" value="<?php echo $step; ?>">

                <?php if ($step === 1): ?>
                    <div class="setup-eyebrow">Step 1 of 3</div>
                    <h1 class="setup-title">Tell us about your organization</h1>
                    <p class="setup-subtitle">Set up the basics for your billing workspace so invoices, taxes, and reporting start with the right defaults.</p>

                    <div class="setup-field">
                        <label><span class="required">Organization Name</span></label>
                        <input class="setup-input" type="text" name="organization_name" value="<?php echo billing_escape($form['organization_name']); ?>" required>
                    </div>

                    <div class="setup-grid-two">
                        <div class="setup-field">
                            <label><span class="required">Country</span></label>
                            <select class="setup-select" name="country" required>
                                <?php foreach ($countryOptions as $option): ?>
                                    <option value="<?php echo billing_escape($option); ?>" <?php echo $form['country'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="setup-field">
                            <label><span class="required">State</span></label>
                            <select class="setup-select" name="state" required>
                                <option value="">Select state</option>
                                <?php foreach ($stateOptions as $option): ?>
                                    <option value="<?php echo billing_escape($option); ?>" <?php echo $form['state'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="setup-grid-two">
                        <div class="setup-field">
                            <label>Base Currency</label>
                            <input class="setup-input" type="text" name="base_currency" value="<?php echo billing_escape($form['base_currency']); ?>">
                        </div>
                        <div class="setup-field">
                            <label>Fiscal Year</label>
                            <select class="setup-select" name="fiscal_year">
                                <?php foreach ($fiscalYears as $option): ?>
                                    <option value="<?php echo billing_escape($option); ?>" <?php echo $form['fiscal_year'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="setup-grid-two">
                        <div class="setup-field">
                            <label>Language</label>
                            <select class="setup-select" name="language">
                                <?php foreach ($languages as $option): ?>
                                    <option value="<?php echo billing_escape($option); ?>" <?php echo $form['language'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="setup-field">
                            <label>Industry Type</label>
                            <input class="setup-input" type="text" name="industry_type" value="<?php echo billing_escape($form['industry_type']); ?>">
                        </div>
                    </div>

                    <label class="setup-switch">
                        <input type="checkbox" name="gst_registered" value="1" <?php echo $form['gst_registered'] === '1' ? 'checked' : ''; ?>>
                        <span>My organization is GST registered</span>
                    </label>

                    <div class="setup-actions">
                        <button class="primary-btn deep" type="submit">Continue</button>
                    </div>
                <?php elseif ($step === 2): ?>
                    <div class="setup-eyebrow">Step 2 of 3</div>
                    <h1 class="setup-title">Choose your billing workflow</h1>
                    <p class="setup-subtitle">Pick the mode that best matches how your team charges customers. You can still expand this later.</p>

                    <div class="mode-cards">
                        <?php foreach ($billingModes as $key => $mode): ?>
                            <label class="mode-card <?php echo $form['billing_mode'] === $key ? 'is-selected' : ''; ?>">
                                <input type="radio" name="billing_mode" value="<?php echo billing_escape($key); ?>" <?php echo $form['billing_mode'] === $key ? 'checked' : ''; ?>>
                                <i class="<?php echo billing_escape((string) $mode['icon']); ?> mode-icon"></i>
                                <span class="mode-title"><?php echo billing_escape((string) $mode['title']); ?></span>
                                <span class="mode-text"><?php echo billing_escape((string) $mode['description']); ?></span>
                            </label>
                        <?php endforeach; ?>
                    </div>

                    <div class="setup-actions">
                        <a class="setup-back" href="onboarding.php?step=1">Back</a>
                        <button class="primary-btn deep" type="submit">Continue</button>
                    </div>
                <?php else: ?>
                    <div class="setup-eyebrow">Step 3 of 3</div>
                    <h1 class="setup-title">Finish and bring your data in</h1>
                    <p class="setup-subtitle">Tell us how you handled billing before and whether you want to import existing records. We’ll complete setup and open your dashboard.</p>

                    <div class="setup-field">
                        <label><span class="required">What were you using before?</span></label>
                        <select class="setup-select" name="billing_source" required>
                            <option value="">Select an option</option>
                            <?php foreach ($billingSources as $source): ?>
                                <option value="<?php echo billing_escape($source); ?>" <?php echo $form['billing_source'] === $source ? 'selected' : ''; ?>><?php echo billing_escape($source); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <label class="setup-switch">
                        <input type="checkbox" name="wants_import" value="1" <?php echo $form['wants_import'] === '1' ? 'checked' : ''; ?>>
                        <span>I want to import my existing customers, invoices, or balances later</span>
                    </label>

                    <div class="setup-actions">
                        <a class="setup-back" href="onboarding.php?step=2">Back</a>
                        <button class="primary-btn deep" type="submit">Complete Setup</button>
                    </div>
                <?php endif; ?>
            </form>
        </div>
    </section>

    <aside class="setup-side">
        <div class="setup-side-art">
            <div class="art-card">
                <h3>What unlocks after setup</h3>
                <div class="art-stats">
                    <div class="art-stat">
                        <div class="line"></div>
                        <strong>Customers</strong>
                        <p style="margin:10px 0 0;color:#64748b;">Create profiles, balances, and statements.</p>
                    </div>
                    <div class="art-stat">
                        <div class="line short"></div>
                        <strong>Invoices</strong>
                        <p style="margin:10px 0 0;color:#64748b;">Send one-time or recurring billing faster.</p>
                    </div>
                    <div class="art-stat">
                        <div class="line short"></div>
                        <strong>Payments</strong>
                        <p style="margin:10px 0 0;color:#64748b;">Track collections, reminders, and cashflow.</p>
                    </div>
                    <div class="art-stat">
                        <div class="line"></div>
                        <strong>Reports</strong>
                        <p style="margin:10px 0 0;color:#64748b;">Review receivables, revenue, and trends.</p>
                    </div>
                </div>
            </div>
        </div>
    </aside>
</main>
</body>
</html>
