<?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') {
    $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 for this user.";
            $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 === 'assign_plan') {
        $planId = $_POST['plan_id'] ?? '';
        $plan = getPlanById($planId);
        if ($plan) {
            $now = nowIST();
            $user['plan_id'] = $plan['id'];
            $user['plan_label'] = $plan['label'];
            $user['plan_expires_at'] = (clone $now)->modify('+' . $plan['days'] . ' days')->format('Y-m-d H:i:s');
            saveUser($user);
            $message = 'Plan assigned: ' . $plan['label'];
            $messageType = 'success';
        }
    } elseif ($action === 'custom_expiry') {
        $days = intval($_POST['custom_days'] ?? 0);
        if ($days > 0) {
            $now = nowIST();
            $user['plan_expires_at'] = (clone $now)->modify("+$days days")->format('Y-m-d H:i:s');
            $user['plan_label'] = 'Custom (' . $days . ' days, admin-assigned)';
            saveUser($user);
            $message = "Expiry extended by $days days.";
            $messageType = 'success';
        }
    }

    $user = getUserById($userId);
}

$plans = getPlans();

$allOrders = readJson(ORDERS_FILE);
$userOrders = array_values(array_filter($allOrders, function($o) use ($userId) {
    return ($o['user_id'] ?? '') === $userId;
}));
usort($userOrders, function($a, $b) {
    return ($b['created_at_timestamp'] ?? 0) <=> ($a['created_at_timestamp'] ?? 0);
});

$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;
}

$pageTitle = 'Manage User';
$pageSub = htmlspecialchars($user['name']) . ' · ' . htmlspecialchars($user['email']);
include __DIR__ . '/../includes/admin_header.php';
?>

