<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

// Add or update points
if (isset($_POST['save_points'])) {
    $customer_id = intval($_POST['customer_id']);
    $points = intval($_POST['points']);

    // check existing
    $r = $conn->query("SELECT * FROM loyalty_points WHERE customer_id = $customer_id")->fetch_assoc();
    if ($r) {
        $conn->query("UPDATE loyalty_points SET points = $points WHERE customer_id = $customer_id");
    } else {
        $conn->query("INSERT INTO loyalty_points (customer_id, points) VALUES ($customer_id, $points)");
    }
    echo "<script>alert('Points saved');window.location='loyalty.php';</script>";
    exit;
}

// Fetch customers list for dropdown
$customers = $conn->query("SELECT id,name FROM customers ORDER BY name ASC");

// Fetch points list
$points_list = $conn->query("SELECT lp.*, c.name FROM loyalty_points lp JOIN customers c ON lp.customer_id = c.id ORDER BY lp.points DESC");
?>

<div class="container mt-4">
     <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>
    <h3>Loyalty Points Management</h3>
    <hr>

    <form method="POST" class="row g-3 mb-4">
        <div class="col-md-6">
            <select name="customer_id" class="form-control" required>
                <option value="">-- Select Customer --</option>
                <?php while($c = $customers->fetch_assoc()): ?>
                    <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['name']) ?></option>
                <?php endwhile; ?>
            </select>
        </div>
        <div class="col-md-3">
            <input type="number" name="points" class="form-control" placeholder="Points" required>
        </div>
        <div class="col-md-3">
            <button name="save_points" class="btn btn-success w-100">Save Points</button>
        </div>
    </form>

    <h4>Points Leaderboard</h4>
    <table class="table table-bordered table-striped">
        <thead class="bg-dark text-white">
            <tr><th>#</th><th>Customer</th><th>Points</th><th>Last Updated</th></tr>
        </thead>
        <tbody>
            <?php $i=1; while($row = $points_list->fetch_assoc()): ?>
                <tr>
                    <td><?= $i ?></td>
                    <td><?= htmlspecialchars($row['name']) ?></td>
                    <td><?= intval($row['points']) ?></td>
                    <td><?= $row['last_updated'] ?></td>
                </tr>
            <?php $i++; endwhile; ?>
        </tbody>
    </table>
</div>

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