<?php
require_once __DIR__ . '/../config.php';
session_start();

if (isset($_SESSION['agent_id'])) {
    header('Location: dashboard.php');
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

    $conn = db();
    $stmt = $conn->prepare("SELECT * FROM agents WHERE email = ? AND status = 'active' LIMIT 1");
    $stmt->bind_param('s', $email);
    $stmt->execute();
    $a = $stmt->get_result()->fetch_assoc();

    if ($a && password_verify($password, $a['password_hash'])) {
        session_regenerate_id(true);
        $_SESSION['agent_id'] = $a['id'];
        $_SESSION['agent_name'] = $a['business_name'];
        header('Location: dashboard.php');
        exit;
    } else {
        $error = 'Invalid email or password.';
    }
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Agent Login</title>
<link rel="stylesheet" href="../style.css">
<style>.agent-box { max-width: 400px; margin: 80px auto; text-align: center; }</style>
</head>
<body>
<div class="container agent-box">
    <h1>🤝 Reseller Portal</h1>
    <p style="color:var(--muted);margin-bottom:20px">Log in to manage your WiFi business.</p>

    <?php if ($error): ?><div class="flash flash-error"><?= htmlspecialchars($error) ?></div><?php endif; ?>

    <form method="POST">
        <div class="form-row"><input type="email" name="email" placeholder="Email Address" required></div>
        <div class="form-row"><input type="password" name="password" placeholder="Password" required></div>
        <button class="btn-buy" type="submit">Log In</button>
    </form>
</div>
</body>
</html>