<?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);

$admin = current_user();

/* ===============================
   SAFE MAILER INCLUDE (NO CRASH)
================================ */
$mailerOk = false;
$mailerPath = __DIR__ . '/../../app/helpers/mailer.php';
if (is_file($mailerPath)) {
  require_once $mailerPath;
  $mailerOk = function_exists('send_mail');
}

/* ===============================
   HELPERS
================================ */
function generate_account_number(mysqli $conn): string {
  do {
    $num = (string) random_int(10000000000, 99999999999);
    $st = $conn->prepare("SELECT id FROM users WHERE account_number=? LIMIT 1");
    $st->bind_param("s", $num);
    $st->execute();
  } while ($st->get_result()->fetch_assoc());
  return $num;
}

function send_customer_email_safe(
  bool $mailerOk,
  string $to,
  string $name,
  string $accountNo,
  string $password,
  string $pin
): bool {
  if (!$mailerOk) return false;

  $subject = 'Your Federal Reserve Bank Account Details';

  $body = "
Hello {$name},

Your account has been created successfully.

Account Number: {$accountNo}
Temporary Password: {$password}
Temporary PIN: {$pin}

Please change your credentials after first login.

Regards,
Astrabank
";

  try {
    return (bool) send_mail($to, $subject, $body);
  } catch (Throwable $e) {
    return false;
  }
}

