<?php
  $nombre = $_POST["nombre"] ?? "";
  $ci = $_POST["ci"] ?? "";
  $celular = $_POST["celular"] ?? "";
  $direccion = $_POST["direccion"] ?? "";

  if($nombre == "" || $ci == "" || $celular == "" || $direccion == ""){
    echo "<p style='color:red'>Error: Todos los campos son obligatorios</p>";
    echo "<a href='formRegistrarCliente.php'>Volver</a>";
    exit;
  }

  // Verificar si ya existe la CI
  if(file_exists("clientes.txt")){
    $recurso = fopen("clientes.txt","r");
    while(!feof($recurso)){
      $linea = fgets($recurso);
      if(trim($linea) != ""){
        $reg = explode("|",$linea);
        if(count($reg) >= 2 && trim($reg[1]) == $ci){
          echo "<p style='color:red'>Error: Ya existe un cliente con CI $ci</p>";
          echo "<a href='formRegistrarCliente.php'>Volver</a>";
          fclose($recurso);
          exit;
        }
      }
    }
    fclose($recurso);
  }

  // Generar numero de cuenta autoincremental
  $numCuenta = "CTA00001";
  if(file_exists("clientes.txt")){
    $recurso = fopen("clientes.txt","r");
    while(!feof($recurso)){
      $linea = fgets($recurso);
      if(trim($linea) != ""){
        $reg = explode("|",$linea);
        if(count($reg) >= 1){
          $ultimo = trim($reg[0]);
          if(preg_match('/CTA(\d+)/',$ultimo,$m)){
            $num = intval($m[1]) + 1;
            $numCuenta = "CTA" . str_pad($num, 5, "0", STR_PAD_LEFT);
          }
        }
      }
    }
    fclose($recurso);
  }

  $fecha = date("Y-m-d H:i:s");
  $registro = $numCuenta."|".$ci."|".$nombre."|".$celular."|".$direccion."|ACTIVO|".$fecha;

  $recurso = fopen("clientes.txt","a");
  fwrite($recurso, $registro."\n");
  fclose($recurso);

  echo "<h3 style='color:green'>Cliente registrado exitosamente!</h3>";
  echo "<p><strong>Cuenta:</strong> $numCuenta</p>";
  echo "<p><strong>Nombre:</strong> $nombre</p>";
  echo "<p><strong>CI:</strong> $ci</p>";
  echo "<p><a href='formRegistrarCliente.php'>Registrar otro</a> | <a href='listarClientes.php' target='_parent'>Ver listado</a></p>";
?>
