<?php
$pageTitle  = 'User Detail';
$activePage = 'users';

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/../db.php';

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

// Load user
$userStmt = $pdo->prepare("SELECT * FROM users WHERE chat_id = ?");
$userStmt->execute([$targetId]);
$user = $userStmt->fetch(PDO::FETCH_ASSOC);
if (!$user) {
    header('Location: users.php');
    exit;
}

$flash     = '';
$flashType = 'success';

// ─── POST actions ────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_verify()) {
    $action = $_POST['action'] ?? '';

    if ($action === 'grant_credits') {
        $amount = (int)($_POST['amount'] ?? 0);
        if ($amount > 0 && $amount <= 10000) {
            $pdo->prepare("UPDATE users SET credits = credits + ? WHERE chat_id = ?")->execute([$amount, $targetId]);
            $pdo->prepare("INSERT INTO credit_transactions (chat_id, amount, type, description) VALUES (?, ?, 'admin_grant', 'Admin panel grant')")
                ->execute([$targetId, $amount]);
            // Notify user on Telegram
            $notif = "🎉 <b>{$amount} credits</b> have been added to your account by the admin!\nUse /status to check your balance.";
            @file_get_contents("https://api.telegram.org/bot{$config['telegram_token']}/sendMessage?" .
                http_build_query(['chat_id' => $targetId, 'text' => $notif, 'parse_mode' => 'HTML']));
            $flash = "Granted {$amount} credits. User has been notified on Telegram.";
        } else {
            $flash = 'Invalid amount (1–10000).';
            $flashType = 'warning';
        }

    } elseif ($action === 'deduct_credits') {
        $amount = (int)($_POST['amount'] ?? 0);
        if ($amount > 0) {
            $pdo->prepare("UPDATE users SET credits = GREATEST(0, credits - ?) WHERE chat_id = ?")->execute([$amount, $targetId]);
            $pdo->prepare("INSERT INTO credit_transactions (chat_id, amount, type, description) VALUES (?, ?, 'admin_grant', 'Admin panel deduction')")
                ->execute([$targetId, -$amount]);
            $flash = "Deducted {$amount} credits.";
        }

    } elseif ($action === 'grant_sub') {
        $plan = $_POST['plan_type'] ?? 'monthly';
        $validPlans = ['monthly' => 30, '3month' => 90, '6month' => 180, '12month' => 365];
        $days = $validPlans[$plan] ?? 30;

        $existing = $pdo->prepare("SELECT id FROM subscriptions WHERE chat_id = ? AND status = 'active' AND expires_at > NOW() LIMIT 1");
        $existing->execute([$targetId]);
        $row = $existing->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            $pdo->prepare("UPDATE subscriptions SET expires_at = DATE_ADD(expires_at, INTERVAL ? DAY), plan_type = ? WHERE id = ?")
                ->execute([$days, $plan, $row['id']]);
            $flash = "Extended subscription by {$days} days.";
        } else {
            $pdo->prepare("INSERT INTO subscriptions (chat_id, plan_type, status, expires_at, granted_by) VALUES (?, ?, 'active', DATE_ADD(NOW(), INTERVAL ? DAY), 'admin')")
                ->execute([$targetId, $plan, $days]);
            $flash = "Granted {$plan} subscription ({$days} days).";
        }
        $planLabels = ['monthly' => '1 Month', '3month' => '3 Months', '6month' => '6 Months', '12month' => '12 Months'];
        $notif = "⭐ <b>Premium Subscription Activated!</b>\n\nYour <b>{$planLabels[$plan]}</b> subscription has been granted by the admin.\n\nEnjoy unlimited diet &amp; workout plans!";
        @file_get_contents("https://api.telegram.org/bot{$config['telegram_token']}/sendMessage?" .
            http_build_query(['chat_id' => $targetId, 'text' => $notif, 'parse_mode' => 'HTML']));

    } elseif ($action === 'revoke_sub') {
        $pdo->prepare("UPDATE subscriptions SET status = 'cancelled' WHERE chat_id = ? AND status = 'active'")
            ->execute([$targetId]);
        $flash     = "Subscription revoked.";
        $flashType = 'warning';
        $notif = "⚠️ Your Premium subscription has been cancelled. Contact support if you think this is an error.";
        @file_get_contents("https://api.telegram.org/bot{$config['telegram_token']}/sendMessage?" .
            http_build_query(['chat_id' => $targetId, 'text' => $notif, 'parse_mode' => 'HTML']));

    } elseif ($action === 'send_message') {
        $msg = trim($_POST['message'] ?? '');
        if ($msg !== '') {
            $url  = "https://api.telegram.org/bot{$config['telegram_token']}/sendMessage";
            $data = http_build_query(['chat_id' => $targetId, 'text' => $msg, 'parse_mode' => 'HTML']);
            $ctx  = stream_context_create(['http' => ['method' => 'POST', 'header' => 'Content-Type: application/x-www-form-urlencoded', 'content' => $data]]);
            $resp = @file_get_contents($url, false, $ctx);
            $ok   = $resp && (json_decode($resp, true)['ok'] ?? false);
            $flash     = $ok ? 'Message sent successfully.' : 'Failed to send message — check token / user may have blocked the bot.';
            $flashType = $ok ? 'success' : 'danger';
        }
    }

    // Re-fetch user after any update
    $userStmt->execute([$targetId]);
    $user = $userStmt->fetch(PDO::FETCH_ASSOC);
}

