<?php
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();
requireAdmin();

$userId = $_GET['id'] ?? '';
$user = getUserById($userId);
if (!$user) { header('Location: users.php'); exit; }

$message = '';
$messageType = '';

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

    if ($action === 'change_password') {
        $newPass = $_POST['new_password'] ?? '';
        if (strlen($newPass) < 6) { $message = 'Password must be at least 6 characters.'; $messageType = 'error'; }
        else { $user['password_hash'] = password_hash($newPass, PASSWORD_DEFAULT); saveUser($user); $message = 'Password updated successfully.'; $messageType = 'success'; }
    } elseif ($action === 'toggle_ban') {
        $user['status'] = ($user['status'] === 'banned') ? 'active' : 'banned';
        saveUser($user);
        $message = $user['status'] === 'banned' ? 'User has been banned.' : 'User has been unbanned.';
        $messageType = 'success';
    } elseif ($action === 'add_custom_key') {
        $customName = trim($_POST['custom_key_name'] ?? '');
        if (count($user['api_keys']) >= 3) { $message = 'This user already has the maximum of 3 API keys.'; $messageType = 'error'; }
        elseif (!preg_match('/^[A-Za-z0-9_]{2,30}$/', $customName)) { $message = 'Name must be 2-30 chars, letters/numbers/underscores only.'; $messageType = 'error'; }
        else {
            $newKey = generateCustomApiKey($customName);
            $user['api_keys'][] = ['key' => $newKey, 'label' => $customName . ' (added by admin)', 'created_at' => nowIST()->format('Y-m-d H:i:s')];
            saveUser($user);
            $message = "New API key added: $newKey"; $messageType = 'success';
        }
    } elseif ($action === 'delete_key') {
        $delIndex = intval($_POST['key_index'] ?? -1);
        if (isset($user['api_keys'][$delIndex]) && count($user['api_keys']) > 1) {
            array_splice($user['api_keys'], $delIndex, 1);
            $user['api_key'] = $user['api_keys'][0]['key'] ?? '';
            saveUser($user);
            $message = 'API key removed.'; $messageType = 'success';
        } else { $message = 'Cannot remove the only remaining key.'; $messageType = 'error'; }
    } elseif ($action === 'set_reset_chances') {
        $chances = intval($_POST['reset_chances'] ?? -1);
        if ($chances < 0) { $message = 'Enter a valid number of chances (0 or more).'; $messageType = 'error'; }
        else { $user['reset_chances'] = $chances; saveUser($user); $message = "Reset chances set to $chances."; $messageType = 'success'; }
    } elseif ($action === 'reset_api') {
        if (isset($user['api_keys'][0])) { $user['api_keys'][0]['key'] = generateApiKey(); $user['api_key'] = $user['api_keys'][0]['key']; }
        else { $user['api_key'] = generateApiKey(); }
        saveUser($user); $message = 'New API key generated for this user.'; $messageType = 'success';
    } elseif ($action === 'clear_user_data') {
        $db = getDB();
        $stmt1 = $db->prepare("DELETE FROM orders WHERE user_id = ?");
        $stmt1->execute([$userId]);
        $stmt2 = $db->prepare("DELETE FROM payment_links WHERE user_id = ?");
        $stmt2->execute([$userId]);
        $stmt3 = $db->prepare("DELETE FROM webhook_logs WHERE user_id = ?");
        $stmt3->execute([$userId]);
        
        $user['total_requests'] = 0;
        $user['total_success'] = 0;
        $user['total_failed'] = 0;
        $user['total_amount_received'] = 0.00;
        saveUser($user);
        
        $message = "All transaction history, payment links, and revenue counters for " . $user['name'] . " have been completely cleared!";
        $messageType = 'success';
    } elseif ($action === 'delete_user') {
        $db = getDB();
        $stmt1 = $db->prepare("DELETE FROM orders WHERE user_id = ?");
        $stmt1->execute([$userId]);
        $stmt2 = $db->prepare("DELETE FROM payment_links WHERE user_id = ?");
        $stmt2->execute([$userId]);
        $stmt3 = $db->prepare("DELETE FROM webhook_logs WHERE user_id = ?");
        $stmt3->execute([$userId]);
        $stmt4 = $db->prepare("DELETE FROM users WHERE id = ?");
        $stmt4->execute([$userId]);
        
        header('Location: users.php?msg=deleted');
        exit;
    } elseif ($action === 'login_as_client') {
        $_SESSION['user_id'] = $userId;
        header('Location: ../dashboard.php');
        exit;
    } elseif ($action === 'edit_user_details') {
        $newName = trim($_POST['name'] ?? '');
        $newEmail = trim($_POST['email'] ?? '');
        $newPhone = trim($_POST['phone'] ?? '');

        if (!$newName || !$newEmail) {
            $message = 'Name and Email are required.';
            $messageType = 'error';
        } else {
            $existing = getUserByEmail($newEmail);
            if ($existing && $existing['id'] !== $userId) {
                $message = 'Email is already in use by another account.';
                $messageType = 'error';
            } else {
                $user['name'] = $newName;
                $user['email'] = $newEmail;
                $user['phone'] = $newPhone;
                saveUser($user);
                $message = 'User details updated successfully.';
                $messageType = 'success';
            }
        }
    }

    $user = getUserById($userId);
}


