<?php
session_start();
require "db.php";

if (isset($_POST['action']) && $_POST['action'] == "register") {

    $fullname = trim($_POST['fullname']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

    $check = $conn->query("SELECT * FROM agents WHERE email='$email'");
    if ($check->num_rows > 0) {
        $_SESSION['error'] = "Email already registered!";
        header("Location: agent-auth.php");
        exit();
    }

    $sql = "INSERT INTO agents (fullname, email, phone, password) 
            VALUES ('$fullname', '$email', '$phone', '$password')";
    if ($conn->query($sql)) {
        $_SESSION['success'] = "Registration successful! You can now login.";
    } else {
        $_SESSION['error'] = "Something went wrong.";
    }

    header("Location: agent-auth.php");
    exit();
}


if (isset($_POST['action']) && $_POST['action'] == "login") {

    $email = trim($_POST['email']);
    $password = trim($_POST['password']);

    $check = $conn->query("SELECT * FROM agents WHERE email='$email'");
    if ($check->num_rows == 1) {
        $agent = $check->fetch_assoc();

        if (password_verify($password, $agent['password'])) {
            $_SESSION['agent_id'] = $agent['id'];
            $_SESSION['agent_name'] = $agent['fullname'];

            header("Location: dashboard.php");
            exit();
        }
    }

    $_SESSION['error'] = "Invalid login details!";
    header("Location: agent-auth.php");
    exit();
}
?>
