<?php
// ------------------------------------------------------------
// 1. Load DB, helpers, auth BEFORE any HTML
// ------------------------------------------------------------
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireLogin();

$id = $_GET['id'] ?? null;
if (!$id) {
    setFlash('danger', 'User ID missing.');
    header('Location: users.php');
    exit;
}

// Fetch user
$userStmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$userStmt->execute([':id' => $id]);
$user = $userStmt->fetch();
if (!$user) {
    setFlash('danger', 'User not found.');
    header('Location: users.php');
    exit;
}

// ------------------------------------------------------------
// 2. Handle actions (toggle active / add wallet transaction)
// ------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // --- Toggle active/inactive ---
    if (isset($_POST['toggle_active'])) {
        $newStatus = $user['is_active'] ? 0 : 1;
        $upd = $pdo->prepare("UPDATE users SET is_active = :status WHERE id = :id");
        $upd->execute([':status' => $newStatus, ':id' => $id]);

        // Refresh user data so the page shows the new status
        $userStmt->execute([':id' => $id]);
        $user = $userStmt->fetch();

        setFlash('success', 'User status updated.');
        header("Location: user_details.php?id=$id");
        exit;
    }

    // --- Add manual wallet transaction ---
    if (isset($_POST['add_transaction'])) {
        $amount = (float)($_POST['amount'] ?? 0);
        $type   = $_POST['type'] ?? 'credit';
        $desc   = trim($_POST['description'] ?? '');

        if ($amount > 0) {
            // Current balance
            $balanceStmt = $pdo->prepare(
                "SELECT COALESCE(SUM(CASE WHEN type='credit' THEN amount ELSE -amount END), 0)
                 FROM wallet_transactions WHERE user_id = :uid"
            );
            $balanceStmt->execute([':uid' => $id]);
            $currentBalance = $balanceStmt->fetchColumn();
            $newBalance = ($type === 'credit') ? $currentBalance + $amount : $currentBalance - $amount;

            $ins = $pdo->prepare(
                "INSERT INTO wallet_transactions (user_id, type, amount, balance_after, description)
                 VALUES (:uid, :type, :amount, :balance, :desc)"
            );
            $ins->execute([
                ':uid'     => $id,
                ':type'    => $type,
                ':amount'  => $amount,
                ':balance' => $newBalance,
                ':desc'    => $desc ?: 'Manual adjustment'
            ]);

            setFlash('success', 'Transaction added.');
        } else {
            setFlash('danger', 'Amount must be > 0.');
        }

        header("Location: user_details.php?id=$id");
        exit;
    }
}

// ------------------------------------------------------------
// 3. Fetch data for display (after possible updates)
// ------------------------------------------------------------
$walletBalance = $pdo->prepare(
    "SELECT COALESCE(SUM(CASE WHEN type='credit' THEN amount ELSE -amount END), 0)
     FROM wallet_transactions WHERE user_id = :uid"
);
$walletBalance->execute([':uid' => $id]);
$balance = $walletBalance->fetchColumn();

// Recent orders (last 10)
$ordersStmt = $pdo->prepare(
    "SELECT id, order_number, status, total_selling, created_at
     FROM orders WHERE user_id = :uid ORDER BY created_at DESC LIMIT 10"
);
$ordersStmt->execute([':uid' => $id]);
$recentOrders = $ordersStmt->fetchAll();

// Active subscriptions
$subsStmt = $pdo->prepare(
    "SELECT us.*, sp.plan_name
     FROM user_subscriptions us
     JOIN subscription_plans sp ON us.plan_id = sp.id
     WHERE us.user_id = :uid
     ORDER BY us.started_at DESC"
);
$subsStmt->execute([':uid' => $id]);
$userSubs = $subsStmt->fetchAll();

// Recent wallet transactions (last 20)
$txnStmt = $pdo->prepare(
    "SELECT * FROM wallet_transactions WHERE user_id = :uid ORDER BY created_at DESC LIMIT 20"
);
$txnStmt->execute([':uid' => $id]);
$transactions = $txnStmt->fetchAll();
?>

<?php
// 4. Now include the full layout (header) – no output before this point
require_once '../includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h1 class="h2">Reseller: <?= htmlspecialchars($user['reseller_name']) ?></h1>
    <div>
        <a href="users.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left"></i> Back to List</a>
        <form method="POST" style="display:inline-block">
            <button type="submit" name="toggle_active"
                    class="btn btn-<?= $user['is_active'] ? 'warning' : 'success' ?> ms-2">
                <?= $user['is_active'] ? 'Deactivate' : 'Activate' ?>
            </button>
        </form>
    </div>
</div>

