<?php

// === SESSION INITIALIZATION ===
session_start();
require_once 'includes/functions.php';
require_once 'db.php';
require_once 'includes/locations.php';

// Clear any previous signup messages
if (isset($_SESSION['signup_errors'])) {
    $errors = $_SESSION['signup_errors'];
    unset($_SESSION['signup_errors']);
}

$success = $_SESSION['signup_success'] ?? '';
unset($_SESSION['signup_success']);

$field_errors = $_SESSION['signup_field_errors'] ?? [];
unset($_SESSION['signup_field_errors']);

$old = $_SESSION['signup_old_input'] ?? [];
unset($_SESSION['signup_old_input']);

// === DATA SETUP ===
$countries_map = get_countries($conn);
$countries_list = $countries_map ? array_keys($countries_map) : get_country_names($conn);
$selected_country = $old['country'] ?? 'India';
$states_list = get_locations($conn, $selected_country);

$preferred_countries = [
    'India',
    'United Arab Emirates',
    'United States',
    'Saudi Arabia',
    'Bahrain',
    'Qatar',
    'Oman',
    'Kuwait',
    'Canada',
];

$countries_list = array_values(array_unique(array_merge(
    $preferred_countries,
    array_values(array_filter($countries_list, static function ($country) use ($preferred_countries) {
        return !in_array($country, $preferred_countries, true);
    }))
)));

$phone_codes = [
    'India' => '+91',
    'United Arab Emirates' => '+971',
    'United States' => '+1',
    'Saudi Arabia' => '+966',
    'Bahrain' => '+973',
    'Qatar' => '+974',
    'Oman' => '+968',
    'Kuwait' => '+965',
    'Canada' => '+1',
];

$default_phone_code = $phone_codes[$selected_country] ?? '+91';
$selected_phone_code = $old['phone_code'] ?? $default_phone_code;
$datacenter_country = strtoupper($selected_country === 'India' ? 'INDIA' : $selected_country);
?>

<!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>Sign Up - Payroll</title>
<link rel="stylesheet" href="signup.css">
<link rel="stylesheet" href="assets/font-manrope.css"><link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
</head>
<body>

