<?php
session_start();
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(dirname(__DIR__)))); }
require_once BASE_PATH . '/database/connection.php';
header('Content-Type: application/json');
$db = Database::getInstance();
$pdo = $db->getConnection();
$clientId = $_SESSION['client_id'] ?? null;
if (!$clientId) { echo json_encode(['success'=>false,'message'=>'No autenticado']); exit; }
$action = $_GET['action'] ?? $_POST['action'] ?? '';
try {
  $pdo->exec("CREATE TABLE IF NOT EXISTS client_profiles (
    client_id INT PRIMARY KEY,
    address VARCHAR(255) NULL,
    address_number VARCHAR(32) NULL,
    country VARCHAR(8) NULL,
    country_name VARCHAR(100) NULL,
    state VARCHAR(64) NULL,
    city VARCHAR(64) NULL,
    postcode VARCHAR(32) NULL,
    neighbourhood VARCHAR(64) NULL,
    personal_id VARCHAR(64) NULL,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (client_id) REFERENCES clients(id) ON DELETE CASCADE
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Throwable $__) {}
if ($action === 'get') {
  try {
    $stC = $pdo->prepare('SELECT first_name,last_name,email,phone FROM clients WHERE id=? LIMIT 1');
    $stC->execute([$clientId]);
    $c = $stC->fetch() ?: [];
    $stP = $pdo->prepare('SELECT address,address_number,country,country_name,state,city,postcode,neighbourhood,personal_id FROM client_profiles WHERE client_id=? LIMIT 1');
    $stP->execute([$clientId]);
    $p = $stP->fetch() ?: [];
    $profile = array_merge([ 'first_name'=>'', 'last_name'=>'', 'email'=>'', 'phone'=>'', 'address'=>'', 'address_number'=>'', 'country'=>'', 'country_name'=>'', 'state'=>'', 'city'=>'', 'postcode'=>'', 'neighbourhood'=>'', 'personal_id'=>'' ], $c, $p);
    echo json_encode(['success'=>true,'profile'=>$profile]);
  } catch (Throwable $e) { echo json_encode(['success'=>false,'message'=>'Error cargando perfil']); }
  exit;
}
if ($action === 'save') {
  $first = trim($_POST['first_name'] ?? '');
  $last = trim($_POST['last_name'] ?? '');
  $email = trim($_POST['email'] ?? '');
  $phone = trim($_POST['phone'] ?? '');
  $address = trim($_POST['address'] ?? '');
  $num = trim($_POST['address_number'] ?? '');
  $country = strtoupper(trim($_POST['country'] ?? ''));
  $state = trim($_POST['state'] ?? '');
  $city = trim($_POST['city'] ?? '');
  $postcode = trim($_POST['postcode'] ?? '');
  $neigh = trim($_POST['neighbourhood'] ?? '');
  $pid = trim($_POST['personal_id'] ?? '');
  try {
    $u = $pdo->prepare('UPDATE clients SET first_name=?, last_name=?, email=?, phone=? WHERE id=?');
    $u->execute([$first, $last, $email, $phone, $clientId]);
    $sel = $pdo->prepare('SELECT client_id FROM client_profiles WHERE client_id=?');
    $sel->execute([$clientId]);
    if ($sel->fetch()) {
      $upd = $pdo->prepare('UPDATE client_profiles SET address=?, address_number=?, country=?, state=?, city=?, postcode=?, neighbourhood=?, personal_id=? WHERE client_id=?');
      $upd->execute([$address, $num, $country, $state, $city, $postcode, $neigh, $pid, $clientId]);
    } else {
      $ins = $pdo->prepare('INSERT INTO client_profiles (client_id,address,address_number,country,state,city,postcode,neighbourhood,personal_id) VALUES (?,?,?,?,?,?,?,?,?)');
      $ins->execute([$clientId, $address, $num, $country, $state, $city, $postcode, $neigh, $pid]);
    }
    echo json_encode(['success'=>true]);
  } catch (Throwable $e) { echo json_encode(['success'=>false,'message'=>'No se pudo guardar']); }
  exit;
}
echo json_encode(['success'=>false,'message'=>'Acción inválida']);