<?php $flash = getFlash(); if ($flash): ?>
<div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show" role="alert">
    <?= htmlspecialchars($flash['message']) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="row">
    <!-- Left: User Info, Wallet, Subscriptions -->
    <div class="col-md-4">
        <div class="card shadow-sm mb-4">
            <div class="card-header bg-white"><h5 class="mb-0">Personal Info</h5></div>
            <div class="card-body">
                <p><strong>Shop:</strong> <?= htmlspecialchars($user['shop_name']) ?></p>
                <p><strong>Email:</strong> <?= htmlspecialchars($user['email']) ?></p>
                <p><strong>Phone:</strong> <?= htmlspecialchars($user['phone']) ?></p>
                <p><strong>Bkash:</strong> <?= htmlspecialchars($user['bkash_number'] ?? 'N/A') ?></p>
                <p>
                    <strong>Status:</strong>
                    <?php if ($user['is_active']): ?>
                        <span class="badge bg-success">Active</span>
                    <?php else: ?>
                        <span class="badge bg-danger">Inactive</span>
                    <?php endif; ?>
                    <?php if ($user['is_verified']): ?>
                        <span class="badge bg-info">Verified</span>
                    <?php else: ?>
                        <span class="badge bg-secondary">Unverified</span>
                    <?php endif; ?>
                </p>
                <p><small class="text-muted">Registered: <?= date('d M Y', strtotime($user['created_at'])) ?></small></p>
            </div>
        </div>

        <div class="card shadow-sm mb-4">
            <div class="card-header bg-white d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Wallet Balance</h5>
                <span class="badge bg-dark fs-6">৳<?= number_format($balance, 2) ?></span>
            </div>
            <div class="card-body">
                <h6>Add Manual Transaction</h6>
                <form method="POST" class="row g-2">
                    <div class="col-12">
                        <select name="type" class="form-select">
                            <option value="credit">Credit (+)</option>
                            <option value="debit">Debit (-)</option>
                        </select>
                    </div>
                    <div class="col-7">
                        <input type="number" step="0.01" name="amount" class="form-control" placeholder="Amount" required>
                    </div>
                    <div class="col-5">
                        <button type="submit" name="add_transaction" class="btn btn-sm btn-primary w-100">Add</button>
                    </div>
                    <div class="col-12">
                        <input type="text" name="description" class="form-control form-control-sm" placeholder="Reason (optional)">
                    </div>
                </form>
            </div>
        </div>

        <div class="card shadow-sm mb-4">
            <div class="card-header bg-white"><h5 class="mb-0">Subscriptions</h5></div>
            <div class="card-body p-0">
                <?php if (empty($userSubs)): ?>
                    <div class="p-3 text-muted">No subscriptions.</div>
                <?php else: ?>
                    <ul class="list-group list-group-flush">
                        <?php foreach ($userSubs as $sub): ?>
                            <li class="list-group-item">
                                <strong><?= htmlspecialchars($sub['plan_name']) ?></strong>
                                <br><small>
                                    <?= date('d M Y', strtotime($sub['started_at'])) ?> – 
                                    <?= date('d M Y', strtotime($sub['expires_at'])) ?>
                                </small>
                                <br>
                                <span class="badge bg-<?= $sub['status'] === 'active' ? 'success' : ($sub['status'] === 'expired' ? 'warning' : 'secondary') ?>">
                                    <?= htmlspecialchars($sub['status']) ?>
                                </span>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Right: Orders & Wallet Transactions -->
    <div class="col-md-8">
        <div class="card shadow-sm mb-4">
            <div class="card-header bg-white"><h5 class="mb-0">Recent Orders</h5></div>
            <div class="card-body p-0">
                <?php if (empty($recentOrders)): ?>
                    <div class="p-3 text-muted">No orders yet.</div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped mb-0">
                            <thead>
                                <tr>
                                    <th>Order #</th>
                                    <th>Status</th>
                                    <th>Total</th>
                                    <th>Date</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($recentOrders as $ord): ?>
                                    <tr>
                                        <td>#<?= htmlspecialchars($ord['order_number']) ?></td>
                                        <td><span class="badge bg-<?= $ord['status'] === 'delivered' ? 'success' : 'warning' ?>"><?= htmlspecialchars($ord['status']) ?></span></td>
                                        <td>৳<?= number_format($ord['total_selling'], 2) ?></td>
                                        <td><?= date('d M Y', strtotime($ord['created_at'])) ?></td>
                                        <td><a href="order_details.php?id=<?= $ord['id'] ?>" class="btn btn-sm btn-outline-primary">View</a></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="card shadow-sm mb-4">
            <div class="card-header bg-white"><h5 class="mb-0">Wallet Transactions</h5></div>
            <div class="card-body p-0">
                <?php if (empty($transactions)): ?>
                    <div class="p-3 text-muted">No transactions.</div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-sm mb-0">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Type</th>
                                    <th>Amount</th>
                                    <th>Balance After</th>
                                    <th>Description</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($transactions as $txn): ?>
                                    <tr>
                                        <td><?= date('d M Y H:i', strtotime($txn['created_at'])) ?></td>
                                        <td>
                                            <span class="badge bg-<?= $txn['type'] === 'credit' ? 'success' : 'danger' ?>">
                                                <?= $txn['type'] ?>
                                            </span>
                                        </td>
                                        <td class="text-<?= $txn['type'] === 'credit' ? 'success' : 'danger' ?>">
                                            <?= $txn['type'] === 'debit' ? '-' : '+' ?>৳<?= number_format($txn['amount'], 2) ?>
                                        </td>
                                        <td>৳<?= number_format($txn['balance_after'], 2) ?></td>
                                        <td><?= htmlspecialchars($txn['description'] ?? '') ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>