<?php
ob_start();
session_start();
require_once __DIR__ . '/../_init.php';

header('Content-Type: application/json; charset=UTF-8');

// 1) Autenticación básica
if (!is_loggedin()) {
  http_response_code(401);
  echo json_encode(['ok' => false, 'error' => trans('error_login')]);
  exit;
}

// 2) Permisos (usa el mismo permiso de transferencias)
if (user_group_id() != 1 && !has_permission('access', 'transfer')) {
  http_response_code(403);
  echo json_encode(['ok' => false, 'error' => trans('error_transfer_permission')]);
  exit;
}

$store_id = (int)store_id();
$req      = $_REQUEST;
$method   = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');

// Utilidad: parsear importe (varchar) a float
function parse_amount_str($s) {
  $s = (string)$s;
  $s = preg_replace('/[^\d,.\-]/', '', $s);
  // Si tiene coma y punto, asumimos formato es-AR: 1.234,56
  if (strpos($s, ',') !== false && strpos($s, '.') !== false) {
    $s = str_replace('.', '', $s); // quita miles
    $s = str_replace(',', '.', $s); // decimal a punto
  } else {
    // si solo coma, usarla como decimal
    if (strpos($s, ',') !== false) {
      $s = str_replace(',', '.', $s);
    }
  }
  return (float)$s;
}

