<?php
ob_start();
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit;
}

require_once 'db.php';

$stmt = $pdo->query("SELECT background_image, logo_image FROM branding WHERE id = 1");
$branding = $stmt->fetch();
$backgroundImage = $branding['background_image'] ?? '';
$logoImage = $branding['logo_image'] ?? '';

$target_user_id = $_POST['target_user_id'] ?? '';
$mode = $_POST['mode'] ?? 'preview';
$deleteReferrals = isset($_POST['delete_referrals']);
$deleteLeads = isset($_POST['delete_leads']);
$deleteResults = '';
$referralCount = null;
$leadCount = null;
$userFound = false;
$user_numeric_id = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $target_user_id !== '') {
    try {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE user_id = ?");
        $stmt->execute([$target_user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user) {
            $userFound = true;
            $user_numeric_id = $user['id'];

            $referralCountStmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE referrer_id = ?");
            $referralCountStmt->execute([$target_user_id]);
            $referralCount = $referralCountStmt->fetchColumn();

            $leadCountStmt = $pdo->prepare("SELECT COUNT(*) FROM leads WHERE user_id = ?");
            $leadCountStmt->execute([$user_numeric_id]);
            $leadCount = $leadCountStmt->fetchColumn();

            // If mode is delete, proceed with deletion
            if ($mode === 'delete') {
                if ($deleteReferrals) {
                    $stmt = $pdo->prepare("DELETE FROM users WHERE referrer_id = ?");
                    $stmt->execute([$target_user_id]);
                    $deleteResults .= "<div class='alert alert-warning'>🧹 Deleted <strong>$referralCount</strong> referral(s) of <strong>$target_user_id</strong>.</div>";
                }

                if ($deleteLeads) {
                    $stmt = $pdo->prepare("DELETE FROM leads WHERE user_id = ?");
                    $stmt->execute([$user_numeric_id]);
                    $deleteResults .= "<div class='alert alert-warning'>🧽 Deleted <strong>$leadCount</strong> lead(s) of <strong>$target_user_id</strong>.</div>";
                }

                $stmt = $pdo->prepare("DELETE FROM users WHERE user_id = ?");
                $stmt->execute([$target_user_id]);
                $deleteResults .= "<div class='alert alert-success'>✅ Deleted user '<strong>$target_user_id</strong>' successfully.</div>";

                // Clear input after deletion
                $target_user_id = '';
                $userFound = false;
            }
        } else {
            $deleteResults = "<div class='alert alert-danger'>❌ User '<strong>$target_user_id</strong>' not found.</div>";
        }
    } catch (Exception $e) {
        $deleteResults = "<div class='alert alert-danger'>Error: " . $e->getMessage() . "</div>";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Delete User, Referrals & Leads</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .form-box { max-width: 640px; margin: 50px auto; }
    </style>
</head>
<body style="margin:0;">
<div style="display:flex; min-height:100vh;">

  <!-- Sidebar -->
  <div class="admin-sidebar" style="width:220px; background:#343a40; padding:20px;">
    <?php include 'google-translate-widget-front-end.php'; ?>
    <?php include 'admin-links.php'; ?>
  </div>

  <!-- Main content -->
  <div style="flex-grow: 1; padding: 20px;">
    <div class="card shadow-sm">
        <div class="card-body">
            <h3 class="card-title">🗑️ Delete User, Referrals & Leads</h3>

            <form method="post">
                <input type="hidden" name="mode" value="<?= $userFound && $mode === 'preview' ? 'delete' : 'preview' ?>">

                <div class="mb-3">
                    <label for="target_user_id" class="form-label">Enter Username (user_id):</label>
                    <input type="text" class="form-control" id="target_user_id" name="target_user_id" required placeholder="e.g. username" value="<?= htmlspecialchars($target_user_id) ?>">
                </div>

                <?php if ($userFound && $referralCount !== null && $leadCount !== null && $mode === 'preview'): ?>
                    <div class="alert alert-info">
                        <strong>Heads up:</strong><br>
                        This user has <strong><?= $referralCount ?></strong> referral(s) and <strong><?= $leadCount ?></strong> lead(s).
                    </div>

                    <button type="submit" class="btn btn-primary w-100">Show Deletion Options</button>
                <?php elseif ($userFound && $mode === 'delete'): ?>
                    <div class="alert alert-info">
                        You're about to delete user <strong><?= htmlspecialchars($target_user_id) ?></strong>.<br>
                        They have <strong><?= $referralCount ?></strong> referral(s) and <strong><?= $leadCount ?></strong> lead(s).
                    </div>

                    <div class="form-check mb-2">
                        <input class="form-check-input" type="checkbox" name="delete_referrals" id="delete_referrals" <?= $deleteReferrals ? 'checked' : '' ?>>
                        <label class="form-check-label" for="delete_referrals">
                            Also delete user's referrals
                        </label>
                    </div>

                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="delete_leads" id="delete_leads" <?= $deleteLeads ? 'checked' : '' ?>>
                        <label class="form-check-label" for="delete_leads">
                            Also delete user's leads
                        </label>
                    </div>

                    <button type="submit" class="btn btn-danger w-100">✅ Confirm and Delete</button>
                <?php else: ?>
                    <button type="submit" class="btn btn-primary w-100">Check User Summary</button>
                <?php endif; ?>
            </form>

            <div class="mt-4">
                <?= $deleteResults ?>
                
                <?php include 'admin-footer.php'; ?>

            </div>
        </div>
    </div>
</div>
</body>
</html>
