<?php
session_start();
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/modules/shared/helpers.php';
if (!isset($_SESSION['client_id'])) { header('Location: ' . module_url('client_portal/login.php')); exit; }
$page_title = 'Perfil';
$active = 'perfil';
ob_start();
?>
<div class="client-page">
  <div class="section-header">
    <h2 class="section-title"><i class="fas fa-user"></i> Perfil</h2>
    <p class="section-sub">Completa y mantén tus datos actualizados</p>
  </div>
  <div class="card">
    <div class="card-body">
      <form id="profileForm">
        <div class="form-grid">
          <div class="form-row"><label>Nombre</label><input type="text" id="first_name" name="first_name" required placeholder="Nombre" /></div>
          <div class="form-row"><label>Apellido</label><input type="text" id="last_name" name="last_name" required placeholder="Apellido" /></div>
          <div class="form-row"><label>Email</label><input type="email" id="email" name="email" required placeholder="Email" readonly /></div>
          <div class="form-row"><label>Teléfono</label><input type="text" id="phone" name="phone" required placeholder="Teléfono" /></div>
          <div class="form-row"><label>Dirección</label><input type="text" id="address" name="address" placeholder="Dirección" /></div>
          <div class="form-row"><label>Número</label><input type="text" id="address_number" name="address_number" placeholder="Número" /></div>
          <div class="form-row"><label>País</label><select id="country" name="country"></select></div>
          <div class="form-row"><label>País (texto)</label><input type="text" id="country_name_display" name="country_name_display" placeholder="Nombre de país" readonly /></div>
          <div class="form-row"><label>Estado/Provincia</label><input type="text" id="state" name="state" placeholder="Estado" /></div>
          <div class="form-row"><label>Ciudad</label><input type="text" id="city" name="city" placeholder="Ciudad" /></div>
          <div class="form-row"><label>Código Postal</label><input type="text" id="postcode" name="postcode" placeholder="Código Postal" /></div>
          <div class="form-row full"><label>Barrio</label><input type="text" id="neighbourhood" name="neighbourhood" placeholder="Barrio" /></div>
          <div class="form-row full"><label>Documento (Personal ID)</label><input type="text" id="personal_id" name="personal_id" placeholder="Documento de identidad" /></div>
        </div>
        <div class="form-actions"><span id="formStatus" class="form-status" style="display:none"></span><button type="submit" class="btn btn-primary">Guardar cambios</button></div>
      </form>
    </div>
  </div>
</div>
<script>
const BASE_PFX = (location.pathname.indexOf('/simple_crm/')!==-1) ? '/simple_crm' : ''
function qs(id){ return document.getElementById(id) }
const countries = [
  {code:'US',name:'Estados Unidos'},{code:'MX',name:'México'},{code:'AR',name:'Argentina'},{code:'BR',name:'Brasil'},{code:'CL',name:'Chile'},{code:'CO',name:'Colombia'},{code:'PE',name:'Perú'},{code:'EC',name:'Ecuador'},{code:'UY',name:'Uruguay'},{code:'CR',name:'Costa Rica'},{code:'PA',name:'Panamá'},{code:'BO',name:'Bolivia'},{code:'ES',name:'España'},{code:'PT',name:'Portugal'},{code:'PY',name:'Paraguay'},{code:'SV',name:'El Salvador'},{code:'GT',name:'Guatemala'},{code:'HN',name:'Honduras'},{code:'NI',name:'Nicaragua'},{code:'DO',name:'República Dominicana'}
]
function renderCountries(selId, val){ const sel = qs(selId); if(!sel) return; sel.innerHTML = countries.map(c => `<option value="${c.code}" ${String(val||'').toUpperCase()===c.code?'selected':''}>${c.name}</option>`).join('') }
function loadProfile(){ return fetch(BASE_PFX + '/modules/client_portal/api/profile.php?action=get', { headers:{'Accept':'application/json'} }).then(r=>r.json()) }
function saveProfile(data){ return fetch(BASE_PFX + '/modules/client_portal/api/profile.php?action=save', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body: new URLSearchParams(data).toString() }).then(r=>r.json()) }
document.addEventListener('DOMContentLoaded', ()=>{
  renderCountries('country', '')
  loadProfile().then(d=>{ if (d && d.success){ const p = d.profile||{}; ['first_name','last_name','email','phone','address','address_number','state','city','postcode','neighbourhood','personal_id'].forEach(k=>{ if (qs(k)) qs(k).value = p[k]||'' }); renderCountries('country', p.country||''); if (qs('country_name_display')) { qs('country_name_display').value = p.country_name || (countries.find(c=>c.code===String(p.country||'').toUpperCase())||{}).name || '' } } })
  qs('profileForm').addEventListener('submit', (ev)=>{ ev.preventDefault(); const s = qs('formStatus'); s.style.display='none'; const data = { first_name:qs('first_name').value, last_name:qs('last_name').value, email:qs('email').value, phone:qs('phone').value, address:qs('address').value, address_number:qs('address_number').value, country:qs('country').value, state:qs('state').value, city:qs('city').value, postcode:qs('postcode').value, neighbourhood:qs('neighbourhood').value, personal_id:qs('personal_id').value }; saveProfile(data).then(d=>{ s.style.display='block'; if (d && d.success){ s.className='form-status success'; s.textContent='Perfil actualizado'; } else { s.className='form-status error'; s.textContent = d && d.message ? d.message : 'Error al guardar'; } }).catch(()=>{ s.style.display='block'; s.className='form-status error'; s.textContent='Error de conexión'; }) })
})
</script>
<style>
.client-page .section-header{display:flex;flex-direction:column;gap:6px;margin-bottom:12px}
.section-title{font-weight:800;display:flex;gap:8px;align-items:center}
.section-sub{color:#6b7280}
.card{border:1px solid #e5e7eb;border-radius:16px;background:#fff;box-shadow:0 10px 24px rgba(0,0,0,.06)}
.card-body{padding:16px}
.form-grid{display:grid;grid-template-columns:repeat(12,1fr);gap:14px}
.form-row{display:flex;flex-direction:column;gap:6px;grid-column:span 6}
.form-row.full{grid-column:span 12}
.form-row label{font-weight:600;color:#334155}
.form-row input,.form-row select{height:44px;border:1px solid #e5e7eb;border-radius:12px;padding:10px 14px;background:#f9fafb}
.form-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:12px}
.btn.btn-primary{background:linear-gradient(180deg,#3b82f6,#2563eb);border:0;border-radius:12px;padding:10px 16px;color:#fff}
.form-status{margin-right:auto;padding:8px 12px;border-radius:10px}
.form-status.success{background:#ecfdf5;color:#065f46}
.form-status.error{background:#fee2e2;color:#7f1d1d}
@media (max-width:1024px){.form-row{grid-column:span 12}}
</style>
<?php
$content = ob_get_clean();
include BASE_PATH . '/modules/client_portal/layout.php';
?>
