<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', 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';

$db = Database::getInstance();
$pdo = $db->getConnection();
$userId = (int)($_SESSION['user_id'] ?? 0);
if (!$userId) { header('Location: ' . route_url(['module'=>'auth','action'=>'login'])); exit; }

function userHasPermissionByName(PDO $pdo, string $permName, int $userId): bool {
    $st = $pdo->prepare("SELECT 1 FROM role_permissions rp INNER JOIN permissions p ON rp.permission_id = p.id INNER JOIN user_roles ur ON rp.role_id = ur.role_id WHERE ur.user_id = ? AND p.name = ? LIMIT 1");
    $st->execute([$userId, $permName]);
    return (bool)$st->fetchColumn();
}

if (!userHasPermissionByName($pdo, 'clients.manual_deposit', $userId)) { header('Location: ' . route_url(['module'=>'auth','action'=>'forbidden'])); exit; }

$clientId = (int)($_GET['client_id'] ?? 0);
if ($clientId <= 0) { header('Location: ' . route_url(['module'=>'clients'])); exit; }

$accounts = [];
try {
    $stmt = $pdo->prepare("SELECT id, account_type, account_number, currency, balance, status FROM client_accounts WHERE client_id = ? AND status = 'active' ORDER BY created_at ASC");
    $stmt->execute([$clientId]);
    $accounts = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $accounts = []; }

$page_title = 'Depósito Manual';
$module = 'clients';
$action = 'manual_deposit';
ob_start();
?>
<section class="card" style="max-width:640px;margin:auto;">
  <div class="card-body">
    <h2 class="section-title">Depósito manual</h2>
    <form method="post" action="<?php echo module_url('clients/actions.php'); ?>">
      <input type="hidden" name="action" value="manual_deposit">
      <input type="hidden" name="client_id" value="<?php echo (int)$clientId; ?>">
      <div class="form-group">
        <label>Cuenta destino</label>
        <select name="account_id" class="filter-select" required>
          <?php foreach ($accounts as $a): ?>
            <option value="<?php echo (int)$a['id']; ?>">#<?php echo htmlspecialchars($a['account_number']); ?> · <?php echo htmlspecialchars($a['account_type']); ?> · <?php echo htmlspecialchars(strtoupper($a['currency'])); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label>Monto</label>
        <input type="number" step="0.01" min="0.01" name="amount" class="search-input" required>
      </div>
      <div class="form-group">
        <label>Moneda</label>
        <input type="text" name="currency" value="USD" class="search-input" required>
      </div>
      <div class="form-group">
        <label>Método</label>
        <input type="text" name="method" value="manual" class="search-input">
      </div>
      <div class="form-group">
        <label>Referencia</label>
        <input type="text" name="reference" class="search-input" placeholder="Opcional">
      </div>
      <input type="hidden" name="redirect" value="<?php echo route_url(['module'=>'clients','action'=>'view','id'=>$clientId]); ?>">
      <div class="filter-actions">
        <button type="submit" class="btn-primary">Registrar depósito</button>
        <a href="<?php echo route_url(['module'=>'clients']); ?>" class="btn-secondary">Cancelar</a>
      </div>
    </form>
  </div>
  <style>
    .filter-actions{display:flex;gap:12px;justify-content:flex-end}
  </style>
</section>
<?php
$content = ob_get_clean();
include BASE_PATH . '/modules/shared/layout.php';
?>
