<?php

include "../helper_functions/data_request.php";

function sendInvitation($pdo, $email, $role, $custom, $invited_by, $creator_type, $type, $uFName, $uProperty) {
    $token = bin2hex(random_bytes(16));

    if ($role == 7) {
        $name = 'Welcome' . " " . $uFName;
    }else {
        $name = 'Welcome';
    }

    try {
        $insertData = [
            'name' => $name,
            'email' => $email,
            'token' => $token,
            'role' => $role,
            'role_type' => $custom,
            'invited_by' => $invited_by,
            'creator_type' => $creator_type
        ];

        $propData = fetchDataSingle('properties', ['id' => $uProperty]);
        $propName = $propData['name'] ?? null;

        if ($type === 'dealer_admins') {
            $result = insertData('dealer_invitations', $insertData);
            $template = 'neqvygm12jdg0p7w';
            $link = "https://yourdomain.com/admin_register.php?token=$token";
        } else {
            $result = insertData('property_invitations', $insertData);
            $template = 'z3m5jgrm2ox4dpyo';
            $link = "https://yourdomain.com/register.php?token=$token";
        }

        if ($result) {
            return sendMailerSendEmail(
                $email,
                'Invitation to Register',
                $template,
                [
                    'name' => $name,
                    'action_url' => $link,
                    'email' => $email,
                    'company' => $propName,
                    'support_email' => 'support@invisibleintercom.com'
                ]
            ) ? $token : false;
        } else {
            return false;
        }
    } catch (Exception $e) {
        error_log("Error: " . $e->getMessage());
        return false;
    }
}

function resendInvitation($email) {

    $userData = fetchDataSingle('property_invitations', ['email' => $email]);
    $type = 'property_users';
    if ($userData) {
        $name = $userData['name'];
    }
    $template = 'z3m5jgrm2ox4dpyo';
    $linkBase = "https://yourdomain.com/register.php?token=$token";

    if (!$userData) {

        $userData = fetchDataSingle('dealer_invitations', ['email' => $email]);
        $type = 'dealer_admins';
        $name = $userData['name'];
        $template = 'neqvygm12jdg0p7w';
        $linkBase = "https://yourdomain.com/register.php?token=$token";
    }

    if (!$userData || empty($userData['token'])) {
        return json_encode(['error' => 'User not found or no token']);
    }

    $token = $userData['token'];
    $link = $linkBase . $token;

    $success = sendMailerSendEmail(
        $email,
        'Invitation to Register',
        $template,
        [
            'name' => $name,
            'action_url' => $link,
            'email' => $email,
            'support_email' => 'support@invisibleintercom.com'
        ]
    );

    return $success ? "Success" : "Failed";
}

function multipropInvitation($email, $property) {
    return sendMailerSendEmail(
        $email,
        'Great News!',
        'v69oxl5wn1xl785k',
        [
            'email' => $email,
            'property' => $property,
            'support_email' => 'support@invisibleintercom.com'
        ]
    );
}

function sendMailerSendEmail($toEmail, $subject, $templateId, $personalizationData) {
    $apiKey = 'apikey';
    $fromEmail = 'email';
    $fromName = 'Your Application';

    $data = [
        'from' => [
            'email' => $fromEmail,
            'name' => $fromName
        ],
        'to' => [
            [
                'email' => $toEmail,
                'name' => $toEmail
            ]
        ],
        'subject' => $subject,
        'template_id' => $templateId,
        'personalization' => [
            [
                'email' => $toEmail,
                'data' => $personalizationData
            ]
        ]
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_CAINFO, '../auth/cacert.pem');
    curl_setopt($ch, CURLOPT_URL, 'https://api.mailersend.com/v1/email');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey
    ]);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($curlError) {
        error_log("MailerSend CURL Error: $curlError");
        return false;
    } elseif ($httpCode >= 400) {
        error_log("MailerSend HTTP Error $httpCode: $response");
        return false;
    }

    return true;
}
