<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../lib/auth.php';
require_once __DIR__ . '/../lib/csrf.php';
require_once __DIR__ . '/../lib/validation.php';

if (isLoggedIn()) {
    header('Location: /dashboard/dashboard.php');
    exit;
}

$errors = [];
$old    = []; // repopulate form fields on error

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $errors['general'] = 'Invalid request. Please try again.';
    } else {
        $old = $_POST;

        // --- Validation ---
        $fullname    = sanitizeString($_POST['fullname']    ?? '', 255);
        $email       = sanitizeString($_POST['email']       ?? '', 255);
        $company     = sanitizeString($_POST['company']     ?? '', 255);
        $mobilephone = sanitizeString($_POST['mobilephone'] ?? '', 50);
        $industry    = $_POST['industry']  ?? '';
        $role        = $_POST['role']      ?? '';
        $city        = sanitizeString($_POST['city']     ?? '', 100);
        $state       = $_POST['state']     ?? '';
        $postcode    = sanitizeString($_POST['postcode'] ?? '', 20);
        $country     = $_POST['country']   ?? 'Australia';
        $password    = $_POST['password']         ?? '';
        $password2   = $_POST['password_confirm'] ?? '';

        if ($fullname === '')    $errors['fullname']    = 'Full name is required.';
        if ($email === '')       $errors['email']       = 'Email is required.';
        elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors['email'] = 'Please enter a valid email.';
        if ($mobilephone === '') $errors['mobilephone'] = 'Mobile phone is required.';
        if ($password === '')    $errors['password']    = 'Password is required.';
        elseif (strlen($password) < 8) $errors['password'] = 'Password must be at least 8 characters.';
        if ($password !== $password2) $errors['password_confirm'] = 'Passwords do not match.';

        $allowedIndustries = ['Broadacre','Viticulture','Horticulture','Permaculture','Dairy'];
        $allowedRoles      = ['Manager','Viticulturist','Horticulturist','Permaculturist','Irrigation Manager'];
        $allowedStates     = ['New South Wales','Victoria','Queensland','Western Australia','South Australia','Tasmania','Australian Capital Territory','Northern Territory','Other'];
        $allowedCountries  = ['Australia','New Zealand'];

        if (!in_array($industry, $allowedIndustries, true)) $errors['industry'] = 'Please select an industry.';
        if (!in_array($role,     $allowedRoles,      true)) $errors['role']     = 'Please select a role.';
        if (!in_array($state,    $allowedStates,     true)) $errors['state']    = 'Please select a state.';
        if (!in_array($country,  $allowedCountries,  true)) $country = 'Australia';

        if (empty($errors)) {
            $result = registerUser([
                'fullname'    => $fullname,
                'email'       => $email,
                'company'     => $company,
                'mobilephone' => $mobilephone,
                'industry'    => $industry,
                'role'        => $role,
                'city'        => $city,
                'state'       => $state,
                'postcode'    => $postcode,
                'country'     => $country,
                'password'    => $password,
            ]);

            if ($result['success']) {
                // Auto-login after registration
                loginUser($email, $password);
                header('Location: /dashboard/dashboard.php?registered=1');
                exit;
            } else {
                $errors['email'] = $result['error'];
            }
        }
    }
}

$pageTitle = 'Create an Account';
include __DIR__ . '/_head.php';

// Helper: old value for text inputs
$v = fn(string $key) => htmlspecialchars($old[$key] ?? '', ENT_QUOTES, 'UTF-8');
// Helper: re-select dropdown option
$sel = fn(string $key, string $val) => (($old[$key] ?? '') === $val) ? 'selected' : '';
?>

