<?php
require_once __DIR__ . '/config/config.php';
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST['email'];
    $passwordInput = $_POST['password'];

    $stmt = $conn->prepare("SELECT id, full_name, email, phone, password, account_balance, referral_code FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows == 1) {
        $stmt->bind_result($id, $fullName, $email, $phone, $hashedPassword, $accountBalance, $referralCode);
        $stmt->fetch();
        if (password_verify($passwordInput, $hashedPassword)) {
            $_SESSION['user_id'] = $id;
            $_SESSION['user_name'] = $fullName;
            $_SESSION['user_email'] =  $email;
            $_SESSION['account_balance'] = $accountBalance;
            echo json_encode(["success" => true, "message" => "Login successful."]);
        } else {
            echo json_encode(["success" => false, "message" => "Incorrect password."]);
        }
    } else {
        echo json_encode(["success" => false, "message" => "User not found."]);
    }

    $stmt->close();
    $conn->close();
}

?>