// ─── Ancillary data ──────────────────────────────────────────────────────────
$dietCount = $pdo->prepare("SELECT COUNT(*) FROM diet_plans WHERE chat_id = ?");
$dietCount->execute([$targetId]);
$dietCount = (int)$dietCount->fetchColumn();

$workoutCount = $pdo->prepare("SELECT COUNT(*) FROM workout_plans WHERE chat_id = ?");
$workoutCount->execute([$targetId]);
$workoutCount = (int)$workoutCount->fetchColumn();

$weightLogs = $pdo->prepare("SELECT weight, logged_at FROM progress WHERE chat_id = ? ORDER BY logged_at DESC LIMIT 10");
$weightLogs->execute([$targetId]);
$weightLogs = $weightLogs->fetchAll(PDO::FETCH_ASSOC);

$txns = $pdo->prepare("SELECT * FROM credit_transactions WHERE chat_id = ? ORDER BY id DESC LIMIT 15");
$txns->execute([$targetId]);
$txns = $txns->fetchAll(PDO::FETCH_ASSOC);

$subStmt = $pdo->prepare("SELECT * FROM subscriptions WHERE chat_id = ? ORDER BY id DESC LIMIT 1");
$subStmt->execute([$targetId]);
$sub = $subStmt->fetch(PDO::FETCH_ASSOC);
$hasSub = $sub && $sub['status'] === 'active' && strtotime($sub['expires_at']) > time();

$pageTitle = htmlspecialchars($user['first_name'] ?? "User #{$targetId}");

require_once __DIR__ . '/_header.php';
?>

<div class="page-header d-flex align-items-center gap-2">
    <a href="users.php" class="btn btn-sm btn-outline-secondary"><i class="bi bi-arrow-left"></i></a>
    <h4 class="fw-bold mb-0"><?= htmlspecialchars($user['first_name'] ?? 'Unknown') ?></h4>
    <code class="text-muted" style="font-size:.85rem"><?= $targetId ?></code>
</div>

