<?php
require_once __DIR__ . '/../../app/helpers/functions.php';
require_once __DIR__ . '/../../app/helpers/csrf.php';
require_once __DIR__ . '/../../app/middleware/auth.php';

session_boot();
require_login();

$conn = require __DIR__ . '/../../app/config/database.php';
require_admin($conn);

if (!is_post()) redirect('customers.php');

csrf_verify();

$userId      = (int)($_POST['user_id'] ?? 0);
$accountType = trim($_POST['account_type'] ?? '');
$currency    = trim($_POST['currency'] ?? 'GHS');

if (!$userId || !$accountType) {
  flash('err', 'Invalid account data');
  redirect('customers.php');
}

/* ===============================
   CHECK IF USER HAS PRIMARY
================================ */
$st = $conn->prepare("
  SELECT COUNT(*) AS c
  FROM accounts
  WHERE user_id = ? AND is_primary = 1
");
$st->bind_param("i", $userId);
$st->execute();
$hasPrimary = (int)$st->get_result()->fetch_assoc()['c'] > 0;

/* ===============================
   GENERATE ACCOUNT NUMBER
================================ */
$accountNo = 'AC' . date('Y') . random_int(100000, 999999);

/* ===============================
   CREATE ACCOUNT
================================ */
$st = $conn->prepare("
  INSERT INTO accounts
    (user_id, account_type, account_no, balance, currency, is_primary, created_at)
  VALUES (?, ?, ?, 0, ?, ?, NOW())
");
$isPrimary = $hasPrimary ? 0 : 1;
$st->bind_param(
  "isssi",
  $userId,
  $accountType,
  $accountNo,
  $currency,
  $isPrimary
);
$st->execute();

/* ===============================
   AUDIT
================================ */
$meta = json_encode([
  'user_id' => $userId,
  'account_type' => $accountType,
  'account_no' => $accountNo
]);

$ip = client_ip();
$a = $conn->prepare("
  INSERT INTO audit_logs (actor_id, action, meta, ip)
  VALUES (?, 'ACCOUNT_CREATE', ?, ?)
");
$admin = current_user();
$a->bind_param("iss", $admin['id'], $meta, $ip);
$a->execute();

flash('msg', 'New account added successfully');
redirect("customer_view.php?id={$userId}");
