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

$currentUser = billing_current_user();
if ($currentUser) {
    $organization = billing_current_organization();
    if ($organization && !empty($organization['onboarding_completed_at'])) {
        billing_redirect('dashboard.php?tab=dashboard');
    }
    billing_redirect('onboarding.php?step=1');
}

$message = '';
$messageType = 'error';
$countryOptions = ['India', 'United States', 'United Kingdom', 'United Arab Emirates', 'Singapore'];
$stateOptions = ['Tamil Nadu', 'Kerala', 'Karnataka', 'Maharashtra', 'Delhi', 'West Bengal', 'Telangana', 'Andhra Pradesh'];
$form = [
    'company_name' => '',
    'email' => '',
    'phone_code' => '+91',
    'phone' => '',
    'password' => '',
    'state' => '',
    'country' => 'India',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $form['company_name'] = billing_clean((string) ($_POST['company_name'] ?? ''));
    $form['email'] = billing_clean((string) ($_POST['email'] ?? ''));
    $form['phone_code'] = billing_clean((string) ($_POST['phone_code'] ?? '+91'));
    $form['phone'] = preg_replace('/\D+/', '', (string) ($_POST['phone'] ?? '')) ?? '';
    $form['password'] = (string) ($_POST['password'] ?? '');
    $form['state'] = billing_clean((string) ($_POST['state'] ?? ''));
    $form['country'] = billing_clean((string) ($_POST['country'] ?? 'India'));

    if ($form['company_name'] === '') {
        $message = 'Please enter your business name.';
    } elseif (!filter_var($form['email'], FILTER_VALIDATE_EMAIL)) {
        $message = 'Please enter a valid email address.';
    } elseif ($form['phone'] === '' || strlen($form['phone']) < 10) {
        $message = 'Please enter a valid phone number.';
    } elseif (strlen($form['password']) < 6) {
        $message = 'Password must be at least 6 characters.';
    } elseif ($form['state'] === '') {
        $message = 'Please enter your state.';
    } else {
        $existingUser = billing_fetch_one('SELECT id FROM users WHERE email = ? LIMIT 1', 's', [$form['email']]);
        if ($existingUser) {
            $message = 'Email already exists. Please sign in instead.';
        } else {
            $userId = billing_create_user_from_signup($form);
            if ($userId) {
                $organizationId = billing_upsert_organization($userId, [
                    'organization_name' => $form['company_name'],
                    'country' => $form['country'],
                    'state' => $form['state'],
                ]);

                $_SESSION['billing_user_id'] = $userId;
                $_SESSION['billing_user_name'] = $form['company_name'];
                $_SESSION['billing_user_email'] = $form['email'];

                if ($organizationId > 0) {
                    billing_redirect('onboarding.php?step=1');
                }

                billing_redirect('dashboard.php?tab=dashboard');
            }

            $message = 'Unable to create your account right now.';
        }
    }
}
?>
<!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>b2lmobitech Billing Sign Up</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 class="billing-auth-body">
<main class="auth-shell">
    <section class="auth-showcase">
        <div class="billing-logo">
            <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="showcase-copy">
            <h1>Create your billing workspace and start managing customers, invoices, subscriptions, and payments.</h1>
        </div>
        <div class="showcase-proof">
            <h4>Built For Speed</h4>
            <div class="proof-logos">
                <span>Invoices</span>
                <span>Subscriptions</span>
                <span>Payments</span>
                <span>GST</span>
                <span>Reports</span>
            </div>
        </div>
    </section>

    <section class="auth-panel">
        <div class="auth-form-wrap">
            <h1 class="auth-title">Sign up</h1>
            <p class="auth-subtitle">Create your billing account.</p>

            <?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" class="field-list">
                <div class="field-group">
                    <label for="company_name">Business name</label>
                    <div class="field-shell">
                        <i class="fa-regular fa-building"></i>
                        <input id="company_name" name="company_name" type="text" value="<?php echo billing_escape($form['company_name']); ?>" required>
                    </div>
                </div>

                <div class="field-group">
                    <label for="email">Email address</label>
                    <div class="field-shell">
                        <i class="fa-regular fa-envelope"></i>
                        <input id="email" name="email" type="email" value="<?php echo billing_escape($form['email']); ?>" required>
                    </div>
                </div>

                <div class="field-row">
                    <div class="field-group">
                        <label for="phone_code">Code</label>
                        <div class="field-shell">
                            <i class="fa-solid fa-globe"></i>
                            <input id="phone_code" name="phone_code" type="text" value="<?php echo billing_escape($form['phone_code']); ?>" required>
                        </div>
                    </div>

                    <div class="field-group">
                        <label for="phone">Phone number</label>
                        <div class="field-shell">
                            <i class="fa-solid fa-phone"></i>
                            <input id="phone" name="phone" type="text" value="<?php echo billing_escape($form['phone']); ?>" required>
                        </div>
                    </div>
                </div>

                <div class="field-group">
                    <label for="password">Password</label>
                    <div class="field-shell">
                        <i class="fa-solid fa-lock"></i>
                        <input id="password" name="password" type="password" required>
                    </div>
                </div>

                <div class="field-row">
                    <div class="field-group">
                        <label for="state">State</label>
                        <div class="field-shell">
                            <i class="fa-regular fa-map"></i>
                            <select id="state" 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="field-group">
                        <label for="country">Country</label>
                        <div class="field-shell">
                            <i class="fa-solid fa-location-dot"></i>
                            <select id="country" 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>
                </div>

                <button class="primary-btn" type="submit">Create Account</button>
            </form>

            <p class="help-note">Already have an account? <a href="signin.php">Sign in</a></p>
        </div>
    </section>
</main>
</body>
</html>
