<?php
require __DIR__ . '/app/bootstrap.php';
require __DIR__ . '/app/layout.php';
require_auth();
$u=current_user();
if(!user_needs_onboarding($u))redirect('dashboard.php');
$error='';
$accountKind=(string)($u['account_kind']??'personal');
if(!in_array($accountKind,['personal','company'],true))$accountKind=($u['role']==='company'?'company':'personal');
$personalRoles=registration_personal_roles();
$allSegments=db()->query("SELECT * FROM segments WHERE status='active' ORDER BY sort_order,name")->fetchAll();
$terms=required_platform_terms();
$planOptions=db()->query("SELECT id,name,price,duration_days FROM plans WHERE status='active' ORDER BY price,name")->fetchAll();

if($_SERVER['REQUEST_METHOD']==='POST'){
    verify_csrf();
    $name=trim((string)request('name'));
    $phone=only_digits(request('phone'));
    $document=request('document');
    $city=trim((string)request('city'));
    $state=normalize_state(request('state'));
    $address=trim((string)request('home_address'));
    $number=trim((string)request('home_number'));
    $instagram=normalize_social_handle(request('instagram'));
    $telegram=normalize_social_handle(request('telegram'));
    $role=$accountKind==='company'?'company':(string)request('role','client');
    $segmentSlug=trim((string)request('segment_slug'));
    $requestedPlanId=(int)request('requested_plan_id',0);
    if($requestedPlanId>0){$pq=db()->prepare("SELECT COUNT(*) FROM plans WHERE id=? AND status='active'");$pq->execute([$requestedPlanId]);if(!(int)$pq->fetchColumn())$requestedPlanId=0;}
    if($name===''||strlen($name)<3)$error='Informe seu nome completo.';
    elseif($phone==='')$error='Informe seu WhatsApp.';
    elseif($city===''||$state==='')$error='Informe sua cidade e estado.';
    elseif($address==='')$error='Informe seu endereço.';
    elseif($accountKind==='personal'&&!in_array($role,$personalRoles,true))$error='Perfil inválido.';
    else{
        try{$document=validate_document_or_throw($document,(int)$u['id']);}catch(Throwable $e){$error=$e->getMessage();}
    }
    if($error===''){
        foreach($terms as $term){if((string)request('term_'.(int)$term['id'])!=='1'){$error='Você precisa aceitar todos os termos e políticas obrigatórios.';break;}}
    }
    $needsSegment=$accountKind==='company'||$role!=='client';
    if($error===''&&$needsSegment){
        $valid=false;foreach($allSegments as $seg){if($seg['slug']===$segmentSlug&&segment_allows_role($seg,$role)){$valid=true;break;}}
        if(!$valid)$error='Escolha um segmento compatível com seu perfil.';
    }
    if($error===''){
        $status=($accountKind==='personal'&&$role==='client')?'active':'pending';
        $expires=$role==='client'?date('Y-m-d',strtotime('+30 days')):null;
        db()->beginTransaction();
        try{
            db()->prepare('UPDATE users SET role=?,name=?,phone=?,document=?,status=?,subscription_expires_at=?,city=?,state=?,home_address=?,home_number=?,home_lat=?,home_lng=?,instagram=?,telegram=?,segment_slug=?,profile_completed=1,identity_edit_unlocked=0,updated_at=? WHERE id=?')
              ->execute([$role,$name,$phone,$document,$status,$expires,$city,$state,$address,$number,request('home_lat')?:null,request('home_lng')?:null,$instagram,$telegram,$role==='client'?null:$segmentSlug,now(),$u['id']]);
            $companyId=0;
            if($accountKind==='company'){
                $companyName=trim((string)request('company_name'));
                if($companyName==='')throw new RuntimeException('Informe o nome da empresa.');
                $slug=preg_replace('/[^a-z0-9]+/','-',strtolower((string)iconv('UTF-8','ASCII//TRANSLIT//IGNORE',$companyName)));$slug=trim($slug,'-').'-'.(int)$u['id'];
                db()->prepare('INSERT INTO companies(owner_user_id,type,name,slug,document,phone,email,address,address_number,city,state,latitude,longitude,instagram,telegram,status,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)')
                  ->execute([$u['id'],$segmentSlug,$companyName,$slug,$document,$phone,$u['email'],$address,$number,$city,$state,request('home_lat')?:null,request('home_lng')?:null,$instagram,$telegram,'pending',now(),now()]);
                $companyId=(int)db()->lastInsertId();
                db()->prepare('UPDATE users SET company_id=? WHERE id=?')->execute([$companyId,$u['id']]);
            }
            if($requestedPlanId>0){
                db()->prepare('INSERT INTO plan_requests(user_id,company_id,target_plan_id,request_type,status,user_notes,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?)')
                  ->execute([$u['id'],$companyId?:null,$requestedPlanId,'initial','pending','Solicitado ao concluir o cadastro público.',now(),now()]);
            }
            foreach($terms as $term){
                db()->prepare('INSERT OR IGNORE INTO term_acceptances(user_id,term_id,term_version,accepted_at,ip_address) VALUES(?,?,?,?,?)')
                  ->execute([$u['id'],$term['id'],$term['version'],now(),$_SERVER['REMOTE_ADDR']??'']);
            }
            db()->commit();
            $joinedCompanyName='';$joinedProviderName='';$joinedIntegrationName='';$joinInviteError='';
            if(pending_integration_invite()){
                try{$pendingInvite=pending_integration_invite();$joinedIntegration=grant_integration_access_from_invite((int)$u['id'],(int)$pendingInvite['link_id']);$joinedIntegrationName=(string)($joinedIntegration['title']??'');clear_pending_integration_invite();}
                catch(Throwable $joinError){$joinInviteError=$joinError->getMessage();clear_pending_integration_invite();}
            }
            if(pending_company_join_invite()){
                try{$pendingInvite=pending_company_join_invite();$joinedCompany=link_client_to_company_from_invite((int)$u['id'],(int)$pendingInvite['company_id'],(int)($pendingInvite['module_link_id']??0));$joinedCompanyName=(string)($joinedCompany['name']??'');clear_pending_company_join_invite();}
                catch(Throwable $joinError){$joinInviteError=$joinError->getMessage();clear_pending_company_join_invite();}
            }
            if(pending_provider_join_invite()){
                try{$pendingInvite=pending_provider_join_invite();$joinedProvider=link_user_to_provider_from_invite((int)$u['id'],(int)$pendingInvite['provider_id']);$joinedProviderName=(string)($joinedProvider['name']??'');clear_pending_provider_join_invite();}
                catch(Throwable $joinError){$joinInviteError=trim($joinInviteError.' '.$joinError->getMessage());clear_pending_provider_join_invite();}
            }
            $label=$accountKind==='company'?('Empresa '.$name):role_label($role).' '.$name;
            notify_super_admins('Cadastro concluído',$label.' concluiu a segunda etapa do cadastro.',$status==='active'?'success':'warning',0,'dashboard.php?page=users','user',(int)$u['id']);
            if($requestedPlanId>0)notify_super_admins('Solicitação de plano',$name.' solicitou um plano ao concluir o cadastro.','warning',0,'dashboard.php?page=subscriptions','plan_request',(int)$u['id']);
            log_activity('registration_step2','users',(int)$u['id'],'Cadastro completo em duas etapas');
            if($status==='active'){
                $joinedName=$joinedIntegrationName!==''?$joinedIntegrationName:($joinedCompanyName!==''?$joinedCompanyName:$joinedProviderName);
                flash('success',$joinedName!==''?'Cadastro concluído e vínculo confirmado com '.$joinedName.'.':'Cadastro concluído. Bem-vindo à '.platform_name().'!');
                if($joinInviteError!=='')flash('warning','Sua conta foi concluída, mas o vínculo por QR Code não pôde ser feito: '.$joinInviteError);
                redirect('dashboard.php');
            }
            // Perfis profissionais e empresas dependem da aprovação administrativa.
            logout_user();
            session_name(config('session_name'));session_start();
            flash('success','Cadastro concluído! Agora aguarde a aprovação do administrador para acessar o painel.');
            redirect('login.php');
        }catch(Throwable $e){if(db()->inTransaction())db()->rollBack();$error=$e->getMessage();}
    }
}
render_public_header('Concluir cadastro');
?>
<section class="auth-shell"><div class="auth-card" style="width:min(860px,100%)">
  <span class="hero-badge"><i></i> Etapa 2 de 2</span><h1>Complete seu cadastro</h1>
  <p>Seu e-mail já está registrado. Preencha os dados abaixo e aceite os termos para finalizar.</p>
  <?php if($error):?><div class="alert alert-error"><?= e($error) ?></div><?php endif;?>
  <form method="post" data-registration-complete-form><?= csrf_field() ?>
    <div class="form-grid">
      <div class="form-group"><label>Nome completo<?= $accountKind==='company'?' do responsável':'' ?></label><input class="input" name="name" value="<?= e(request('name',$u['name'])) ?>" required></div>
      <?php if($accountKind==='company'):?><div class="form-group"><label>Nome da empresa</label><input class="input" name="company_name" value="<?= e(request('company_name')) ?>" required></div><?php endif;?>
      <?php if($accountKind==='personal'):?><div class="form-group"><label>Perfil de cadastro</label><select name="role" data-registration-role required><?php foreach($personalRoles as $r):?><option value="<?= e($r) ?>"<?= selected(request('role','client'),$r) ?>><?= role_icon($r).' '.e(role_label($r)) ?></option><?php endforeach;?></select></div><?php else:?><input type="hidden" name="role" value="company"><?php endif;?>
      <div class="form-group" data-registration-segment-wrap<?= ($accountKind==='personal'&&request('role','client')==='client')?' style="display:none"':'' ?>><label>Segmento relacionado ao perfil</label><select name="segment_slug" data-registration-segment><option value="">Selecione</option><?php foreach($allSegments as $seg):?><option value="<?= e($seg['slug']) ?>" data-roles="<?= e(implode(',',segment_allowed_roles($seg))) ?>"<?= selected(request('segment_slug'),$seg['slug']) ?>><?= e(($seg['icon']?:'•').' '.$seg['name']) ?></option><?php endforeach;?></select><small>São exibidos somente segmentos compatíveis com o perfil escolhido.</small></div>
      <div class="form-group"><label>WhatsApp</label><input class="input" name="phone" data-phone-mask value="<?= e(request('phone')) ?>" required></div>
      <div class="form-group"><label>CPF/CNPJ</label><input class="input" name="document" data-document-mask inputmode="numeric" value="<?= e(request('document')) ?>" required></div>
      <div class="form-group"><label>Instagram</label><input class="input" name="instagram" value="<?= e(request('instagram')) ?>" placeholder="@usuario"></div>
      <div class="form-group"><label>Telegram</label><input class="input" name="telegram" value="<?= e(request('telegram')) ?>" placeholder="@usuario"></div>
      <div class="form-group"><label>Cidade</label><input class="input" name="city" value="<?= e(request('city',setting('platform_city'))) ?>" required></div>
      <div class="form-group"><label>Estado</label><input class="input" name="state" maxlength="2" data-state-mask value="<?= e(request('state',setting('platform_state'))) ?>" required></div>
      <div class="form-group full"><label>Endereço</label><div class="inline-filter"><input class="input" name="home_address" data-address-autocomplete data-lat-field="home_lat" data-lng-field="home_lng" value="<?= e(request('home_address')) ?>" required><button class="btn btn-secondary" type="button" data-geolocate-form data-address-field="home_address" data-lat-field="home_lat" data-lng-field="home_lng">📍 Localizar</button></div><input type="hidden" name="home_lat" value="<?= e(request('home_lat')) ?>"><input type="hidden" name="home_lng" value="<?= e(request('home_lng')) ?>"></div>
      <div class="form-group"><label>Número</label><input class="input" name="home_number" value="<?= e(request('home_number')) ?>"></div>
      <div class="form-group full"><label>Plano desejado (opcional)</label><select name="requested_plan_id"><option value="">Escolher depois</option><?php foreach($planOptions as $plan):?><option value="<?= (int)$plan['id'] ?>"<?= selected(request('requested_plan_id'),$plan['id']) ?>><?= e($plan['name']) ?> — <?= money($plan['price']) ?> / <?= (int)$plan['duration_days'] ?> dias</option><?php endforeach;?></select><small>A solicitação do plano continua passando pela aprovação administrativa.</small></div>
    </div>

    <section class="terms-accept-box">
      <h3>Termos e políticas</h3><p>Leia os documentos abaixo e marque cada quadrado para confirmar sua aceitação.</p>
      <?php if(!$terms):?><div class="notice">Não há termos obrigatórios ativos neste momento.</div><?php endif;?>
      <?php foreach($terms as $term):?><label class="term-check"><input type="checkbox" name="term_<?= (int)$term['id'] ?>" value="1"<?= request('term_'.(int)$term['id'])==='1'?' checked':'' ?> required><span><strong><?= e($term['title']) ?></strong><small>Versão <?= (int)$term['version'] ?> • <a href="terms.php#term-<?= (int)$term['id'] ?>" target="_blank" rel="noopener">Ler documento completo</a></small></span></label><?php endforeach;?>
    </section>
    <div class="form-actions"><a class="muted" href="logout.php">Sair e continuar depois</a><button class="btn btn-primary">Concluir cadastro</button></div>
  </form>
</div></section>
<?php render_public_footer(); ?>