try {
  // ============================
  // GET: listar cheques por cuenta
  // ============================
  if ($method === 'GET' && isset($req['action']) && $req['action'] === 'list') {
    $from_account_id = isset($req['from_account_id']) ? (int)$req['from_account_id'] : 0;
    if ($from_account_id <= 0) {
      http_response_code(422);
      echo json_encode(['ok' => false, 'error' => 'from_account_id inválido', 'items' => []]);
      exit;
    }

    $sql = "SELECT cheque_id, numero, fecha, fecha_pago, importe, cuit, banco, observaciones
            FROM cheques
            WHERE caja_id = ?
            ORDER BY fecha_pago ASC, fecha ASC, cheque_id ASC";
    $st = db()->prepare($sql);
    $st->execute([$from_account_id]);
    $items = $st->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['ok' => true, 'items' => $items]);
    exit;
  }

  // ============================
  // POST: transferir cheques
  // ============================
  if ($method === 'POST' && isset($_POST['action']) && $_POST['action'] === 'transfer') {
    $from_account_id = isset($_POST['from_account_id']) ? (int)$_POST['from_account_id'] : 0;
    $to_account_id   = isset($_POST['to_account_id'])   ? (int)$_POST['to_account_id']   : 0;

    // Puede venir como cheque_ids[] en el JS, pero PHP lo ve como cheque_ids
    $cheque_ids = [];
    if (isset($_POST['cheque_ids'])) {
      $cheque_ids = (array)$_POST['cheque_ids'];
    } elseif (isset($_POST['cheque_ids'])) {
      $cheque_ids = (array)$_POST['cheque_ids'];
    } elseif (isset($_POST['cheque_ids'])) {
      $cheque_ids = (array)$_POST['cheque_ids'];
    }
    // fallback por si se envía exactamente 'cheque_ids[]'
    if (empty($cheque_ids) && isset($_POST['cheque_ids'])) {
      $cheque_ids = (array)$_POST['cheque_ids'];
    }
    if (empty($cheque_ids) && isset($_POST['cheque_ids'])) {
      $cheque_ids = (array)$_POST['cheque_ids'];
    }
    if (empty($cheque_ids) && isset($_POST['cheque_ids'])) {
      $cheque_ids = (array)$_POST['cheque_ids'];
    }
    // En la práctica, con 'cheque_ids[]' en JS, PHP rellena $_POST['cheque_ids']

    if (isset($_POST['cheque_ids']) && empty($cheque_ids)) {
      $cheque_ids = (array)$_POST['cheque_ids'];
    }

    if ($from_account_id <= 0)      throw new Exception('Cuenta origen inválida');
    if ($to_account_id   <= 0)      throw new Exception('Cuenta destino inválida');
    if ($from_account_id === $to_account_id) throw new Exception('La cuenta origen y destino no pueden ser la misma');
    if (empty($cheque_ids))         throw new Exception('Seleccione al menos un cheque');

    // Valido pertenencia de cheques a la cuenta origen y calculo total
    $placeholders = implode(',', array_fill(0, count($cheque_ids), '?'));
    $params       = array_map('intval', $cheque_ids);

    $sql = "SELECT cheque_id, importe
            FROM cheques
            WHERE caja_id = ? AND cheque_id IN ($placeholders)";
    array_unshift($params, $from_account_id);

    $st = db()->prepare($sql);
    $st->execute($params);
    $rows = $st->fetchAll(PDO::FETCH_ASSOC);

    if (count($rows) !== count($cheque_ids)) {
      throw new Exception('Uno o más cheques no pertenecen a la cuenta origen.');
    }

    $total = 0.0;
    foreach ($rows as $r) {
      $total += parse_amount_str($r['importe']);
    }

    // Transacción
    $pdo = db();
    $pdo->beginTransaction();

    // 1) Mover cheques (cambiar caja_id) y anotar traza
    $obs = 'Transferido de cuenta ' . $from_account_id . ' a ' . $to_account_id . ' el ' . date_time();
    $sqlUp = "UPDATE cheques
              SET caja_id = ?, observaciones = TRIM(CONCAT(COALESCE(observaciones,''), CASE WHEN observaciones<>'' THEN ' | ' ELSE '' END, ?))
              WHERE cheque_id IN ($placeholders)";
    $execParams = array_merge([$to_account_id, $obs], array_map('intval', $cheque_ids));
    $stUp = $pdo->prepare($sqlUp);
    $stUp->execute($execParams);

    // 2) Actualizar acumuladores en bank_account_to_store
    // from: transfer_to_other += total
    $st1 = $pdo->prepare("UPDATE bank_account_to_store
                          SET transfer_to_other = transfer_to_other + ?
                          WHERE store_id = ? AND account_id = ?");
    $st1->execute([$total, $store_id, $from_account_id]);

    if ($st1->rowCount() === 0) {
      $ins1 = $pdo->prepare("INSERT INTO bank_account_to_store
        (store_id, account_id, deposit, withdraw, transfer_from_other, transfer_to_other, status, sort_order)
        VALUES (?, ?, 0, 0, 0, ?, 1, 0)");
      $ins1->execute([$store_id, $from_account_id, $total]);
    }

    // to: transfer_from_other += total
    $st2 = $pdo->prepare("UPDATE bank_account_to_store
                          SET transfer_from_other = transfer_from_other + ?
                          WHERE store_id = ? AND account_id = ?");
    $st2->execute([$total, $store_id, $to_account_id]);

    if ($st2->rowCount() === 0) {
      $ins2 = $pdo->prepare("INSERT INTO bank_account_to_store
        (store_id, account_id, deposit, withdraw, transfer_from_other, transfer_to_other, status, sort_order)
        VALUES (?, ?, 0, 0, ?, 0, 1, 0)");
      $ins2->execute([$store_id, $to_account_id, $total]);
    }

    // 3) Registrar la RENDICIÓN en cheque_transfer_info / cheque_transfer_item
    $nowDate      = date_time();
    $nowUnix      = time();
    $user_id      = (int)user_id();
    $cheque_count = count($cheque_ids);
    $notes        = ''; // si querés permitir notas, podés leerlas de $_POST

    // 3.a) Cabecera
    $stInfo = $pdo->prepare("
      INSERT INTO cheque_transfer_info
        (store_id, from_account_id, to_account_id, user_id, total, cheque_count, notes, created_at, created_at_unix)
      VALUES
        (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stInfo->execute([
      $store_id,
      $from_account_id,
      $to_account_id,
      $user_id,
      $total,
      $cheque_count,
      $notes,
      $nowDate,
      $nowUnix
    ]);
    $transfer_id = (int)$pdo->lastInsertId();

    // 3.b) Detalle: snapshot de los cheques
    $sqlChequesDet = "SELECT cheque_id, numero, fecha, fecha_pago, importe, cuit, banco, observaciones
                      FROM cheques
                      WHERE cheque_id IN ($placeholders)";
    $stDet = $pdo->prepare($sqlChequesDet);
    $stDet->execute(array_map('intval', $cheque_ids));
    $detRows = $stDet->fetchAll(PDO::FETCH_ASSOC);

    $stItem = $pdo->prepare("
      INSERT INTO cheque_transfer_item
        (transfer_id, cheque_id, numero, fecha, fecha_pago, importe, cuit, banco, observaciones)
      VALUES
        (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    foreach ($detRows as $c) {
      $stItem->execute([
        $transfer_id,
        (int)$c['cheque_id'],
        $c['numero'],
        $c['fecha'],
        $c['fecha_pago'],
        parse_amount_str($c['importe']),
        $c['cuit'],
        $c['banco'],
        $c['observaciones'],
      ]);
    }

    $pdo->commit();

    echo json_encode([
      'ok'           => true,
      'moved'        => count($cheque_ids),
      'total'        => $total,
      'transfer_id'  => $transfer_id,
    ]);
    exit;
  }

  // Acción desconocida
  http_response_code(400);
  echo json_encode(['ok' => false, 'error' => 'Acción inválida']);
  exit;

} catch (Exception $e) {
  if (db()->inTransaction()) {
    db()->rollBack();
  }
  http_response_code(422);
  echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
  exit;
}
