<?php
require __DIR__ . '/app/bootstrap.php';
require_auth();
header('Content-Type: application/json; charset=utf-8');
$id=strtoupper(trim((string)request('id')));
$purpose=trim((string)request('purpose'));
if(!preg_match('/^LXU-[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}$/',$id)){echo json_encode(['ok'=>false]);exit;}
$q=db()->prepare("SELECT id,name,role,avatar,phone,email,document,city,state,company_id,home_address,home_number,home_lat,home_lng FROM users WHERE upper(public_id)=upper(?) AND status='active' LIMIT 1");
$q->execute([$id]);
$target=$q->fetch();
if(!$target){echo json_encode(['ok'=>false],JSON_UNESCAPED_UNICODE);exit;}
if($purpose==='charge' && !can_issue_charge_to(current_user(),(int)$target['id'])){
    echo json_encode(['ok'=>false,'not_allowed'=>true,'message'=>'Este usuário não está vinculado à sua empresa/serviços.'],JSON_UNESCAPED_UNICODE);exit;
}
if($purpose==='pet_tutor'){
    $viewer=current_user();
    $companyId=is_super_admin()?(int)request('company_id',0):resolve_company_id_for_user($viewer);
    $allowed=$companyId>0 && company_is_petcare($companyId) && (is_super_admin() || (in_array((string)($viewer['role']??''),['company','employee'],true) && resolve_company_id_for_user($viewer)===$companyId));
    if(!$allowed){echo json_encode(['ok'=>false,'not_allowed'=>true,'message'=>'Sem permissão para consultar tutor nesta clínica.'],JSON_UNESCAPED_UNICODE);exit;}
    $address=trim((string)($target['home_address']??''));
    $number=trim((string)($target['home_number']??''));
    if($number!==''&&$address!=='')$address.=', '.$number;
    echo json_encode([
        'ok'=>true,
        'name'=>(string)($target['name']??''),
        'document'=>(string)($target['document']??''),
        'phone'=>only_digits((string)($target['phone']??'')),
        'whatsapp'=>only_digits((string)($target['phone']??'')),
        'email'=>(string)($target['email']??''),
        'address'=>$address,
        'city'=>(string)($target['city']??''),
        'state'=>(string)($target['state']??''),
        'message'=>'Cliente localizado. Os dados disponíveis foram preenchidos automaticamente.'
    ],JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);exit;
}

if($purpose==='delivery'){
    $viewer=current_user();
    $companyId=is_admin()?(int)request('company_id',0):resolve_company_id_for_user($viewer);
    if($companyId<1 && !is_admin()) $companyId=(int)($viewer['company_id']??0);
    $company=null;
    if($companyId>0){
        $cq=db()->prepare('SELECT id,name,address,address_number,latitude,longitude FROM companies WHERE id=? LIMIT 1');
        $cq->execute([$companyId]);
        $company=$cq->fetch();
    }

    $authorized=is_admin();
    if(!$authorized && $companyId>0){
        if((int)($target['company_id']??0)===$companyId) $authorized=true;
        if(!$authorized){
            $pq=db()->prepare("SELECT COUNT(*) FROM delivery_address_permissions WHERE company_id=? AND user_id=? AND always_visible=1 AND status='active'");
            $pq->execute([$companyId,(int)$target['id']]);
            $authorized=(int)$pq->fetchColumn()>0;
        }
        if(!$authorized && ($target['role']??'')==='company') $authorized=true;
    }

    $address='';$lat=null;$lng=null;
    if($authorized){
        $address=full_user_address($target);
        $lat=$target['home_lat']!==null?(float)$target['home_lat']:null;
        $lng=$target['home_lng']!==null?(float)$target['home_lng']:null;
        if(($target['role']??'')==='company' && (int)($target['company_id']??0)>0){
            $tc=db()->prepare('SELECT address,address_number,latitude,longitude FROM companies WHERE id=? LIMIT 1');
            $tc->execute([(int)$target['company_id']]);$tcRow=$tc->fetch();
            if($tcRow){
                $address=trim((string)$tcRow['address']);
                if(trim((string)$tcRow['address_number'])!=='' && $address!=='')$address.=', '.trim((string)$tcRow['address_number']);
                $lat=$tcRow['latitude']!==null?(float)$tcRow['latitude']:$lat;
                $lng=$tcRow['longitude']!==null?(float)$tcRow['longitude']:$lng;
            }
        }
    }

    $companyLat=$company&&$company['latitude']!==null?(float)$company['latitude']:null;
    $companyLng=$company&&$company['longitude']!==null?(float)$company['longitude']:null;
    $distance=null;
    if($authorized && $lat!==null && $lng!==null && $companyLat!==null && $companyLng!==null){
        $straight=distance_km($companyLat,$companyLng,$lat,$lng);
        if($straight!==null)$distance=round($straight*1.25,2);
    }
    echo json_encode([
        'ok'=>true,'name'=>$target['name'],'authorized'=>$authorized,
        'phone'=>$authorized?only_digits((string)($target['phone']??'')):'',
        'address'=>$authorized?$address:'','lat'=>$authorized?$lat:null,'lng'=>$authorized?$lng:null,
        'distance_km'=>$distance,
        'company_address'=>$company?trim((string)$company['address']).(trim((string)$company['address_number'])!==''?', '.trim((string)$company['address_number']):''):'',
        'company_lat'=>$companyLat,'company_lng'=>$companyLng,
        'message'=>$authorized?'Cliente localizado. Endereço e distância preenchidos.':'Cliente localizado. O endereço ainda depende da autorização do cliente.'
    ],JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);exit;
}

if($purpose==='ride_driver'){
    $type=trim((string)request('ride_type'));
    $compatible=($type==='mototaxi'&&$target['role']==='mototaxi')
        ||($type==='taxi'&&in_array($target['role'],['taxi','private_driver'],true))
        ||($type==='private_driver'&&in_array($target['role'],['private_driver','taxi'],true));
    if(!$compatible){
        echo json_encode(['ok'=>false,'not_allowed'=>true,'message'=>'O ID não pertence a um motorista/mototaxista compatível.'],JSON_UNESCAPED_UNICODE);exit;
    }
    echo json_encode(['ok'=>true,'name'=>$target['name'],'role'=>role_label($target['role']),'avatar'=>$target['avatar']?media_url($target['avatar']):''],JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);exit;
}
echo json_encode(['ok'=>true,'name'=>$target['name']],JSON_UNESCAPED_UNICODE);