/* ===============================
   CREATE CUSTOMER
================================ */
if (is_post()) {
  csrf_verify();

  $name    = trim($_POST['full_name'] ?? '');
  $email   = trim($_POST['email'] ?? '');
  $phone   = trim($_POST['phone'] ?? '');
  $dob     = $_POST['dob'] ?? null;
  $gender  = $_POST['gender'] ?? null;
  $job     = trim($_POST['occupation'] ?? '');
  $addr    = trim($_POST['address'] ?? '');
  $country = trim($_POST['country'] ?? '');

  $acctType = $_POST['account_type'] ?? '';
  $currency = $_POST['currency'] ?? '';
  $opening  = (float)($_POST['opening_balance'] ?? 0);

  $password = trim($_POST['password'] ?? '');
  $pin      = trim($_POST['pin'] ?? '');

  if (!$name || !$email || !$acctType || !$currency) {
    flash('err', 'Required fields are missing.');
    redirect('customer_create.php');
  }

  $accountNo = generate_account_number($conn);

  $tempPass = $password ?: bin2hex(random_bytes(4));
  $passwordHash = password_hash($tempPass, PASSWORD_DEFAULT);

  if ($pin && (!ctype_digit($pin) || strlen($pin) < 4 || strlen($pin) > 6)) {
    flash('err', 'PIN must be 4–6 digits.');
    redirect('customer_create.php');
  }

  $tempPin = $pin ?: (string) random_int(1000, 9999);
  $pinHash = password_hash($tempPin, PASSWORD_DEFAULT);

  $conn->begin_transaction();

  try {

    $photoPath = null;
    if (!empty($_FILES['photo']['name'])) {
      $dir = __DIR__ . '/../uploads/users';
      if (!is_dir($dir)) mkdir($dir, 0777, true);
      $photoPath = 'uploads/users/' . time() . '_' . basename($_FILES['photo']['name']);
      move_uploaded_file($_FILES['photo']['tmp_name'], __DIR__ . '/../' . $photoPath);
    }

    $st = $conn->prepare("
      INSERT INTO users
      (full_name,email,password_hash,phone,dob,gender,occupation,address,country,photo,
       status,pin_hash,account_number,pin_temp)
      VALUES (?,?,?,?,?,?,?,?,?,?,
              'active',?,?,1)
    ");

    $st->bind_param(
      "sssssssssssi",
      $name,
      $email,
      $passwordHash,
      $phone,
      $dob,
      $gender,
      $job,
      $addr,
      $country,
      $photoPath,
      $pinHash,
      $accountNo
    );

    $st->execute();
    $userId = $conn->insert_id;

    $st = $conn->prepare("
      INSERT INTO accounts
      (user_id,account_no,account_type,currency,balance,is_primary)
      VALUES (?,?,?,?,0,1)
    ");
    $st->bind_param("isss", $userId, $accountNo, $acctType, $currency);
    $st->execute();

    $conn->commit();

    send_customer_email_safe($mailerOk, $email, $name, $accountNo, $tempPass, $tempPin);

    flash('msg', "Customer created successfully.<br>
      <b>Account No:</b> {$accountNo}<br>
      <b>Password:</b> {$tempPass}<br>
      <b>PIN:</b> {$tempPin}");

    redirect('customers.php');

  } catch (Throwable $e) {
    $conn->rollback();
    flash('err', $e->getMessage());
    redirect('customer_create.php');
  }
}

$title = 'Create Customer — Admin';
include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/admin_sidebar.php';
?>

<div class="container-fluid py-4">
  <h3 class="fw-bold mb-3">Create Customer</h3>

  <?php if ($m = flash('msg')): ?>
    <div class="alert alert-success"><?= $m ?></div>
  <?php endif; ?>

  <?php if ($m = flash('err')): ?>
    <div class="alert alert-danger"><?= e($m) ?></div>
  <?php endif; ?>

  <div class="card ab-card p-4">
    <form method="post" enctype="multipart/form-data">
      <?= csrf_field() ?>

      <div class="row g-3">

        <div class="col-md-6">
          <label class="form-label">Full Name</label>
          <input class="form-control" name="full_name" required>
        </div>

        <div class="col-md-6">
          <label class="form-label">Email</label>
          <input type="email" class="form-control" name="email" required>
        </div>

        <div class="col-md-4">
          <label class="form-label">Phone</label>
          <input class="form-control" name="phone">
        </div>

        <div class="col-md-4">
          <label class="form-label">Date of Birth</label>
          <input type="date" class="form-control" name="dob">
        </div>

        <div class="col-md-4">
          <label class="form-label">Gender</label>
          <select class="form-select" name="gender">
            <option value="">— Select —</option>
            <option value="male">Male</option>
            <option value="female">Female</option>
            <option value="other">Other</option>
          </select>
        </div>

        <div class="col-md-6">
          <label class="form-label">Occupation</label>
          <input class="form-control" name="occupation" placeholder="e.g., Trader / Engineer">
        </div>

        <div class="col-md-6">
          <label class="form-label">Address</label>
          <input class="form-control" name="address" placeholder="Residential address">
        </div>

        <div class="col-md-6">
          <label class="form-label">Profile Photo</label>
          <input type="file" class="form-control" name="photo" accept="image/jpeg,image/png,image/webp">
          <div class="form-text">JPG/PNG/WEBP only.</div>
        </div>
        
        <div class="col-md-6">
      <label class="form-label">Country</label>
      <input class="form-control" name="country" placeholder="e.g. United States">
      </div>

        <div class="col-md-6"></div>

        <div class="col-md-6">
          <label class="form-label">Account Type</label>
          <select class="form-select" name="account_type" required>
            <option value="">— Select —</option>
            <option value="savings">Savings</option>
            <option value="current">Current</option>
            <option value="checking">Checking Account</option>
            <option value="online_banking">Online Banking</option>
            <option value="non_resident">Non Resident Account</option>
            <option value="domiciliary">Domiciliary Account</option>
            <option value="joint">Joint Account</option>
            <option value="fixed">Fixed Deposit</option>
          </select>
        </div>

        <div class="col-md-6">
          <label class="form-label">Currency</label>
          <select class="form-select" name="currency" required>
            <option value="USD">USD</option>
            <option value="EUR">EUR</option>
            <option value="GBP">GBP</option>
          </select>
        </div>

        <div class="col-md-4">
          <label class="form-label">Opening Balance</label>
          <input type="number" step="0.01" class="form-control" name="opening_balance">
        </div>

        <div class="col-md-4">
          <label class="form-label">Password (optional)</label>
          <input class="form-control" name="password" placeholder="Leave blank to auto-generate">
        </div>

        <div class="col-md-4">
          <label class="form-label">PIN (optional)</label>
          <input class="form-control" name="pin" maxlength="6" inputmode="numeric" placeholder="Leave blank to auto-generate">
        </div>

      </div>

      <div class="mt-4">
        <button class="btn ab-btn text-white">
          <i class="bi bi-person-plus me-1"></i>Create Customer
        </button>
        <a href="customers.php" class="btn btn-outline-secondary ms-2">Cancel</a>
      </div>

    </form>
  </div>
</div>

<?php include __DIR__ . '/../../views/partials/foot.php'; ?>
