<?php
require_once __DIR__ . '/../app/bootstrap.php';

use App\Core\Auth;
use App\Core\Database;
use App\Core\Security;

if (Auth::check()) redirect(role_dashboard_url());
$role = ($_GET['role'] ?? $_POST['role'] ?? 'customer') === 'vendor' ? 'vendor' : 'customer';
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf()) $errors[] = 'Invalid security token. Refresh the page and try again.';
    $name = trim((string)($_POST['name'] ?? ''));
    $phone = trim((string)($_POST['phone'] ?? ''));
    $email = strtolower(trim((string)($_POST['email'] ?? '')));
    $password = (string)($_POST['password'] ?? '');
    $confirm = (string)($_POST['password_confirmation'] ?? '');
    $shopName = trim((string)($_POST['shop_name'] ?? ''));

    if ($name === '') $errors[] = 'Name is required.';
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Enter a valid email address.';
    if ($passwordError = Security::passwordError($password, $email)) $errors[] = $passwordError;
    if ($password !== $confirm) $errors[] = 'Password confirmation does not match.';
    if ($role === 'vendor' && $shopName === '') $errors[] = 'Shop name is required.';
    if (!Security::rateLimit('register:' . ($_SERVER['REMOTE_ADDR'] ?? ''), 5, 3600)) $errors[] = 'Too many registration attempts. Try again later.';
    if (Database::safeFetchOne('SELECT id FROM users WHERE LOWER(email)=? LIMIT 1', [$email])) $errors[] = 'An account with this email already exists.';

    if (!$errors) {
        try {
            $userId = Database::transaction(function() use ($role,$name,$email,$phone,$password,$shopName) {
                $status = $role === 'vendor' ? 'pending' : 'active';
                Database::execute('INSERT INTO users (role,name,email,phone,password_hash,status,created_at,updated_at) VALUES (?,?,?,?,?,?,NOW(),NOW())', [$role,$name,$email,$phone,password_hash($password, PASSWORD_DEFAULT),$status]);
                $userId = Database::lastInsertId();
                if ($role === 'vendor') {
                    Database::execute('INSERT INTO vendors (user_id,shop_name,slug,commission_type,commission_value,status,created_at,updated_at) VALUES (?,?,?,"percentage",5,"pending",NOW(),NOW())', [$userId,$shopName,unique_slug('vendors',$shopName)]);
                } else {
                    foreach (['cash','purchase','point','reward'] as $walletType) {
                        Database::safeExecute('INSERT INTO wallets (user_id,wallet_type,balance,created_at,updated_at) VALUES (?,?,0,NOW(),NOW())', [$userId,$walletType]);
                    }
                }
                return $userId;
            });
            Security::logActivity($userId, 'registration', ['role'=>$role]);
            if ($role === 'customer') {
                Auth::loginUser(['id'=>$userId,'role'=>'customer']);
                set_flash('success', 'Your account has been created.');
                redirect('customer/dashboard.php');
            }
            set_flash('success', 'Vendor registration submitted. You can log in after administrator approval.');
            redirect('public/login.php');
        } catch (Throwable $e) {
            error_log('Registration failed: ' . $e->getMessage());
            $errors[] = str_contains(strtolower($e->getMessage()), 'duplicate') ? 'That email or shop address is already registered.' : 'Registration could not be completed. Please try again.';
        }
    }
}

$pageTitle = 'Register | ' . BRAND_NAME;
include ROOT_PATH . '/app/Layouts/frontend_header.php';
?>
<section class="container py-5"><div class="row justify-content-center"><div class="col-lg-7"><div class="card border-0 shadow-sm"><div class="card-body p-4 p-lg-5">
<h3><?= $role === 'vendor' ? 'Vendor' : 'Customer' ?> Registration</h3>
<p class="text-muted"><?= $role === 'vendor' ? 'Vendor accounts require administrator approval.' : 'Create an account to track orders, wallet and rewards.' ?></p>
<?php foreach($errors as $error): ?><div class="alert alert-danger py-2"><?= e($error) ?></div><?php endforeach; ?>
<form method="post" novalidate><?= csrf_field() ?><input type="hidden" name="role" value="<?= e($role) ?>"><div class="row g-3">
<div class="col-md-6"><label class="form-label">Name</label><input name="name" class="form-control" value="<?= e($_POST['name'] ?? '') ?>" required></div>
<div class="col-md-6"><label class="form-label">Phone</label><input name="phone" class="form-control" value="<?= e($_POST['phone'] ?? '') ?>"></div>
<div class="col-12"><label class="form-label">Email</label><input type="email" name="email" class="form-control" value="<?= e($_POST['email'] ?? '') ?>" required></div>
<?php if($role === 'vendor'): ?><div class="col-12"><label class="form-label">Shop Name</label><input name="shop_name" class="form-control" value="<?= e($_POST['shop_name'] ?? '') ?>" required></div><?php endif; ?>
<div class="col-md-6"><label class="form-label">Password</label><input type="password" name="password" minlength="<?= PASSWORD_MIN_LENGTH ?>" class="form-control" required></div>
<div class="col-md-6"><label class="form-label">Confirm Password</label><input type="password" name="password_confirmation" minlength="<?= PASSWORD_MIN_LENGTH ?>" class="form-control" required></div>
</div><button class="btn btn-primary mt-4">Create Account</button> <a class="btn btn-link" href="<?= url('public/login.php') ?>">Already registered?</a></form>
</div></div></div></div></section>
<?php include ROOT_PATH . '/app/Layouts/frontend_footer.php'; ?>
