<?php
require_once __DIR__ . '/../config/database.php';

requireLogin();
requireAnyRole(['admin', 'super_admin']);

$db = Database::getInstance();

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
if ($id <= 0) {
    $_SESSION['flash']['danger'] = 'Invalid user ID.';
    header('Location: users.php');
    exit;
}

// Handle AI Premium Copilot access grant/revoke actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ai_premium_action'])) {
    $action = $_POST['ai_premium_action'];

    try {
        if ($action === 'grant') {
            // If no completed ai_premium payment exists, create a manual one
            $existing = $db->get(
                "SELECT id FROM payments WHERE user_id = ? AND payment_type = ? AND payment_status = ? LIMIT 1",
                [$id, 'ai_premium', 'completed']
            );

            if (!$existing) {
                $db->insert('payments', [
                    'user_id' => $id,
                    'course_id' => null,
                    'enrollment_id' => null,
                    'appointment_id' => null,
                    'payment_type' => 'ai_premium',
                    'amount' => 0.0,
                    'currency' => 'USD',
                    'payment_method' => 'manual',
                    'payment_status' => 'completed',
                    'transaction_id' => 'ai_premium_manual_' . time(),
                    'gateway_response' => json_encode(['source' => 'admin_toggle']),
                    'paid_at' => formatDate(),
                ]);
            }

            $_SESSION['flash']['success'] = 'AI Premium Copilot access has been granted for this user.';
        } elseif ($action === 'revoke') {
            // Mark any completed ai_premium records as revoked
            $db->update(
                'payments',
                ['payment_status' => 'revoked'],
                'user_id = ? AND payment_type = ? AND payment_status = ?',
                [$id, 'ai_premium', 'completed']
            );

            $_SESSION['flash']['success'] = 'AI Premium Copilot access has been revoked for this user.';
        }
    } catch (Exception $e) {
        $_SESSION['flash']['danger'] = 'Failed to update AI Premium access: ' . $e->getMessage();
    }

    header('Location: users_view.php?id=' . $id);
    exit;
}

$user = $db->get(
    "SELECT u.*, ur.role, ur.permissions, ur.assigned_at
     FROM users u
     LEFT JOIN user_roles ur ON u.id = ur.user_id
     WHERE u.id = ?",
    [$id]
);

if (!$user) {
    $_SESSION['flash']['danger'] = 'User not found.';
    header('Location: users.php');
    exit;
}

// Additional stats
$enrollments = $db->get(
    "SELECT COUNT(*) AS cnt FROM course_enrollments WHERE student_id = ?",
    [$id]
);

$certificates = $db->get(
    "SELECT COUNT(*) AS cnt FROM certificates WHERE student_id = ? AND is_revoked = 0",
    [$id]
);

// Check AI Premium Copilot access status via payments table
$aiPremiumPayment = null;
$hasAiPremium = false;
try {
    $aiPremiumPayment = $db->get(
        "SELECT * FROM payments WHERE user_id = ? AND payment_type = ? AND payment_status = ? ORDER BY paid_at DESC LIMIT 1",
        [$id, 'ai_premium', 'completed']
    );
    if ($aiPremiumPayment && isset($aiPremiumPayment['id'])) {
        $hasAiPremium = true;
    }
} catch (Exception $e) {
    $aiPremiumPayment = null;
    $hasAiPremium = false;
}

$pageTitle = 'View User';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">User Details</h1>
    <p class="text-muted mb-0">View profile and activity</p>
  </div>
  <div>
    <a href="users_edit.php?id=<?php echo $id; ?>" class="btn btn-primary me-2">
      <i class="fas fa-edit me-2"></i>Edit
    </a>
    <a href="users.php" class="btn btn-outline-secondary">
      <i class="fas fa-arrow-left me-2"></i>Back to Users
    </a>
  </div>
</div>

