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

$id = (int)($_GET['id'] ?? 0);
if (!$id) redirect('customers.php');

/* ===============================
   LOAD CUSTOMER
================================ */
$st = $conn->prepare("SELECT * FROM users WHERE id=?");
$st->bind_param("i", $id);
$st->execute();
$user = $st->get_result()->fetch_assoc();
if (!$user) die('Customer not found');

/* ===============================
   ADMIN RESET ACTIONS
================================ */
/* ===============================
   ADMIN REVEAL ACTIONS (EDUCATIONAL)
================================ */
if (is_post()) {
  csrf_verify();

  $action = $_POST['action'] ?? '';

  try {

    /* ===== REVEAL PASSWORD ===== */
    if ($action === 'reveal_password') {

      $newPass = bin2hex(random_bytes(4)); // 8 chars
      $hash = password_hash($newPass, PASSWORD_DEFAULT);

      $st = $conn->prepare("UPDATE users SET password_hash=? WHERE id=?");
      $st->bind_param("si", $hash, $id);
      $st->execute();

      flash(
        'msg',
        "🔐 <b>New Password Generated</b><br>
         Password: <strong>$newPass</strong><br>
         <small class='text-muted'>Shown once. Customer should change it.</small>"
      );

      redirect("customer_view.php?id=$id");
    }

    /* ===== REVEAL PIN ===== */
    if ($action === 'reveal_pin') {

      $newPin = (string) random_int(1000, 9999);
      $pinHash = password_hash($newPin, PASSWORD_DEFAULT);

      $st = $conn->prepare("
        UPDATE users
        SET pin_hash=?, pin_temp=1
        WHERE id=?
      ");
      $st->bind_param("si", $pinHash, $id);
      $st->execute();

      flash(
        'msg',
        "🔑 <b>New PIN Generated</b><br>
         PIN: <strong>$newPin</strong><br>
         <small class='text-muted'>Forced change on next login.</small>"
      );

      redirect("customer_view.php?id=$id");
    }

  } catch (Throwable $e) {
    flash('err', $e->getMessage());
    redirect("customer_view.php?id=$id");
  }
}


/* ===============================
   LOAD ACCOUNTS
================================ */
$accounts = [];
$res = $conn->query("
  SELECT *
  FROM accounts
  WHERE user_id = {$id}
  ORDER BY is_primary DESC, id ASC
");
while ($r = $res->fetch_assoc()) $accounts[] = $r;

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

<div class="container-fluid py-4">

  <div class="d-flex justify-content-between align-items-center mb-3">
    <h3 class="fw-bold mb-0">Customer Profile</h3>
    <a href="customers.php" class="btn btn-sm btn-outline-secondary">Back</a>
  </div>

  <?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="row g-4">

    <!-- ================= PROFILE ================= -->
    <div class="col-lg-4">
      <div class="card ab-card p-4 text-center">

        <?php
          $photo = (!empty($user['photo']) && file_exists(__DIR__.'/../'.$user['photo']))
            ? '../'.$user['photo']
            : '../assets/img/avatar.png';
        ?>
        <img src="<?= $photo ?>"
             class="rounded-circle mb-3"
             style="width:120px;height:120px;object-fit:cover">

        <h5 class="fw-bold mb-1"><?= e($user['full_name']) ?></h5>
        <div class="text-muted mb-2"><?= e($user['email']) ?></div>

        <div class="mb-3">
          <span class="badge <?= $user['banned']==='yes'?'text-bg-danger':'text-bg-success' ?>">
            <?= $user['banned']==='yes'?'BANNED':'ACTIVE' ?>
          </span>

          <span class="badge ms-1
            <?= $user['kyc_status']==='verified'?'text-bg-success':
               ($user['kyc_status']==='pending'?'text-bg-warning':'text-bg-secondary') ?>">
            KYC: <?= strtoupper(e($user['kyc_status'])) ?>
          </span>
        </div>

        <div class="d-grid gap-2">
          <a href="customer_edit.php?id=<?= $id ?>" class="btn btn-outline-primary">Edit Customer</a>
          <a href="customer_transactions.php?id=<?= $id ?>" class="btn btn-outline-secondary">View Transactions</a>
          <a href="impersonate.php?id=<?= $id ?>" class="btn btn-outline-dark">Login as Customer</a>
        </div>
      </div>

      <!-- ================= LOGIN CREDENTIALS ================= -->
<div class="card ab-card p-4 mt-3">
  <h6 class="fw-bold mb-3">Login Credentials (Admin)</h6>

  <div class="small mb-2">
    <b>Account Number (Login):</b><br>
    <span class="badge text-bg-dark"><?= e($user['account_number']) ?></span>
  </div>

  <form method="post" class="d-grid gap-2">
    <?= csrf_field() ?>

    <button name="action" value="reveal_password" class="btn btn-outline-danger">
      Reveal New Password (One-Time)
    </button>

    <button name="action" value="reveal_pin" class="btn btn-outline-warning">
      Reveal New PIN (One-Time)
    </button>
  </form>

  <div class="text-muted small mt-2">
    • Values are generated and shown once<br>
    • Customer must change on next login<br>
    • Original password/PIN cannot be retrieved
  </div>
</div>


      <!-- ================= ADD ACCOUNT ================= -->
      <div class="card ab-card p-4 mt-3">
        <h6 class="fw-bold mb-3">Add New Account</h6>

        <form method="post" action="account_create.php">
          <?= csrf_field() ?>
          <input type="hidden" name="user_id" value="<?= (int)$user['id'] ?>">

          <label class="form-label">Account Type</label>
          <select name="account_type" class="form-select mb-2" required>
            <option value="savings">Savings</option>
            <option value="current">Current</option>
            <option value="fixed">Fixed</option>
            <option value="business">Business</option>
          </select>

          <label class="form-label">Currency</label>
          <select name="currency" class="form-select mb-3">
            <option value="GHS">GHS</option>
            <option value="USD">USD</option>
          </select>

          <button class="btn btn-success w-100">
            <i class="bi bi-plus-circle"></i> Create Account
          </button>
        </form>
      </div>
    </div>

    <!-- ================= DETAILS & ACCOUNTS ================= -->
    <div class="col-lg-8">

      <!-- CUSTOMER DETAILS -->
      <div class="card ab-card p-4 mb-3">
        <h6 class="fw-bold mb-3">Customer Details</h6>

        <div class="row g-3 small">
          <div class="col-md-6"><b>Phone:</b> <?= e($user['phone'] ?? '-') ?></div>
          <div class="col-md-6"><b>DOB:</b> <?= e($user['dob'] ?? '-') ?></div>
          <div class="col-md-6"><b>Gender:</b> <?= e($user['gender'] ?? '-') ?></div>
          <div class="col-md-6"><b>Occupation:</b> <?= e($user['occupation'] ?? '-') ?></div>
          <div class="col-md-12"><b>Address:</b> <?= e($user['address'] ?? '-') ?></div>
          <div class="col-md-6"><b>Joined:</b> <?= e($user['created_at']) ?></div>
        </div>
      </div>

      <!-- ACCOUNTS -->
      <div class="card ab-card p-4">
        <h6 class="fw-bold mb-3">Customer Accounts</h6>

        <div class="table-responsive">
          <table class="table align-middle mb-0">
            <thead>
              <tr>
                <th>Account No</th>
                <th>Type</th>
                <th>Currency</th>
                <th>Balance</th>
                <th>Primary</th>
                <th class="text-end">Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($accounts as $a): ?>
                <tr>
                  <td><?= e($a['account_no']) ?></td>
                  <td><?= ucfirst(e($a['account_type'])) ?></td>
                  <td><?= e($a['currency']) ?></td>
                  <td class="fw-bold"><?= e($a['currency']) ?> <?= money($a['balance']) ?></td>
                  <td>
                    <?php if ((int)$a['is_primary'] === 1): ?>
                      <span class="badge text-bg-success">PRIMARY</span>
                    <?php else: ?>
                      <span class="badge text-bg-secondary">—</span>
                    <?php endif; ?>
                  </td>
                  <td class="text-end">
                    <a href="adjust_balance.php?id=<?= (int)$a['id'] ?>" class="btn btn-sm btn-outline-success">Credit</a>
                    <a href="adjust_balance.php?id=<?= (int)$a['id'] ?>" class="btn btn-sm btn-outline-danger">Debit</a>
                  </td>
                </tr>
              <?php endforeach; ?>

              <?php if (!$accounts): ?>
                <tr>
                  <td colspan="6" class="text-center text-muted py-3">
                    No accounts found
                  </td>
                </tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>

      </div>
    </div>

  </div>
</div>

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