<?php
require __DIR__ . '/app/bootstrap.php';
require __DIR__ . '/app/layout.php';
if (current_user()) { $cu=current_user(); redirect(user_needs_onboarding($cu)?'complete_registration.php':(pending_integration_invite()?'integration_join.php':(pending_company_join_invite()?'company_join.php':(pending_provider_join_invite()?'provider_join.php':'dashboard.php')))); }
if (setting('allow_public_registration','1') !== '1') { http_response_code(403); exit('Cadastros públicos estão temporariamente desativados.'); }
$error='';
if($_SERVER['REQUEST_METHOD']==='POST'){
    verify_csrf();
    $accountKind=request('account_kind','personal');
    $email=strtolower(trim((string)request('email')));
    $password=(string)request('password');
    if(!in_array($accountKind,['personal','company'],true))$error='Escolha o tipo de conta.';
    elseif(!filter_var($email,FILTER_VALIDATE_EMAIL))$error='Informe um e-mail válido.';
    elseif(strlen($password)<6)$error='A senha precisa ter pelo menos 6 caracteres.';
    else{
        $q=db()->prepare('SELECT COUNT(*) FROM users WHERE lower(email)=lower(?)');$q->execute([$email]);
        if((int)$q->fetchColumn()>0)$error='Já existe uma conta com este e-mail.';
        else{
            $role=$accountKind==='company'?'company':'client';
            $prefix=trim((string)strtok($email,'@'));
            $name=$prefix!==''?ucwords(str_replace(['.','_','-'],' ',$prefix)):'Novo cadastro';
            db()->prepare('INSERT INTO users(role,name,email,password_hash,status,work_status,profile_completed,account_kind,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?)')
                ->execute([$role,$name,$email,password_hash($password,PASSWORD_DEFAULT),'active','offline',0,$accountKind,now(),now()]);
            $id=(int)db()->lastInsertId();ensure_public_user_id($id);
            session_regenerate_id(true);$_SESSION['user_id']=$id;
            log_activity('registration_step1','users',$id,'Conta iniciada em duas etapas');
            flash('success','Conta criada. Agora complete seus dados para liberar o acesso.');
            redirect('complete_registration.php');
        }
    }
}
render_public_header('Criar conta');
?>
<section class="auth-shell"><div class="auth-card" style="width:min(650px,100%)">
  <span class="hero-badge"><i></i> Etapa 1 de 2</span>
  <h1>Abra sua conta</h1>
  <p>Primeiro escolha o tipo de conta e defina e-mail e senha. A conta é criada imediatamente; o painel só será liberado depois que você concluir seus dados na etapa 2.</p>
  <?php if($error):?><div class="alert alert-error"><?= e($error) ?></div><?php endif;?>
  <form method="post"><?= csrf_field() ?>
    <div class="account-kind-grid">
      <label class="account-kind-card"><input type="radio" name="account_kind" value="personal"<?= request('account_kind','personal')==='personal'?' checked':'' ?>><span class="account-kind-icon">👤</span><span class="account-kind-copy"><strong>Conta de Cliente / Pessoa</strong><small>Cliente, motorista, entregador, prestador e outros perfis pessoais.</small></span></label>
      <label class="account-kind-card"><input type="radio" name="account_kind" value="company"<?= request('account_kind')==='company'?' checked':'' ?>><span class="account-kind-icon">🏢</span><span class="account-kind-copy"><strong>Conta Empresarial</strong><small>Empresa com cadastro completo, incluindo clínicas, segmento e dados do estabelecimento.</small></span></label>
    </div>
    <div class="form-grid" style="margin-top:18px">
      <div class="form-group full"><label>E-mail</label><input class="input" type="email" name="email" value="<?= e(request('email')) ?>" required autocomplete="email"></div>
      <div class="form-group full"><label>Senha</label><input class="input" type="password" name="password" minlength="6" required autocomplete="new-password"><small>Mínimo de 6 caracteres.</small></div>
    </div>
    <div class="form-actions"><a class="muted" href="login.php">Já tenho conta</a><button class="btn btn-primary" type="submit">Criar conta e continuar →</button></div>
  </form>
</div></section>
<?php render_public_footer(); ?>