$allOrders = getAllOrders();
$userOrders = array_values(array_filter($allOrders, fn($o) => ($o['user_id'] ?? '') === $userId));
$userLinks = getPaymentLinksByUser($userId);
$userInvoices = [];

$userPaid = 0; $userPending = 0; $userFailed = 0;
foreach ($userOrders as $o) {
    $amt = floatval($o['amount'] ?? 0);
    if ($o['status'] === 'success') $userPaid += $amt;
    elseif ($o['status'] === 'pending') $userPending += $amt;
    else $userFailed += $amt;
}
foreach ($userLinks as $pl) {
    $st = $pl['status'] ?? '';
    if ($st !== 'paid' && isset($pl['expires_at']) && time() > $pl['expires_at']) {
        $st = 'expired';
    }
    $amt = floatval($pl['amount'] ?? 0);
    if ($st === 'pending') $userPending += $amt;
    elseif ($st === 'expired') $userFailed += $amt;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php $pageTitle = "Manage: " . htmlspecialchars($user['name']) . " — Admin"; include __DIR__ . '/admin-style.php'; ?>
</head>
<body>
<?php include __DIR__ . '/admin-nav.php'; ?>
    <div class="wrap">

      <!-- Breadcrumb -->
      <a href="users.php" style="color:var(--blue-600);font-size:13px;font-weight:600;text-decoration:none;display:inline-flex;align-items:center;gap:5px;margin-bottom:18px;">
        <i data-lucide="arrow-left" style="width:14px;height:14px;"></i> Back to Users
      </a>

      <!-- User Header -->
      <div style="display:flex;align-items:center;gap:16px;margin-bottom:28px;flex-wrap:wrap;">
        <?php if (!empty($user['avatar'])): ?>
          <img src="<?= htmlspecialchars($user['avatar']) ?>" style="width:64px;height:64px;border-radius:50%;object-fit:cover;border:2px solid var(--blue-600);box-shadow:0 4px 12px rgba(37,99,235,0.2);" alt="">
        <?php else: ?>
          <div style="width:64px;height:64px;border-radius:50%;background:#1e3a8a;color:#fff;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:26px;flex-shrink:0;">
            <?= strtoupper(substr($user['name'] ?? 'U', 0, 1)) ?>
          </div>
        <?php endif; ?>
        <div>
          <h1 style="font-size:22px;font-weight:700;color:var(--color-ink);letter-spacing:-0.5px;display:flex;align-items:center;gap:10px;margin-bottom:4px;">
            <?= htmlspecialchars($user['name']) ?>
            <span class="badge <?= $user['status'] === 'banned' ? 'badge-danger' : 'badge-success' ?>"><?= ucfirst($user['status']) ?></span>
          </h1>
          <p style="font-size:13px;color:var(--color-ink-mute);"><?= htmlspecialchars($user['email']) ?> • Gmail: <?= $user['gmail_connected'] ? htmlspecialchars($user['fampay_gmail']) : 'Not connected' ?></p>
        </div>
      </div>

      <?php if ($message): ?>
        <div class="callout callout-<?= $messageType === 'success' ? 'success' : 'error' ?>" style="margin-bottom:20px;"><?= htmlspecialchars($message) ?></div>
      <?php endif; ?>

      <!-- Payment Stats -->
      <div class="stat-grid" style="margin-bottom:20px;">
        <div class="stat-card">
          <div class="stat-card-top">
            <div class="stat-card-label">Total Paid</div>
            <div class="stat-card-icon green"><i data-lucide="check-circle-2" style="width:17px;height:17px;"></i></div>
          </div>
          <div class="stat-card-value tnum" style="color:var(--color-success-text);">₹<?= number_format($userPaid, 2) ?></div>
        </div>
        <div class="stat-card">
          <div class="stat-card-top">
            <div class="stat-card-label">Pending</div>
            <div class="stat-card-icon orange"><i data-lucide="clock" style="width:17px;height:17px;"></i></div>
          </div>
          <div class="stat-card-value tnum">₹<?= number_format($userPending, 2) ?></div>
        </div>
        <div class="stat-card">
          <div class="stat-card-top">
            <div class="stat-card-label">Failed / Expired</div>
            <div class="stat-card-icon red"><i data-lucide="x-circle" style="width:17px;height:17px;"></i></div>
          </div>
          <div class="stat-card-value tnum">₹<?= number_format($userFailed, 2) ?></div>
        </div>
        <div class="stat-card">
          <div class="stat-card-top">
            <div class="stat-card-label">Reset Chances Left</div>
            <div class="stat-card-icon blue"><i data-lucide="rotate-ccw" style="width:17px;height:17px;"></i></div>
          </div>
          <div class="stat-card-value tnum"><?= (int)$user['reset_chances'] ?> <span style="font-size:14px;font-weight:500;color:var(--color-ink-mute);">/ 100</span></div>
        </div>
      </div>

      <!-- Main Grid: API Keys + Action Cards -->
      <div class="dashboard-bottom-grid" style="align-items:start;">

        <!-- Left Column -->
        <div style="display:flex;flex-direction:column;gap:20px;">
          <!-- Edit User Details Card -->
          <div class="card" style="margin-bottom:0;">
            <div class="card-title" style="margin-bottom:14px;"><i data-lucide="user" style="width:18px;height:18px;color:var(--color-primary);"></i> Edit User Details</div>
            <form method="POST" style="display:flex;flex-direction:column;gap:12px;">
              <input type="hidden" name="action" value="edit_user_details">
              <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">
              <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%, 150px),1fr));gap:12px;">
                <div>
                  <label class="form-label" style="font-size:12px;color:var(--color-ink-mute);margin-bottom:4px;display:block;">Full Name</label>
                  <input type="text" name="name" class="form-input" value="<?= htmlspecialchars($user['name']) ?>" required>
                </div>
                <div>
                  <label class="form-label" style="font-size:12px;color:var(--color-ink-mute);margin-bottom:4px;display:block;">Phone Number</label>
                  <input type="text" name="phone" class="form-input" value="<?= htmlspecialchars($user['phone'] ?? '') ?>">
                </div>
              </div>
              <div>
                <label class="form-label" style="font-size:12px;color:var(--color-ink-mute);margin-bottom:4px;display:block;">Email Address</label>
                <input type="email" name="email" class="form-input" value="<?= htmlspecialchars($user['email']) ?>" required>
              </div>
              <button type="submit" class="btn btn-primary" style="align-self:flex-start;padding:8px 16px;">Save Details</button>
            </form>
          </div>

          <!-- API Keys Card -->
          <div class="card" style="margin-bottom:0;">
            <div class="card-title" style="margin-bottom:6px;"><i data-lucide="key" style="width:18px;height:18px;color:var(--color-primary);"></i> Active API Keys (<?= count($user['api_keys']) ?>/3)</div>
          <div class="card-sub" style="margin-bottom:18px;">Manage keys for this user. Removing requires at least one key to remain.</div>

          <?php foreach ($user['api_keys'] as $idx => $keyData): ?>
            <div style="display:flex;align-items:center;gap:10px;background:var(--surface-page);border:1px solid var(--color-hairline);border-radius:var(--r-md);padding:12px 14px;margin-bottom:10px;flex-wrap:wrap;">
              <code class="tnum" style="color:var(--blue-700);font-weight:600;flex:1;word-break:break-all;font-size:12px;"><?= htmlspecialchars($keyData['key']) ?></code>
              <span class="badge badge-neutral" style="font-size:11px;"><?= htmlspecialchars($keyData['label']) ?></span>
              <?php if (count($user['api_keys']) > 1): ?>
                <form method="POST" onsubmit="return confirm('Remove this API key?');" style="display:inline;">
                  <input type="hidden" name="action" value="delete_key">
                  <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">
                  <input type="hidden" name="key_index" value="<?= $idx ?>">
                  <button type="submit" class="btn btn-danger" style="font-size:12px;padding:4px 10px;margin:0;"><i data-lucide="trash-2" style="width:12px;height:12px;"></i></button>
                </form>
              <?php endif; ?>
            </div>
          <?php endforeach; ?>

          <!-- Add Custom Key -->
          <div style="margin-top:16px;padding-top:16px;border-top:1px solid var(--color-hairline);">
            <div style="font-size:13px;font-weight:600;color:var(--color-ink);margin-bottom:10px;">Add Custom API Key <span style="font-weight:400;color:var(--color-ink-mute);">(for cash/offline payments)</span></div>
            <form method="POST" style="display:flex;gap:8px;flex-wrap:wrap;">
              <input type="hidden" name="action" value="add_custom_key">
              <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">
              <input type="text" name="custom_key_name" class="form-input" placeholder="e.g. RahulShop" maxlength="30" style="flex:1;min-width:150px;" <?= count($user['api_keys']) >= 3 ? 'disabled' : 'required' ?>>
              <button type="submit" class="btn btn-primary" style="white-space:nowrap;" <?= count($user['api_keys']) >= 3 ? 'disabled' : '' ?>>
                <i data-lucide="plus" style="width:14px;height:14px;"></i> <?= count($user['api_keys']) >= 3 ? 'Max Reached' : 'Add Key' ?>
              </button>
            </form>
          </div>
        </div>

        <!-- Transaction History -->
          <div class="card" style="padding:0;overflow:hidden;margin-bottom:0;">
            <div style="padding:22px 28px 18px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:12px;">
              <div>
                <div class="card-title"><i data-lucide="list" style="width:18px;height:18px;color:var(--color-primary);"></i> Transaction History</div>
                <div class="card-sub">All payment requests created under <?= htmlspecialchars(explode(' ', $user['name'])[0]) ?>'s account</div>
              </div>
              <div style="position:relative;">
                <i data-lucide="search" style="position:absolute;left:10px;top:50%;transform:translateY(-50%);width:14px;height:14px;color:var(--color-ink-mute);"></i>
                <input type="text" id="searchTxn" placeholder="Search Order ID or Status..." class="form-input" style="padding-left:32px; height:32px; font-size:13px; width:220px; border-radius:var(--r-md);">
              </div>
            </div>
            
            <div class="table-container" style="margin:0; border-top:1px solid var(--color-hairline); border-radius:0 0 var(--r-xl) var(--r-xl);">
              <table class="table">
                <thead>
                  <tr>
                    <th>Order ID</th>
                    <th>Type</th>
                    <th>Amount</th>
                    <th>Status</th>
                    <th>Created</th>
                  </tr>
                </thead>
                <tbody>
                  <?php if (empty($userOrders)): ?>
                  <tr>
                    <td colspan="5">
                      <div class="empty-state">
                        <div class="empty-state-icon"><i data-lucide="inbox" style="width:24px;height:24px;"></i></div>
                        <div class="empty-state-title">No transactions found</div>
                        <div class="empty-state-sub">This user hasn't received any payments yet.</div>
                      </div>
                    </td>
                  </tr>
                  <?php else: ?>
                  <?php foreach ($userOrders as $order): ?>
                  <tr>
                    <td style="white-space:nowrap;"><code style="font-size:12px;color:var(--color-ink-mute);background:var(--surface-page);padding:3px 7px;border-radius:5px;border:1px solid var(--color-hairline);"><?= htmlspecialchars($order['order_id']) ?></code></td>
                    <td style="white-space:nowrap;">
                      <?php if ($order['type'] === 'payment_link'): ?>
                        <span class="badge badge-soft" style="font-size:10px;"><i data-lucide="link" style="width:10px;height:10px;"></i> payment_link</span>
                      <?php else: ?>
                        <span class="badge badge-neutral" style="font-size:10px;"><i data-lucide="code" style="width:10px;height:10px;"></i> api_request</span>
                      <?php endif; ?>
                    </td>
                    <td class="tnum" style="font-weight:600;">₹<?= number_format($order['amount'], 2) ?></td>
                    <td style="white-space:nowrap;">
                      <?php if ($order['status'] === 'success'): ?>
                        <span class="badge badge-success"><i data-lucide="check" style="width:11px;height:11px;"></i> Paid</span>
                      <?php elseif ($order['status'] === 'pending'): ?>
                        <span class="badge badge-warning"><i data-lucide="clock" style="width:11px;height:11px;"></i> Pending</span>
                      <?php else: ?>
                        <span class="badge badge-danger"><i data-lucide="x" style="width:11px;height:11px;"></i> <?= htmlspecialchars(ucfirst($order['status'])) ?></span>
                      <?php endif; ?>
                    </td>
                    <td class="tnum" style="color:var(--color-ink-mute);font-size:12px;white-space:nowrap;"><?= $order['created_at'] ?></td>
                  </tr>
                  <?php endforeach; ?>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <!-- Right: Action Cards -->
        <div style="display:flex;flex-direction:column;gap:16px;">
          <!-- Ban / Reset Key -->
          <div class="card" style="margin-bottom:0;">
            <div class="card-title" style="margin-bottom:14px;"><i data-lucide="shield-alert" style="width:18px;height:18px;color:#ef4444;"></i> Account Actions</div>
            <div style="display:flex;flex-direction:column;gap:8px;">
              <form method="POST">
                <input type="hidden" name="action" value="login_as_client">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">
                <button type="submit" class="btn btn-primary" style="width:100%;"><i data-lucide="log-in" style="width:15px;height:15px;"></i> Login as Client</button>
              </form>
              <hr style="border:none; border-top:1px solid var(--color-hairline); margin: 4px 0;">
              <form method="POST" onsubmit="return confirm('<?= $user['status'] === 'banned' ? 'Unban' : 'Ban' ?> this user?');">
                <input type="hidden" name="action" value="toggle_ban">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">
                <button type="submit" class="btn <?= $user['status'] === 'banned' ? 'btn-primary' : 'btn-danger' ?>" style="width:100%;">
                  <i data-lucide="<?= $user['status'] === 'banned' ? 'check-circle' : 'ban' ?>" style="width:15px;height:15px;"></i> <?= $user['status'] === 'banned' ? 'Unban User' : 'Ban User' ?>
                </button>
              </form>
              <form method="POST" onsubmit="return confirm('Generate a new primary key? Old key #1 will stop working.');">
                <input type="hidden" name="action" value="reset_api">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">
                <button type="submit" class="btn btn-secondary" style="width:100%;"><i data-lucide="refresh-cw" style="width:15px;height:15px;"></i> Reset Primary Key</button>
              </form>
              <form method="POST" onsubmit="return confirm('WARNING: Are you absolutely sure you want to DELETE this user and all their data? This action cannot be undone.');">
                <input type="hidden" name="action" value="delete_user">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">
                <button type="submit" class="btn btn-danger" style="width:100%; margin-top:4px;"><i data-lucide="trash-2" style="width:15px;height:15px;"></i> Delete User Account</button>
              </form>
            </div>
          </div>

          <!-- Set Chances -->
          <div class="card" style="margin-bottom:0;">
            <div class="card-title" style="margin-bottom:12px;font-size:14px;"><i data-lucide="rotate-ccw" style="width:16px;height:16px;color:#f59e0b;"></i> Set Reset Chances</div>
            <form method="POST" style="display:flex;gap:8px;">
              <input type="hidden" name="action" value="set_reset_chances">
              <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">
              <input type="number" name="reset_chances" class="form-input tnum" value="<?= (int)$user['reset_chances'] ?>" min="0" required style="padding:8px 12px;">
              <button type="submit" class="btn btn-secondary" style="white-space:nowrap;">Set</button>
            </form>
          </div>

          <!-- Change Password -->
          <div class="card" style="margin-bottom:0;">
            <div class="card-title" style="margin-bottom:12px;font-size:14px;"><i data-lucide="lock" style="width:16px;height:16px;color:#9333ea;"></i> Change Password</div>
            <form method="POST" style="display:flex;gap:8px;">
              <input type="hidden" name="action" value="change_password">
              <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">
              <input type="password" name="new_password" class="form-input" placeholder="Min 6 chars" required style="padding:8px 12px;">
              <button type="submit" class="btn btn-secondary" style="white-space:nowrap;">Save</button>
            </form>
          </div>


          <!-- Clear User Transaction Data -->
          <div class="card" style="margin-bottom:0; border:1px solid #fca5a5; background:#fef2f2;">
            <div class="card-title" style="margin-bottom:6px; font-size:14px; color:#dc2626;"><i data-lucide="trash-2" style="width:16px;height:16px;color:#dc2626;"></i> Clear Transaction Data</div>
            <p style="font-size:12px; color:#991b1b; margin-bottom:12px; line-height:1.5;">Wipe all past API orders, payment links, and reset total revenue/request counters for this user account.</p>
            <form method="POST" onsubmit="return confirm('⚠️ WARNING: Are you sure you want to completely erase all transaction history and reset stats for <?= htmlspecialchars(addslashes($user['name'])) ?>? This cannot be undone.');">
              <input type="hidden" name="action" value="clear_user_data">
              <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">
              <button type="submit" class="btn btn-danger" style="width:100%; background:#dc2626; color:#fff; border:none; font-weight:600; padding:10px; display:flex; align-items:center; justify-content:center; gap:6px; font-size:13px; white-space:normal; line-height:1.2; text-align:center;"><i data-lucide="alert-triangle" style="width:15px;height:15px;color:#fff;flex-shrink:0;"></i> Wipe All Transaction History</button>
            </form>
          </div>

        </div>
      </div>

    </div>
  </main>
</div>
<script>
if (document.getElementById('searchTxn')) {
  document.getElementById('searchTxn').addEventListener('keyup', function() {
    let filter = this.value.toLowerCase();
    let rows = document.querySelectorAll('.table tbody tr');
    rows.forEach(row => {
      if(row.querySelector('td[colspan]')) return;
      let text = row.innerText.toLowerCase();
      row.style.display = text.includes(filter) ? '' : 'none';
    });
  });
}
if (window.lucide) { lucide.createIcons(); }
</script>
</body>
</html>