<div class="container">
    <div class="card o-hidden border-0 shadow-lg my-5">
        <div class="card-body p-0">
            <div class="row">
                <div class="col-lg-5 d-none d-lg-block bg-register-image"></div>
                <div class="col-lg-7">
                    <div class="p-5">
                        <div class="text-center mb-4">
                            <h1 class="h4 text-gray-900">Create an Account</h1>
                        </div>

                        <?php if (!empty($errors['general'])): ?>
                            <div class="alert alert-danger"><?= htmlspecialchars($errors['general'], ENT_QUOTES, 'UTF-8') ?></div>
                        <?php endif; ?>

                        <form method="POST" action="/login/register.php" novalidate>
                            <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">

                            <!-- Name + Company -->
                            <div class="row mb-3">
                                <div class="col-md-6 mb-2 mb-md-0">
                                    <input type="text" name="fullname" class="form-control form-control-user <?= isset($errors['fullname']) ? 'is-invalid' : '' ?>"
                                           placeholder="Full Name *" value="<?= $v('fullname') ?>" required>
                                    <?php if (isset($errors['fullname'])): ?>
                                        <span class="error"><?= htmlspecialchars($errors['fullname'], ENT_QUOTES, 'UTF-8') ?></span>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-6">
                                    <input type="text" name="company" class="form-control form-control-user"
                                           placeholder="Company Name" value="<?= $v('company') ?>">
                                </div>
                            </div>

                            <!-- Email -->
                            <div class="mb-3">
                                <input type="email" name="email" class="form-control form-control-user <?= isset($errors['email']) ? 'is-invalid' : '' ?>"
                                       placeholder="Email Address *" value="<?= $v('email') ?>" required>
                                <?php if (isset($errors['email'])): ?>
                                    <span class="error"><?= htmlspecialchars($errors['email'], ENT_QUOTES, 'UTF-8') ?></span>
                                <?php endif; ?>
                            </div>

                            <!-- Mobile -->
                            <div class="mb-3">
                                <input type="tel" name="mobilephone" class="form-control form-control-user <?= isset($errors['mobilephone']) ? 'is-invalid' : '' ?>"
                                       placeholder="Mobile Phone *" value="<?= $v('mobilephone') ?>">
                                <?php if (isset($errors['mobilephone'])): ?>
                                    <span class="error"><?= htmlspecialchars($errors['mobilephone'], ENT_QUOTES, 'UTF-8') ?></span>
                                <?php endif; ?>
                            </div>

                            <!-- Industry + Role -->
                            <div class="row mb-3">
                                <div class="col-md-6 mb-2 mb-md-0">
                                    <select name="industry" class="form-control form-control-user <?= isset($errors['industry']) ? 'is-invalid' : '' ?>">
                                        <option value="">Choose your industry *</option>
                                        <option value="Broadacre"    <?= $sel('industry','Broadacre') ?>>Broadacre</option>
                                        <option value="Viticulture"  <?= $sel('industry','Viticulture') ?>>Viticulture</option>
                                        <option value="Horticulture" <?= $sel('industry','Horticulture') ?>>Horticulture</option>
                                        <option value="Permaculture" <?= $sel('industry','Permaculture') ?>>Permaculture</option>
                                        <option value="Dairy"        <?= $sel('industry','Dairy') ?>>Dairy</option>
                                    </select>
                                    <?php if (isset($errors['industry'])): ?>
                                        <span class="error"><?= htmlspecialchars($errors['industry'], ENT_QUOTES, 'UTF-8') ?></span>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-6">
                                    <select name="role" class="form-control form-control-user <?= isset($errors['role']) ? 'is-invalid' : '' ?>">
                                        <option value="">Choose your role *</option>
                                        <option value="Manager"            <?= $sel('role','Manager') ?>>Manager</option>
                                        <option value="Viticulturist"      <?= $sel('role','Viticulturist') ?>>Viticulturist</option>
                                        <option value="Horticulturist"     <?= $sel('role','Horticulturist') ?>>Horticulturist</option>
                                        <option value="Permaculturist"     <?= $sel('role','Permaculturist') ?>>Permaculturist</option>
                                        <option value="Irrigation Manager" <?= $sel('role','Irrigation Manager') ?>>Irrigation Manager</option>
                                    </select>
                                    <?php if (isset($errors['role'])): ?>
                                        <span class="error"><?= htmlspecialchars($errors['role'], ENT_QUOTES, 'UTF-8') ?></span>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- City + State -->
                            <div class="row mb-3">
                                <div class="col-md-6 mb-2 mb-md-0">
                                    <input type="text" name="city" class="form-control form-control-user"
                                           placeholder="City" value="<?= $v('city') ?>">
                                </div>
                                <div class="col-md-6">
                                    <select name="state" class="form-control form-control-user <?= isset($errors['state']) ? 'is-invalid' : '' ?>">
                                        <option value="">State *</option>
                                        <option value="New South Wales"          <?= $sel('state','New South Wales') ?>>New South Wales</option>
                                        <option value="Victoria"                 <?= $sel('state','Victoria') ?>>Victoria</option>
                                        <option value="Queensland"               <?= $sel('state','Queensland') ?>>Queensland</option>
                                        <option value="Western Australia"        <?= $sel('state','Western Australia') ?>>Western Australia</option>
                                        <option value="South Australia"          <?= $sel('state','South Australia') ?>>South Australia</option>
                                        <option value="Tasmania"                 <?= $sel('state','Tasmania') ?>>Tasmania</option>
                                        <option value="Australian Capital Territory" <?= $sel('state','Australian Capital Territory') ?>>ACT</option>
                                        <option value="Northern Territory"       <?= $sel('state','Northern Territory') ?>>Northern Territory</option>
                                        <option value="Other"                    <?= $sel('state','Other') ?>>Other</option>
                                    </select>
                                    <?php if (isset($errors['state'])): ?>
                                        <span class="error"><?= htmlspecialchars($errors['state'], ENT_QUOTES, 'UTF-8') ?></span>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Postcode + Country -->
                            <div class="row mb-3">
                                <div class="col-md-6 mb-2 mb-md-0">
                                    <input type="text" name="postcode" class="form-control form-control-user"
                                           placeholder="Post Code" value="<?= $v('postcode') ?>">
                                </div>
                                <div class="col-md-6">
                                    <select name="country" class="form-control form-control-user">
                                        <option value="Australia"    <?= $sel('country','Australia') ?>>Australia</option>
                                        <option value="New Zealand"  <?= $sel('country','New Zealand') ?>>New Zealand</option>
                                    </select>
                                </div>
                            </div>

                            <!-- Password -->
                            <div class="row mb-3">
                                <div class="col-md-6 mb-2 mb-md-0">
                                    <input type="password" name="password" class="form-control form-control-user <?= isset($errors['password']) ? 'is-invalid' : '' ?>"
                                           placeholder="Password * (min 8 chars)" required>
                                    <?php if (isset($errors['password'])): ?>
                                        <span class="error"><?= htmlspecialchars($errors['password'], ENT_QUOTES, 'UTF-8') ?></span>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-6">
                                    <input type="password" name="password_confirm" class="form-control form-control-user <?= isset($errors['password_confirm']) ? 'is-invalid' : '' ?>"
                                           placeholder="Repeat Password *" required>
                                    <?php if (isset($errors['password_confirm'])): ?>
                                        <span class="error"><?= htmlspecialchars($errors['password_confirm'], ENT_QUOTES, 'UTF-8') ?></span>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <button type="submit" class="btn btn-success btn-user w-100 mb-3">
                                Register Account
                            </button>
                        </form>

                        <hr>
                        <div class="text-center">
                            <a class="small" href="/login/forgot-password.php">Forgot Password?</a>
                        </div>
                        <div class="text-center">
                            <a class="small" href="/login/login.php">Already have an account? Login!</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include __DIR__ . '/_foot.php'; ?>
