<?php
session_start();

require_once __DIR__ . '/../includes/helpers.php';
require_once __DIR__ . '/../includes/layout.php';
require_once __DIR__ . '/../includes/data.php';

if (!isset($_SESSION['verified_signup'])) {
    redirect('../signup/signup.php');
}

$errors = [];
$field_errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $_SESSION['old'] = $_POST;

    $orgName = trim($_POST['organization_name'] ?? '');
    $location = trim($_POST['organization_location'] ?? 'India');
    $state = trim($_POST['state'] ?? '');
    $industry = trim($_POST['industry'] ?? '');
    $currency = trim($_POST['currency'] ?? 'INR - Indian Rupee');
    $language = trim($_POST['language'] ?? 'English');
    $timezone = trim($_POST['timezone'] ?? '(GMT 5:30) India Standard Time (Asia/Kolkata)');
    $terms = isset($_POST['terms']);

    if ($orgName === '') $field_errors['organization_name'] = 'Please enter your organization name';
    if ($industry === '') $field_errors['industry'] = 'Please select an industry';
    if (!$terms) $field_errors['terms'] = 'Please accept the terms of service and privacy policy';

    if (!$field_errors) {
        $user = fetch_one('SELECT id FROM users WHERE email = ?', 's', [$_SESSION['verified_signup']['email']]);

        if (!$user) {
            $errors[] = 'User not found.';
        } else {
            $userId = (int) $user['id'];
            execute_query(
                'INSERT INTO organizations (user_id, organization_name, organization_location, state_union_territory, industry, base_currency, language, time_zone, terms_accepted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)',
                'isssssss',
                [$userId, $orgName, $location, $state, $industry, $currency, $language, $timezone]
            );
            $_SESSION['organization'] = [
                'user_id' => $userId,
                'organization_name' => $orgName,
                'organization_location' => $location,
                'state' => $state,
                'industry' => $industry,
                'currency' => $currency,
                'language' => $language,
                'timezone' => $timezone,
            ];
            unset($_SESSION['old']);
            redirect('../dashboard/dashboard.php');
        }
    }
}

$selectedOrgLocation = old('organization_location', 'India');
$selectedStates = $states[$selectedOrgLocation] ?? $states['India'];

render_header('Organization Setup', 'org-body');
?>
<div class="org-page">
    <div class="org-topbar">
        <div class="org-brand">
            <span class="org-brand-icon" aria-hidden="true"></span>
            <span>Procurement</span>
        </div>
    </div>

    <div class="org-shell">
        <div class="org-card">
            <div class="org-greeting">Hi <?= e($_SESSION['verified_signup']['business_name'] ?? 'there') ?>,</div>
            <h2>Let's get you up and running!</h2>

            <?php if (!empty($errors)): ?>
                <div class="notice error"><?= e(implode(' ', $errors)) ?></div>
            <?php endif; ?>

            <form method="post" class="org-form" data-org-form novalidate>
                <div class="org-row">
                    <div class="org-field<?= !empty($field_errors['organization_name']) ? ' is-invalid' : ''; ?>" data-field="organization_name">
                        <label>Organization Name*</label>
                        <input type="text" name="organization_name" class="org-input<?= !empty($field_errors['organization_name']) ? ' is-invalid' : ''; ?>" value="<?= e(old('organization_name')) ?>" required>
                        <p class="field-error" data-error-for="organization_name"><?= e($field_errors['organization_name'] ?? '') ?></p>
                    </div>
                </div>

                <div class="org-row two">
                    <div>
                        <label>Organization Location*</label>
                        <div class="org-select-wrap">
                            <select name="organization_location" id="orgCountrySelect" class="org-select">
                                <?php foreach ($countries as $item): ?>
                                    <option value="<?= e($item['name']) ?>" <?= $selectedOrgLocation === $item['name'] ? 'selected' : '' ?>>
                                        <?= e($item['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div>
                        <label>State/Union Territory*</label>
                        <div class="org-select-wrap">
                            <select name="state" id="orgStateSelect" class="org-select">
                                <?php foreach ($selectedStates as $item): ?>
                                    <option value="<?= e($item) ?>" <?= old('state') === $item ? 'selected' : '' ?>>
                                        <?= e($item) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>

                <a href="#" class="org-add-address">+ Add Organization Address</a>

                <div class="org-row">
                    <div class="org-field<?= !empty($field_errors['industry']) ? ' is-invalid' : ''; ?>" data-field="industry">
                        <label>Industry</label>
                        <div class="org-select-wrap">
                            <select name="industry" class="org-select<?= !empty($field_errors['industry']) ? ' is-invalid' : ''; ?>">
                                <option value="">Select</option>
                                <?php foreach ($industries as $item): ?>
                                    <option value="<?= e($item) ?>" <?= old('industry') === $item ? 'selected' : '' ?>><?= e($item) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <p class="field-error" data-error-for="industry"><?= e($field_errors['industry'] ?? '') ?></p>
                    </div>
                </div>

                <div class="org-settings">
                    <div><span>Base Currency*:</span> <strong><?= e(old('currency', 'INR - Indian Rupee')) ?></strong></div>
                    <div><span>Language*:</span> <strong><?= e(old('language', 'English')) ?></strong></div>
                    <div><span>Time Zone*:</span> <strong><?= e(old('timezone', '(GMT 5:30) India Standard Time (Asia/Kolkata)')) ?></strong></div>
                </div>

                <div class="org-grid">
                    <div>
                        <label>Base Currency*</label>
                        <div class="org-select-wrap">
                            <select name="currency" class="org-select">
                                <?php foreach ($currencies as $item): ?>
                                    <option value="<?= e($item) ?>" <?= old('currency', 'INR - Indian Rupee') === $item ? 'selected' : '' ?>><?= e($item) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div>
                        <label>Language*</label>
                        <div class="org-select-wrap">
                            <select name="language" class="org-select">
                                <?php foreach ($languages as $item): ?>
                                    <option value="<?= e($item) ?>" <?= old('language', 'English') === $item ? 'selected' : '' ?>><?= e($item) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div>
                        <label>Time Zone*</label>
                        <div class="org-select-wrap">
                            <select name="timezone" class="org-select">
                                <?php foreach ($timezones as $item): ?>
                                    <option value="<?= e($item) ?>" <?= old('timezone', '(GMT 5:30) India Standard Time (Asia/Kolkata)') === $item ? 'selected' : '' ?>><?= e($item) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="org-field<?= !empty($field_errors['terms']) ? ' is-invalid' : ''; ?>" data-field="terms">
                    <label class="org-check">
                        <input type="checkbox" name="terms" <?= isset($_POST['terms']) ? 'checked' : '' ?>>
                        <span>I agree to the <a href="#">Terms of Service</a> and <a href="#">Privacy Policy</a></span>
                    </label>
                    <p class="field-error" data-error-for="terms"><?= e($field_errors['terms'] ?? '') ?></p>
                </div>

                <button type="submit" class="save-btn">Save</button>
            </form>
        </div>
    </div>
</div>
<script>
window.PROCUREMENT_STATE_MAP = <?php echo json_encode($states, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
</script>
<?php render_footer(); ?>









