<?php
session_start();
include 'includes/db.php';
header('Content-Type: application/json');

// 🔐 Helper
function clean($data) {
    return htmlspecialchars(trim($data));
}

// ================= LOGIN =================
if (isset($_POST['login'])) {

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

    if (empty($email) || empty($password)) {
        echo json_encode(["status" => "error", "message" => "All fields are required"]);
        exit();
    }

    $result = $conn->query("SELECT * FROM users WHERE email='$email'");

    // ❗ DB error check
    if (!$result) {
        echo json_encode([
            "status" => "error",
            "message" => "Database error: " . $conn->error
        ]);
        exit();
    }

    if ($result->num_rows > 0) {

        $user = $result->fetch_assoc();

        if (password_verify($password, $user['password'])) {

            $_SESSION['user_id'] = $user['id'];

            echo json_encode([
                "status" => "success",
                "message" => "Login successful"
            ]);
            exit();

        } else {
            echo json_encode([
                "status" => "error",
                "message" => "Wrong password"
            ]);
            exit();
        }

    } else {
        echo json_encode([
            "status" => "error",
            "message" => "Account not found"
        ]);
        exit();
    }
}

// ================= SIGNUP =================
if (isset($_POST['signup'])) {

    $name = clean($_POST['name']);
    $email = clean($_POST['email']);
    $password = $_POST['password'];
    $phone = $_POST['phone'];

    if (empty($name) || empty($email) || empty($password)) {
        echo json_encode([
            "status" => "error",
            "message" => "All fields are required"
        ]);
        exit();
    }

    // 🔍 Check duplicate email
    $check = $conn->query("SELECT id FROM users WHERE email='$email'");

    if (!$check) {
        echo json_encode([
            "status" => "error",
            "message" => "Database error: " . $conn->error
        ]);
        exit();
    }

    if ($check->num_rows > 0) {
        echo json_encode([
            "status" => "error",
            "message" => "Email already exists"
        ]);
        exit();
    }

    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    $insert = $conn->query("INSERT INTO users (name, email, password, phone) VALUES ('$name','$email','$hashedPassword','$phone')");

    if (!$insert) {
        echo json_encode([
            "status" => "error",
            "message" => "Database error: " . $conn->error
        ]);
        exit();
    }

    $_SESSION['user_id'] = $conn->insert_id;

    echo json_encode([
        "status" => "success",
        "message" => "Signup successful"
    ]);
    exit();
}

// ================= DEFAULT =================
echo json_encode([
    "status" => "error",
    "message" => "Invalid request"
]);
exit();
?>