<div class="row">
  <div class="col-md-4">
    <div class="card">
      <div class="card-body text-center">
        <div class="avatar avatar-xl mb-3">
          <div class="avatar-initial rounded-circle bg-primary">
            <?php echo strtoupper(substr($user['first_name'] ?? '', 0, 1) . substr($user['last_name'] ?? '', 0, 1)); ?>
          </div>
        </div>
        <h5 class="mb-1"><?php echo htmlspecialchars(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')); ?></h5>
        <p class="text-muted mb-3">@<?php echo htmlspecialchars($user['username'] ?? ''); ?></p>
        <?php
          $roleValue = $user['role'] ?? '';
          $roleBadgeClass = $roleValue === 'super_admin' ? 'danger' : ($roleValue === 'admin' ? 'warning' : 'secondary');
        ?>
        <span class="badge bg-<?php echo $roleBadgeClass; ?>">
          <?php echo htmlspecialchars(ucwords(str_replace('_',' ', $roleValue))); ?>
        </span>
      </div>
    </div>
  </div>

  <div class="col-md-8">
    <div class="card">
      <div class="card-header">
        <h5 class="mb-0">Profile Information</h5>
      </div>
      <div class="card-body">
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Username</strong></div>
          <div class="col-sm-9"><?php echo htmlspecialchars($user['username'] ?? ''); ?></div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Email</strong></div>
          <div class="col-sm-9"><?php echo htmlspecialchars($user['email'] ?? ''); ?></div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Region</strong></div>
          <div class="col-sm-9"><?php echo htmlspecialchars(ucfirst($user['region'] ?? '')); ?></div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Status</strong></div>
          <div class="col-sm-9">
            <?php
              $statusValue = $user['status'] ?? '';
              $statusBadgeClass = $statusValue === 'active' ? 'success' : ($statusValue === 'suspended' ? 'danger' : 'secondary');
            ?>
            <span class="badge bg-<?php echo $statusBadgeClass; ?>">
              <?php echo htmlspecialchars(ucfirst($statusValue)); ?>
            </span>
          </div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Permissions</strong></div>
          <div class="col-sm-9">
            <?php
                $perms = [];
                if (!empty($user['permissions'])) {
                    $decoded = is_string($user['permissions']) ? json_decode($user['permissions'], true) : $user['permissions'];
                    if (is_array($decoded)) {
                        foreach ($decoded as $k => $v) {
                            if ($v) $perms[] = $k;
                        }
                    }
                }
            ?>
            <?php if (empty($perms)): ?>
                <small class="text-muted">None</small>
            <?php else: ?>
                <?php foreach ($perms as $p): ?>
                    <span class="badge bg-info me-1 small"><?php echo htmlspecialchars($p); ?></span>
                <?php endforeach; ?>
            <?php endif; ?>
          </div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Joined</strong></div>
          <div class="col-sm-9"><?php echo htmlspecialchars($user['created_at'] ?? ''); ?></div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Last Login</strong></div>
          <div class="col-sm-9"><?php echo htmlspecialchars($user['last_login'] ?? 'Never'); ?></div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="row mt-4">
  <div class="col-md-6">
    <div class="card">
      <div class="card-header">
        <h5 class="mb-0">Learning Stats</h5>
      </div>
      <div class="card-body">
        <div class="row text-center">
          <div class="col-4">
            <h4 class="mb-1"><?php echo (int)($enrollments['cnt'] ?? 0); ?></h4>
            <small class="text-muted">Enrollments</small>
          </div>
          <div class="col-4">
            <h4 class="mb-1"><?php echo (int)($certificates['cnt'] ?? 0); ?></h4>
            <small class="text-muted">Certificates</small>
          </div>
          <div class="col-4">
            <h4 class="mb-1">&mdash;</h4>
            <small class="text-muted">Points</small>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="col-md-6">
    <div class="card">
      <div class="card-header">
        <h5 class="mb-0">Recent Activity</h5>
      </div>
      <div class="card-body">
        <p class="text-muted">Activity log coming soon.</p>
        <hr>
        <h6 class="mb-3">AI Premium Copilot Access</h6>
        <?php if ($hasAiPremium): ?>
            <p class="mb-1">
                <span class="badge bg-success">Active</span>
            </p>
            <?php if (!empty($aiPremiumPayment['paid_at'])): ?>
                <p class="small text-muted mb-1">Granted on: <?php echo htmlspecialchars($aiPremiumPayment['paid_at']); ?></p>
            <?php endif; ?>
            <form method="post" class="mt-2">
                <input type="hidden" name="ai_premium_action" value="revoke">
                <button type="submit" class="btn btn-sm btn-outline-danger">
                    Revoke AI Premium Copilot Access
                </button>
            </form>
        <?php else: ?>
            <p class="mb-2">
                <span class="badge bg-secondary">Not Active</span>
            </p>
            <p class="small text-muted mb-2">
                This user does not currently have access to the AI Premium Cybersecurity Copilot.
            </p>
            <form method="post">
                <input type="hidden" name="ai_premium_action" value="grant">
                <button type="submit" class="btn btn-sm btn-primary">
                    Grant AI Premium Copilot Access
                </button>
            </form>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

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