<?php
session_start();

require_once '../models/User.php';
require_once '../include/Helper.php';
require_once '../models/Document.php';
require_once '../models/Withdrawal.php';
require_once '../models/Invoice.php';
require_once '../include/DatabaseConn.php';
require_once '../include/Constants.php';
require_once '../models/Admin.php';
require_once '../models/Wallet.php';
require_once '../models/Referral.php';


$db = new DatabaseConn();
$link = $db->connect();
$conn = $link;

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['emails']) && is_array($_POST['emails']) && isset($_POST['userEmail'])) {
        $emails = $_POST['emails'];
        $userEmail = mysqli_real_escape_string($conn, $_POST['userEmail']);

        foreach ($emails as $email) {
            $email = mysqli_real_escape_string($conn, $email);

            // Check if the email exists in the users table
            $user_query = "SELECT * FROM users WHERE email = '$email'";
            $user_result = mysqli_query($conn, $user_query);
            if (mysqli_num_rows($user_result) > 0) {
                // Insert into referral table
                $time = time();
                $insert_query = "INSERT INTO referral (user, guest, date, status) VALUES ('$userEmail', '$email', '$time', '')";
                mysqli_query($conn, $insert_query);
            }
        }
        // Return success response
        echo json_encode(['status' => 'success']);
    } else {
        // Invalid data
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Invalid data']);

    }
} else {
    // Invalid request method
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
}
?>

