<?php
session_start();

// Database connection
$conn = new mysqli("localhost", "root", "", "reseller_db");
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Authentication Logic
if (isset($_POST['login'])) {
    $email = $_POST['email'];
    $password = $_POST['password'];
    $stmt = $conn->prepare("SELECT * FROM resellers WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();
        if (password_verify($password, $user['password'])) {
            $_SESSION['reseller_id'] = $user['id'];
        } else {
            echo "Invalid password";
            exit();
        }
    } else {
        echo "Invalid email";
        exit();
    }
}

// Logout Logic
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: ?");
    exit();
}

// Protect Dashboard
if (!isset($_SESSION['reseller_id'])) {
    echo '<form method="POST">';
    echo '<h2>Login</h2>';
    echo '<input type="email" name="email" placeholder="Email" required><br>';
    echo '<input type="password" name="password" placeholder="Password" required><br>';
    echo '<button type="submit" name="login">Login</button>';
    echo '</form>';
    exit();
}

$reseller_id = $_SESSION['reseller_id'];
$res = $conn->query("SELECT * FROM resellers WHERE id = $reseller_id")->fetch_assoc();
$rate = $res['rate'];

// Functions
function getCount($table, $rid, $conn) {
    return $conn->query("SELECT COUNT(*) as c FROM $table WHERE reseller_id = $rid")->fetch_assoc()['c'];
}
function getSum($table, $rid, $conn) {
    return $conn->query("SELECT SUM(amount) as s FROM $table WHERE reseller_id = $rid AND status='success'")->fetch_assoc()['s'] ?? 0;
}

$activations = getCount('activations', $reseller_id, $conn);
$paid = getSum('payments', $reseller_id, $conn);
$due = ($activations * $rate) - $paid;

// Payment Processing
if (isset($_POST['make_payment'])) {
    $amount = $_POST['amount'];
    $conn->query("INSERT INTO payments (reseller_id, amount, status, date) VALUES ($reseller_id, $amount, 'success', NOW())");
    echo "<script>alert('Payment Recorded');location.href='?';</script>";
    exit();
}

// Fetch Replacements
$replacements = $conn->query("SELECT * FROM replacements WHERE reseller_id = $reseller_id");
?>

<!DOCTYPE html>
<html>
<head>
    <title>Reseller Dashboard</title>
    <style>
        body { font-family: Arial; padding: 20px; background: #f5f5f5; }
        .card { background: #fff; padding: 20px; margin-bottom: 20px; box-shadow: 0 0 10px #ccc; }
        input, button { padding: 8px; margin-top: 10px; width: 100%; }
    </style>
</head>
<body>
    <h2>Welcome, <?php echo $res['name']; ?> | <a href="?logout=true">Logout</a></h2>
    <div class="card">
        <h3>Your Stats</h3>
        <p>Activations: <b><?php echo $activations; ?></b></p>
        <p>Rate: ₹<b><?php echo $rate; ?></b></p>
        <p>Paid: ₹<b><?php echo $paid; ?></b></p>
        <p>Due: ₹<b><?php echo $due; ?></b></p>
    </div>

    <div class="card">
        <h3>Make a Payment</h3>
        <form method="POST">
            <input type="number" name="amount" value="<?php echo $due; ?>" required>
            <button type="submit" name="make_payment">Pay Now</button>
        </form>
    </div>

    <div class="card">
        <h3>Replacements</h3>
        <ul>
        <?php while ($r = $replacements->fetch_assoc()) {
            echo "<li>" . $r['product'] . " - " . $r['reason'] . "</li>";
        } ?>
        </ul>
    </div>
</body>
</html>