<main class="main-container">

    <section class="left-section">
        <div class="shape"></div>

        <div class="steps">
            <div class="step-item">
                <span class="check"><i class="fa-solid fa-check"></i></span>
                Create your account
            </div>
            <div class="step-item">
                <span class="check"><i class="fa-solid fa-check"></i></span>
                Configure settings
            </div>
            <div class="step-item">
                <span class="check"><i class="fa-solid fa-check"></i></span>
                Run payroll
            </div>
        </div>

        <h1>
            Payroll made simple, efficient,<br>
            and auto-compliant for every business.
        </h1>

        <div class="trusted-box">
            <p class="trusted">Trusted by growing companies</p>
            <div class="companies">
                <span class="company-item"><img src="images/dexian-2x.png" alt="Dexian" class="company-logo"></span>
                <span class="company-item"><img src="images/vedatya-2x.png" alt="Vedatya Institute" class="company-logo"></span>
                <span class="company-item"><img src="images/geeks-for-geeks-2x.png" alt="Geeks for Geeks" class="company-logo"></span>
                <span class="company-item"><img src="images/securityhq-2x.png" alt="SecurityHQ" class="company-logo"></span>
                <span class="company-item"><img src="images/leegality-logo-2x.png" alt="Leegality" class="company-logo"></span>
            </div>
        </div>
    </section>

    <section class="right-section">
        <div class="logo-row">
            <img src="images/zoho-payroll-logo.svg" alt="Zoho Payroll" class="logo-image">
        </div>

        <div class="form-wrapper">
            <h2>Let's get started</h2>

            <?php if (isset($errors) && count($errors) > 0): ?>
                <div class="error-box">
                    <?php foreach ($errors as $error): ?>
                        <p><?php echo $error; ?></p>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <?php if (!empty($success)): ?>
                <div class="success-box">
                    <p><?php echo htmlspecialchars($success); ?></p>
                </div>
            <?php endif; ?>

            <form action="signup_otp.php" method="POST" novalidate>
                <div class="form-group">
                    <label for="company_name">Company Name</label>
                    <div class="input-box">
                        <i class="fa fa-building"></i>
                        <input type="text" id="company_name" name="company_name" placeholder="Company Name" value="<?php echo htmlspecialchars($old['company_name'] ?? ''); ?>" required>
                    </div>
                    <?php if (!empty($field_errors['company_name'])): ?><p class="field-error"><?php echo htmlspecialchars($field_errors['company_name']); ?></p><?php endif; ?>
                </div>

                <div class="form-group">
                    <label for="email">Email Address</label>
                    <div class="input-box">
                        <i class="fa fa-envelope"></i>
                        <input type="email" id="email" name="email" placeholder="Email Address" value="<?php echo htmlspecialchars($old['email'] ?? ''); ?>" required>
                    </div>
                    <?php if (!empty($field_errors['email'])): ?><p class="field-error"><?php echo $field_errors['email']; ?></p><?php endif; ?>
                </div>

                <div class="form-group">
                    <label for="phone">Phone Number</label>
                    <div class="phone-group">
                        <div class="phone-code-wrap">
                            <i class="fa fa-phone"></i>
                            <select id="phone_code" name="phone_code" required>
                                <?php foreach (array_unique(array_values($phone_codes)) as $code): ?>
                                    <option value="<?php echo htmlspecialchars($code); ?>" <?php echo ($selected_phone_code === $code) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($code); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <input type="text" id="phone" name="phone" placeholder="Phone Number" value="<?php echo htmlspecialchars($old['phone'] ?? ''); ?>" pattern="[0-9]{10}" minlength="10" maxlength="10" required>
                    </div>
                    <?php if (!empty($field_errors['phone'])): ?><p class="field-error"><?php echo htmlspecialchars($field_errors['phone']); ?></p><?php endif; ?>
                </div>

                <div class="form-group">
                    <label for="password">Password</label>
                    <div class="input-box">
                        <i class="fa fa-key"></i>
                        <input type="password" id="password" name="password" placeholder="Password" minlength="8" required>
                    </div>
                    <?php if (!empty($field_errors['password'])): ?><p class="field-error"><?php echo htmlspecialchars($field_errors['password']); ?></p><?php endif; ?>
                </div>

                <div class="form-row">
                    <div class="form-group half">
                        <label for="country">Country</label>
                        <div class="input-box">
                            <i class="fa fa-globe"></i>
                            <select id="country" name="country" required>
                                <?php foreach ($countries_list as $country): ?>
                                    <option value="<?php echo htmlspecialchars($country); ?>" <?php echo ($selected_country === $country) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($country); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <?php if (!empty($field_errors['country'])): ?><p class="field-error"><?php echo htmlspecialchars($field_errors['country']); ?></p><?php endif; ?>
                    </div>

                    <div class="form-group half">
                        <label for="state">State</label>
                        <div class="input-box">
                            <i class="fa fa-location-dot"></i>
                            <select id="state" name="state" required>
                                <option value="">Select State</option>
                                <?php foreach ($states_list as $state): ?>
                                    <option value="<?php echo $state; ?>" <?php echo (($old['state'] ?? '') === $state) ? 'selected' : ''; ?>><?php echo $state; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <?php if (!empty($field_errors['state'])): ?><p class="field-error"><?php echo htmlspecialchars($field_errors['state']); ?></p><?php endif; ?>
                    </div>
                </div>

                <p class="datacenter">Your data will be in <span id="datacenterCountry"><?php echo htmlspecialchars($datacenter_country); ?></span> data center.</p>

                <div class="checkbox-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="terms" value="1" <?php echo !empty($old['terms']) ? 'checked' : ''; ?> required>
                        <span>I agree to the <a href="#">Terms of Service</a> and <a href="#">Privacy Policy</a></span>
                    </label>
                    <?php if (!empty($field_errors['terms'])): ?><p class="field-error"><?php echo htmlspecialchars($field_errors['terms']); ?></p><?php endif; ?>
                </div>

                <button type="submit" class="signup-btn">Sign up now</button>
            </form>

            <div class="social-login">
                <p>Or sign up using</p>
                <div class="social-icons">
                    <div class="icon google"><i class="fa-brands fa-google"></i></div>
                    <div class="icon linkedin"><i class="fa-brands fa-linkedin"></i></div>
                    <div class="icon office365">
                        <span title="Office365" onclick="FederatedSignIn.GO(&quot;AZURE&quot;),zohoFedClickEvent(&quot;Office365&quot;)" class="social-icon-windows"></span>
                    </div>
                </div>
            </div>

            <div class="login-link">
                Already have an account? <a href="signin.php">Sign In</a>
            </div>
        </div>
    </section>

</main>

<script>
  (function(){
    const countrySelect = document.getElementById('country');
    const stateSelect = document.getElementById('state');
    const phoneCodeSelect = document.getElementById('phone_code');
    const datacenterCountry = document.getElementById('datacenterCountry');
    if (!countrySelect || !stateSelect) return;

    const phoneCodes = <?php echo json_encode($phone_codes); ?>;

    const setStates = (states) => {
      const current = stateSelect.dataset.selected || stateSelect.value;
      stateSelect.innerHTML = '<option value="">Select State</option>';
      states.forEach(state => {
        const opt = document.createElement('option');
        opt.value = state;
        opt.textContent = state;
        if (state === current) opt.selected = true;
        stateSelect.appendChild(opt);
      });
    };

    const fetchStates = (country) => {
      fetch('get_states.php?country=' + encodeURIComponent(country))
        .then(res => res.json())
        .then(data => {
        if (Array.isArray(data.states)) {
          setStates(data.states);
        }
        })
        .catch(() => {});
    };

    countrySelect.addEventListener('change', function(){
      const nextCountry = countrySelect.value;
      if (phoneCodeSelect && phoneCodes[nextCountry]) {
        phoneCodeSelect.value = phoneCodes[nextCountry];
      }
      if (datacenterCountry) {
        datacenterCountry.textContent = nextCountry.toUpperCase();
      }
      stateSelect.dataset.selected = '';
      fetchStates(countrySelect.value);
    });
  })();
</script>
</body>
</html>