<?php if ($flash): ?>
<div class="alert alert-<?= $flashType ?> alert-dismissible fade show py-2">
    <?= htmlspecialchars($flash) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="row g-3">

    <!-- Left column: Profile + Activity summary -->
    <div class="col-md-5">

        <!-- Activity counters -->
        <div class="card table-card mb-3">
            <div class="card-body">
                <div class="row text-center g-0">
                    <div class="col border-end">
                        <div class="fs-4 fw-bold text-primary"><?= (int)$user['credits'] ?></div>
                        <div class="text-muted" style="font-size:.72rem">Credits</div>
                    </div>
                    <div class="col border-end">
                        <div class="fs-4 fw-bold text-success"><?= $dietCount ?></div>
                        <div class="text-muted" style="font-size:.72rem">Diet Plans</div>
                    </div>
                    <div class="col border-end">
                        <div class="fs-4 fw-bold text-info"><?= $workoutCount ?></div>
                        <div class="text-muted" style="font-size:.72rem">Workouts</div>
                    </div>
                    <div class="col">
                        <div class="fs-4 fw-bold text-warning"><?= count($weightLogs) ?></div>
                        <div class="text-muted" style="font-size:.72rem">Logs</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Profile fields -->
        <div class="card table-card mb-3">
            <div class="card-header bg-white border-0 pt-3 pb-1">
                <h6 class="fw-semibold mb-0">Profile</h6>
            </div>
            <div class="card-body p-0">
            <?php
            $profileRows = [
                'Weight'  => ($user['weight']  ?? '—') . ($user['weight']  ? ' kg' : ''),
                'Height'  => ($user['height']  ?? '—') . ($user['height']  ? ' cm' : ''),
                'Age'     => $user['age']  ?? '—',
                'Gender'  => $user['gender'] ?? '—',
                'Goal'    => str_replace('_', ' ', $user['goal'] ?? '—'),
                'Diet'    => $user['diet']   ?? '—',
                'Budget'  => $user['budget'] ? '₹' . number_format($user['budget']) : '—',
                'Wake'    => $user['wake_time'] ?? '—',
                'Bed'     => $user['bed_time']  ?? '—',
                'Workout' => $user['workout']   ?? '—',
                'Notes'   => $user['notes']     ?? '—',
                'BMI'     => $user['bmi']       ?? '—',
                'BMR'     => ($user['bmr'] ?? '—') . ($user['bmr'] ? ' kcal' : ''),
                'TDEE'    => ($user['maintenance_calories'] ?? '—') . ($user['maintenance_calories'] ? ' kcal' : ''),
                'Joined'  => $user['created_at'] ? date('d M Y', strtotime($user['created_at'])) : '—',
            ];
            foreach ($profileRows as $label => $val): ?>
            <div class="d-flex justify-content-between px-3 py-2 border-bottom" style="font-size:.82rem">
                <span class="text-muted"><?= $label ?></span>
                <span class="fw-medium text-end" style="max-width:60%"><?= htmlspecialchars((string)$val) ?></span>
            </div>
            <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Right column: Actions + History -->
    <div class="col-md-7">

        <!-- Grant / Deduct Credits -->
        <div class="card table-card mb-3">
            <div class="card-header bg-white border-0 pt-3 pb-1">
                <h6 class="fw-semibold mb-0">Manage Credits</h6>
            </div>
            <div class="card-body">
                <form method="POST" class="d-flex flex-wrap gap-2 align-items-end mb-3">
                    <input type="hidden" name="_csrf" value="<?= csrf_token() ?>">
                    <div>
                        <label class="form-label small mb-1">Amount</label>
                        <input type="number" id="creditAmount" name="amount" class="form-control" min="1" max="10000" placeholder="e.g. 20" required style="width:120px">
                    </div>
                    <button name="action" value="grant_credits" class="btn btn-success px-3">
                        <i class="bi bi-plus-circle me-1"></i>Grant
                    </button>
                    <button name="action" value="deduct_credits" class="btn btn-outline-danger px-3"
                            onclick="return confirm('Deduct credits from this user?')">
                        <i class="bi bi-dash-circle me-1"></i>Deduct
                    </button>
                </form>
                <div class="d-flex gap-2 flex-wrap">
                    <?php foreach ([5, 10, 20, 50, 100] as $q): ?>
                    <button type="button" class="btn btn-outline-secondary btn-sm quick-val" data-val="<?= $q ?>">+<?= $q ?></button>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- Subscription -->
        <div class="card table-card mb-3">
            <div class="card-header bg-white border-0 pt-3 pb-1 d-flex justify-content-between align-items-center">
                <h6 class="fw-semibold mb-0">Subscription</h6>
                <?php if ($hasSub): ?>
                <span class="badge bg-success-subtle text-success">⭐ Active</span>
                <?php else: ?>
                <span class="badge bg-secondary-subtle text-secondary">None</span>
                <?php endif; ?>
            </div>
            <div class="card-body">
                <?php if ($sub): ?>
                <div class="mb-3 p-2 rounded" style="background:#f9fafb;font-size:.82rem">
                    <?php
                    $planLabels = ['monthly' => '1 Month', '3month' => '3 Months', '6month' => '6 Months', '12month' => '12 Months'];
                    $daysLeft = max(0, (int)ceil((strtotime($sub['expires_at']) - time()) / 86400));
                    ?>
                    <div class="d-flex justify-content-between mb-1">
                        <span class="text-muted">Plan</span>
                        <span class="fw-semibold"><?= htmlspecialchars($planLabels[$sub['plan_type']] ?? $sub['plan_type']) ?></span>
                    </div>
                    <div class="d-flex justify-content-between mb-1">
                        <span class="text-muted">Status</span>
                        <span class="fw-semibold <?= $hasSub ? 'text-success' : 'text-danger' ?>">
                            <?= $hasSub ? 'Active' : ucfirst($sub['status']) ?>
                        </span>
                    </div>
                    <div class="d-flex justify-content-between mb-1">
                        <span class="text-muted">Expires</span>
                        <span class="fw-semibold"><?= date('d M Y', strtotime($sub['expires_at'])) ?></span>
                    </div>
                    <?php if ($hasSub): ?>
                    <div class="d-flex justify-content-between">
                        <span class="text-muted">Days Left</span>
                        <span class="fw-semibold <?= $daysLeft <= 7 ? 'text-warning' : '' ?>"><?= $daysLeft ?>d</span>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>

                <form method="POST" class="d-flex flex-wrap gap-2 align-items-end mb-2">
                    <input type="hidden" name="_csrf" value="<?= csrf_token() ?>">
                    <input type="hidden" name="action" value="grant_sub">
                    <div>
                        <label class="form-label small mb-1">Grant / Extend</label>
                        <select name="plan_type" class="form-select form-select-sm" style="width:auto">
                            <option value="monthly">1 Month</option>
                            <option value="3month">3 Months</option>
                            <option value="6month">6 Months</option>
                            <option value="12month">12 Months</option>
                        </select>
                    </div>
                    <button class="btn btn-sm btn-success px-3"><i class="bi bi-star me-1"></i>Grant</button>
                </form>

                <?php if ($hasSub): ?>
                <form method="POST" onsubmit="return confirm('Revoke this subscription? User will be notified.')">
                    <input type="hidden" name="_csrf" value="<?= csrf_token() ?>">
                    <input type="hidden" name="action" value="revoke_sub">
                    <button class="btn btn-sm btn-outline-danger px-3"><i class="bi bi-x-circle me-1"></i>Revoke Subscription</button>
                </form>
                <?php endif; ?>
            </div>
        </div>

        <!-- Send Message -->
        <div class="card table-card mb-3">
            <div class="card-header bg-white border-0 pt-3 pb-1">
                <h6 class="fw-semibold mb-0">Send Direct Message via Telegram</h6>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="_csrf" value="<?= csrf_token() ?>">
                    <input type="hidden" name="action" value="send_message">
                    <textarea name="message" class="form-control mb-2" rows="3"
                              placeholder="Message text (HTML tags allowed: &lt;b&gt;, &lt;i&gt;, &lt;code&gt;, &lt;a href=''&gt;)" required></textarea>
                    <button class="btn btn-primary px-4"><i class="bi bi-send me-1"></i>Send</button>
                </form>
            </div>
        </div>

        <!-- Weight log -->
        <?php if (!empty($weightLogs)): ?>
        <div class="card table-card mb-3">
            <div class="card-header bg-white border-0 pt-3 pb-1">
                <h6 class="fw-semibold mb-0">Weight History</h6>
            </div>
            <div class="table-responsive">
                <table class="table table-sm mb-0">
                    <thead><tr><th>Weight</th><th>Date</th></tr></thead>
                    <tbody>
                    <?php foreach ($weightLogs as $log): ?>
                    <tr>
                        <td class="fw-semibold"><?= $log['weight'] ?> kg</td>
                        <td class="text-muted" style="font-size:.8rem"><?= date('d M Y', strtotime($log['logged_at'])) ?></td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>

        <!-- Credit transactions -->
        <?php if (!empty($txns)): ?>
        <div class="card table-card">
            <div class="card-header bg-white border-0 pt-3 pb-1 d-flex justify-content-between">
                <h6 class="fw-semibold mb-0">Credit Transactions</h6>
                <a href="transactions.php?chat=<?= $targetId ?>" class="small text-decoration-none text-primary">All →</a>
            </div>
            <div class="table-responsive">
                <table class="table table-sm mb-0">
                    <thead><tr><th>Amount</th><th>Type</th><th>Description</th><th>Date</th></tr></thead>
                    <tbody>
                    <?php foreach ($txns as $tx): ?>
                    <tr>
                        <td class="fw-bold <?= $tx['amount'] > 0 ? 'text-success' : 'text-danger' ?>">
                            <?= $tx['amount'] > 0 ? '+' : '' ?><?= $tx['amount'] ?>
                        </td>
                        <td><span class="badge bg-secondary-subtle text-secondary" style="font-size:.68rem"><?= htmlspecialchars($tx['type']) ?></span></td>
                        <td class="text-muted" style="font-size:.78rem"><?= htmlspecialchars($tx['description'] ?? '') ?></td>
                        <td class="text-muted" style="font-size:.75rem"><?= date('d M, H:i', strtotime($tx['created_at'])) ?></td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
document.querySelectorAll('.quick-val').forEach(btn => {
    btn.addEventListener('click', () => {
        document.getElementById('creditAmount').value = btn.dataset.val;
    });
});
</script>

<?php require_once __DIR__ . '/_footer.php'; ?>
