<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(dirname(__DIR__)))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/modules/shared/helpers.php';

function redirect_back($msgKey, $ok=true){
  $loc = module_url('client_portal/dashboard.php');
  $sep = (strpos($loc,'?')===false)?'?':'&';
  header('Location: ' . $loc . $sep . 'message=' . urlencode($msgKey));
  exit;
}

if (!isset($_SESSION['client_id'])) { redirect_back('not_authenticated', false); }
$cid = (int)$_SESSION['client_id'];

$first_name = trim($_POST['first_name'] ?? '');
$last_name = trim($_POST['last_name'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$address_line = trim($_POST['address_line'] ?? '');
$country = trim($_POST['country'] ?? '');
$phone_country_code = trim($_POST['phone_country_code'] ?? '');
$country_code = strtoupper(trim($_POST['country_code'] ?? ''));
$state = trim($_POST['state'] ?? '');
$city = trim($_POST['city'] ?? '');
$postal_code = trim($_POST['postal_code'] ?? '');
$district = trim($_POST['district'] ?? '');
$document_number = trim($_POST['document_number'] ?? '');

$required = [$first_name,$last_name,$email,$phone,$address_line,$country,$phone_country_code,$document_number];
foreach($required as $r){ if($r===''){ redirect_back('profile_missing'); }
}

$db = Database::getInstance();
$pdo = $db->getConnection();
$errors = [];

// Asegurar columnas requeridas en producción si faltan
$needCols = [
  'address_line' => 'VARCHAR(255) NULL',
  'country' => 'VARCHAR(64) NULL',
  'phone_country_code' => 'VARCHAR(8) NULL',
  'state' => 'VARCHAR(100) NULL',
  'city' => 'VARCHAR(100) NULL',
  'postal_code' => 'VARCHAR(20) NULL',
  'district' => 'VARCHAR(100) NULL',
  'document_number' => 'VARCHAR(64) NULL'
];
foreach ($needCols as $col => $type) {
  try {
    $chk = $pdo->prepare("SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'clients' AND COLUMN_NAME = ?");
    $chk->execute([$col]);
    if (!$chk->fetchColumn()) { $pdo->exec("ALTER TABLE clients ADD COLUMN $col $type"); }
  } catch (Throwable $__) {}
}

// Manejar conflicto de email único
$emailConflict = false;
try {
  $curSt = $pdo->prepare("SELECT email FROM clients WHERE id = ?");
  $curSt->execute([$cid]);
  $currentEmail = (string)$curSt->fetchColumn();
  if ($email !== '' && strtolower($email) !== strtolower($currentEmail)) {
    $dup = $pdo->prepare("SELECT 1 FROM clients WHERE email = ? AND id <> ? LIMIT 1");
    $dup->execute([$email, $cid]);
    if ($dup->fetchColumn()) { $emailConflict = true; $email = $currentEmail; }
  } else {
    $email = $currentEmail; // mantener email actual si no cambió
  }
} catch (Throwable $__) {}

try {
  $stmt = $pdo->prepare("UPDATE clients SET first_name=?, last_name=?, email=?, phone=?, address_line=?, country=?, phone_country_code=?, state=?, city=?, postal_code=?, district=?, document_number=?, updated_at=NOW() WHERE id=?");
  $stmt->execute([$first_name,$last_name,$email,$phone,$address_line,$country,$phone_country_code,$state,$city,$postal_code,$district,$document_number,$cid]);
} catch (Throwable $e) {
  $errors[] = 'clients_update:' . $e->getMessage();
}

// Refrescar variables de sesión del cliente para reflejar cambios en UI
$_SESSION['client_first_name'] = $first_name;
$_SESSION['client_last_name'] = $last_name;
$_SESSION['client_name'] = trim($first_name.' '.$last_name);
$_SESSION['client_email'] = $email;

// Reflejar en client_profiles (sección Perfil del Trader Room)
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");
  $cpCountry = ($country_code ?: strtoupper($country));
  $cpCountryName = $country;
  $sel = $pdo->prepare('SELECT 1 FROM client_profiles WHERE client_id = ?');
  $sel->execute([$cid]);
  if ($sel->fetchColumn()) {
    $upd = $pdo->prepare('UPDATE client_profiles SET address=?, address_number=?, country=?, country_name=?, state=?, city=?, postcode=?, neighbourhood=?, personal_id=?, updated_at=NOW() WHERE client_id=?');
    $upd->execute([$address_line, NULL, $cpCountry, $cpCountryName, $state, $city, $postal_code, $district, $document_number, $cid]);
  } else {
    $ins = $pdo->prepare('INSERT INTO client_profiles (client_id,address,address_number,country,country_name,state,city,postcode,neighbourhood,personal_id,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,NOW())');
    $ins->execute([$cid, $address_line, NULL, $cpCountry, $cpCountryName, $state, $city, $postal_code, $district, $document_number]);
  }
} catch (Throwable $__) {}

if (isset($_FILES['document_file']) && $_FILES['document_file']['error']===UPLOAD_ERR_OK) {
  $file = $_FILES['document_file'];
  $orig = $file['name']; $tmp = $file['tmp_name']; $size = (int)$file['size'];
  $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime = finfo_file($finfo,$tmp); finfo_close($finfo);
  $allowed = ['image/jpeg','image/png','image/gif','application/pdf'];
  if (in_array($mime,$allowed,true)) {
    $dir = BASE_PATH . '/uploads/documents/' . $cid; if (!is_dir($dir)) { @mkdir($dir,0775,true); }
    $ext = pathinfo($orig, PATHINFO_EXTENSION); $safe = preg_replace('/[^a-zA-Z0-9]/','',$ext);
    $name = uniqid('id_', true) . ($safe?('.'.$safe):''); $dest = $dir . '/' . $name;
    if (move_uploaded_file($tmp,$dest)) {
      $rel = '/uploads/documents/' . $cid . '/' . $name;
      try {
        $pdo->exec("CREATE TABLE IF NOT EXISTS client_documents (
          id INT AUTO_INCREMENT PRIMARY KEY,
          client_id INT NOT NULL,
          type ENUM('id','address','selfie','other') NOT NULL,
          filename VARCHAR(255) NOT NULL,
          original_name VARCHAR(255) NULL,
          mime_type VARCHAR(100) NULL,
          size INT NULL,
          status ENUM('submitted','approved','rejected') DEFAULT 'submitted',
          uploaded_at DATETIME DEFAULT CURRENT_TIMESTAMP,
          updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          notes TEXT NULL,
          INDEX idx_client_type (client_id, type),
          INDEX idx_client_status (client_id, status)
        ) ENGINE=InnoDB");
      } catch (Throwable $__) {}
      $pdo->prepare("INSERT INTO client_documents (client_id,type,filename,original_name,mime_type,size,status,uploaded_at) VALUES (?,?,?,?,?,?,'submitted',NOW())")
          ->execute([$cid,'id',$rel,$orig,$mime,$size]);
    }
  }
}

// Redirigir mostrando errores para diagnóstico
$loc = module_url('client_portal/dashboard.php');
$sep = (strpos($loc,'?')===false)?'?':'&';
if (!empty($errors)) {
  header('Location: ' . $loc . $sep . 'error=profile_save_failed&detail=' . urlencode(implode('|', $errors)));
  exit;
}
if ($emailConflict) {
  header('Location: ' . $loc . $sep . 'message=profile_updated&note=email_conflict');
  exit;
}
header('Location: ' . $loc . $sep . 'message=profile_updated');
exit;
?>