<div class="admin-wrap">
  <a href="users.php" style="font-size:13.5px; font-weight:600;">← Back to Users</a>

  <?php if ($message): ?>
    <div class="alert alert-<?= $messageType === 'success' ? 'ok' : 'warn' ?>" style="margin-top:16px;"><?= htmlspecialchars($message) ?></div>
  <?php endif; ?>

  <div class="card">
    <h2 class="card-title">User info</h2>
    <div class="flex items-center" style="gap:14px; margin-bottom:16px;">
      <?php if (!empty($user['avatar'])): ?>
        <img src="<?= htmlspecialchars($user['avatar']) ?>" style="width:56px;height:56px;border-radius:50%;object-fit:cover;border:2px solid var(--primary);" alt="">
      <?php else: ?>
        <div class="avatar-fallback" style="width:56px;height:56px;font-size:22px;"><?= mb_substr(htmlspecialchars($user['name']), 0, 1) ?></div>
      <?php endif; ?>
      <div>
        <p style="font-size:15px; font-weight:700; color:var(--ink);"><?= htmlspecialchars($user['name']) ?></p>
        <p style="font-size:13px; color:var(--muted);"><?= htmlspecialchars($user['email']) ?></p>
      </div>
    </div>

    <div class="stat-grid" style="margin-bottom:0;">
      <div class="stat-card">
        <div class="stat-label">Current plan</div>
        <div class="stat-value" style="font-size:17px;"><?= htmlspecialchars($user['plan_label']) ?></div>
      </div>
      <div class="stat-card">
        <div class="stat-label">Expires</div>
        <div class="stat-value" style="font-size:17px;"><?= date('d M Y, h:i A', strtotime($user['plan_expires_at'])) ?></div>
      </div>
      <div class="stat-card">
        <div class="stat-label">Status</div>
        <div class="stat-value" style="font-size:17px;"><span class="badge <?= $user['status'] === 'banned' ? 'badge-red' : 'badge-green' ?>"><?= ucfirst($user['status']) ?></span></div>
      </div>
      <div class="stat-card">
        <div class="stat-label">Gmail</div>
        <div class="stat-value" style="font-size:17px;"><?= $user['gmail_connected'] ? '<span class="badge badge-green">Connected</span>' : '<span class="badge badge-gray">No</span>' ?></div>
      </div>
      <div class="stat-card">
        <div class="stat-label">Reset chances</div>
        <div class="stat-value" style="font-size:17px;"><?= (int)$user['reset_chances'] ?>/10</div>
      </div>
    </div>

    <h3 style="font-size:14px; font-weight:600; margin:22px 0 10px;">API keys (<?= count($user['api_keys']) ?>/3)</h3>
    <?php foreach ($user['api_keys'] as $idx => $keyData): ?>
      <div class="key-row">
        <span class="key-text"><?= htmlspecialchars($keyData['key']) ?></span>
        <span class="key-label" style="margin:0;"><?= 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="key_index" value="<?= $idx ?>">
            <button type="submit" class="btn btn-danger btn-sm">Remove</button>
          </form>
        <?php endif; ?>
      </div>
    <?php endforeach; ?>

    <div class="row mt-24">
      <form method="POST" onsubmit="return confirm('<?= $user['status'] === 'banned' ? 'Unban' : 'Ban' ?> this user?');">
        <input type="hidden" name="action" value="toggle_ban">
        <button type="submit" class="btn <?= $user['status'] === 'banned' ? 'btn-primary' : 'btn-danger' ?>">
          <?= $user['status'] === 'banned' ? 'Unban user' : 'Ban user' ?>
        </button>
      </form>
      <form method="POST" onsubmit="return confirm('Generate a new key #1 for this user? Old key #1 will stop working.');">
        <input type="hidden" name="action" value="reset_api">
        <button type="submit" class="btn btn-secondary">Reset key #1</button>
      </form>
    </div>
  </div>

  <div class="card">
    <h2 class="card-title">Add custom API key</h2>
    <div class="card-sub">Use after receiving payment outside the app (cash, COD, etc). Max 3 keys per user.</div>
    <form method="POST">
      <input type="hidden" name="action" value="add_custom_key">
      <label class="label" for="customKeyName">Key name (letters/numbers/underscores only)</label>
      <input class="input" type="text" id="customKeyName" name="custom_key_name" placeholder="e.g. RahulShop" maxlength="30" <?= count($user['api_keys']) >= 3 ? 'disabled' : 'required' ?>>
      <div class="row mt-24">
        <button type="submit" class="btn btn-primary" <?= count($user['api_keys']) >= 3 ? 'disabled' : '' ?>>
          <?= count($user['api_keys']) >= 3 ? 'Max 3 keys reached' : 'Generate & add key' ?>
        </button>
      </div>
    </form>
  </div>

  <div class="card">
    <h2 class="card-title">Set reset chances</h2>
    <div class="card-sub">Give this user any number of "Generate New API" chances — shared counter across all their keys.</div>
    <form method="POST">
      <input type="hidden" name="action" value="set_reset_chances">
      <label class="label" for="resetChances">Number of chances</label>
      <input class="input" type="number" id="resetChances" name="reset_chances" value="<?= (int)$user['reset_chances'] ?>" min="0" required>
      <div class="row mt-24">
        <button type="submit" class="btn btn-primary">Set chances</button>
      </div>
    </form>
  </div>

  <div class="card">
    <h2 class="card-title">Change password</h2>
    <form method="POST">
      <input type="hidden" name="action" value="change_password">
      <label class="label" for="newPass">New password</label>
      <input class="input" type="password" id="newPass" name="new_password" placeholder="Minimum 6 characters" required>
      <div class="row mt-24">
        <button type="submit" class="btn btn-primary">Update password</button>
      </div>
    </form>
  </div>

  <div class="card">
    <h2 class="card-title">Assign plan</h2>
    <form method="POST">
      <input type="hidden" name="action" value="assign_plan">
      <label class="label" for="assignPlan">Select plan</label>
      <select class="input" id="assignPlan" name="plan_id" required>
        <?php foreach ($plans as $plan): ?>
          <option value="<?= $plan['id'] ?>"><?= htmlspecialchars($plan['label']) ?> - ₹<?= $plan['price'] ?></option>
        <?php endforeach; ?>
      </select>
      <div class="row mt-24">
        <button type="submit" class="btn btn-primary">Assign this plan (free)</button>
      </div>
    </form>

    <form method="POST" style="margin-top:24px; padding-top:24px; border-top:1px solid var(--hairline-soft);">
      <input type="hidden" name="action" value="custom_expiry">
      <label class="label" for="customDays">Or extend by custom days</label>
      <input class="input" type="number" id="customDays" name="custom_days" placeholder="e.g. 45" min="1">
      <div class="row mt-24">
        <button type="submit" class="btn btn-secondary">Extend expiry</button>
      </div>
    </form>
  </div>

  <div class="card">
    <h2 class="card-title">Payments summary</h2>
    <div class="stat-grid">
      <div class="stat-card">
        <div class="stat-label">Total paid</div>
        <div class="stat-value up">₹<?= number_format($userPaid, 2) ?></div>
      </div>
      <div class="stat-card">
        <div class="stat-label">Pending</div>
        <div class="stat-value">₹<?= number_format($userPending, 2) ?></div>
      </div>
      <div class="stat-card">
        <div class="stat-label">Failed / expired</div>
        <div class="stat-value down">₹<?= number_format($userFailed, 2) ?></div>
      </div>
    </div>

    <div class="table-card" style="margin-top:16px;">
      <table class="data-table">
        <tr>
          <th>Order ID</th>
          <th>Type</th>
          <th>Amount</th>
          <th>Status</th>
          <th>Created</th>
        </tr>
        <?php foreach ($userOrders as $o): ?>
          <tr>
            <td class="mono" style="font-size:12px;"><?= htmlspecialchars($o['order_id']) ?></td>
            <td><?= htmlspecialchars($o['type'] ?? '-') ?></td>
            <td>₹<?= number_format(floatval($o['amount'] ?? 0), 2) ?></td>
            <td>
              <?php if ($o['status'] === 'success'): ?>
                <span class="badge badge-green">Success</span>
              <?php elseif ($o['status'] === 'pending'): ?>
                <span class="badge badge-amber">Pending</span>
              <?php else: ?>
                <span class="badge badge-red">Failed</span>
              <?php endif; ?>
            </td>
            <td style="font-size:12px;"><?= htmlspecialchars($o['created_at'] ?? '-') ?></td>
          </tr>
        <?php endforeach; ?>
        <?php if (empty($userOrders)): ?>
          <tr><td colspan="5" class="empty-row">No orders from this user yet.</td></tr>
        <?php endif; ?>
      </table>
    </div>
  </div>
</div>

<?php include __DIR__ . '/../includes/admin_footer.php'; ?>
