<?php
require __DIR__ . '/app/bootstrap.php';
$phone=whatsapp_digits(request('phone',''));
if($phone===''){http_response_code(400);exit('WhatsApp inválido.');}
$message=(string)request('message','');
$targetUserId=(int)request('user',0);$targetCompanyId=(int)request('company',0);$source=trim((string)request('source',''));
$local=$phone;
if(strlen($local)>11 && substr($local,0,2)==='55')$local=substr($local,2);
try{
    if($targetUserId<1){
        $q=db()->prepare("SELECT id FROM users WHERE replace(replace(replace(replace(replace(COALESCE(phone,''),'(',''),')',''),'-',''),' ',''),'+','') IN (?,?) ORDER BY CASE WHEN status='active' THEN 0 ELSE 1 END,id LIMIT 1");
        $q->execute([$local,$phone]);$targetUserId=(int)$q->fetchColumn();
    }
    if($targetCompanyId<1){
        $q=db()->prepare("SELECT id,owner_user_id FROM companies WHERE replace(replace(replace(replace(replace(COALESCE(phone,''),'(',''),')',''),'-',''),' ',''),'+','') IN (?,?) ORDER BY CASE WHEN status='active' THEN 0 ELSE 1 END,id LIMIT 1");
        $q->execute([$local,$phone]);$company=$q->fetch();
        if($company){$targetCompanyId=(int)$company['id'];if($targetUserId<1)$targetUserId=(int)$company['owner_user_id'];}
    }
    $visitor=current_user();
    db()->prepare('INSERT INTO whatsapp_clicks(visitor_user_id,target_user_id,target_company_id,phone,source,created_at) VALUES(?,?,?,?,?,?)')
      ->execute([$visitor?(int)$visitor['id']:null,$targetUserId?:null,$targetCompanyId?:null,$phone,$source?:null,now()]);
}catch(Throwable $ignored){}
$target='https://wa.me/'.$phone.($message!==''?'?text='.rawurlencode($message):'');
header('Location: '.$target,true,302);exit;
