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

function handleInvitation($coname, $email, $role, $slots, $type) {
    $token = bin2hex(random_bytes(16));

    try {
        $insertData = [
            'company_name' => $coname,
            'email' => $email,
            'token' => $token,
            'role' => $role,
            'dealer_slots' => $slots
        ];

        $result = insertData('invitations', $insertData);

        if ($result) {

            $apiKey = 'MAILERSEND_API_KEY';
            $templateId = 'neqvygm12jdg0p7w';
            $fromEmail = 'no-reply@yourdomain.com';
            $fromName = 'Your Application';
            $name = 'Welcome';
            $name1 = 'New User';

            $actionUrl = "https://yourdomain.com/register.php?token=$token";

            $data = [
                'from' => [
                    'email' => $fromEmail,
                    'name' => $fromName
                ],
                'to' => [
                    [
                        'email' => $email,
                        'name' => $name1
                    ]
                ],
                'subject' => 'You’ve been invited to join',
                'template_id' => $templateId,
                'personalization' => [
                    [
                        'email' => $email,
                        'data' => [
                            'name' => $name,
                            'company' => $coname,
                            'action_url' => $actionUrl,
                            'support_email' => 'support@invisibleintercom.com'
                        ]
                    ]
                ]
            ];

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . '/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);

            if ($curlError) {
                throw new Exception("MailerSend CURL Error: " . $curlError);
            } elseif ($httpCode >= 400) {
                throw new Exception("MailerSend HTTP Error $httpCode: " . $response);
            }

            curl_close($ch);
            return true;
        } else {
            throw new Exception("Failed to create invitation in the database.");
        }
    } catch (Exception $e) {
        throw new Exception("Error: " . $e->getMessage());
    }
}

function resendInvitation($userId) {
    $userDatas = fetchData('invitations', ['id' => $userId]);
    $token = $userDatas[0]['token'];
    $email = $userDatas[0]['email'];
    $coname = $userDatas[0]['company_name'];

    $apiKey = 'MAILERSEND_API_KEY';
    $templateId = '3yxj6ljo3w14do2r';
    $fromEmail = 'no-reply@yourdomain.com';
    $fromName = 'Your Application';
    $name = 'Welcome';
    $name1 = 'New User';

    $actionUrl = "https://yourdomain.com/register.php?token=$token";

    $data = [
        'from' => [
            'email' => $fromEmail,
            'name' => $fromName
        ],
        'to' => [
            [
                'email' => $email,
                'name' => $name1
            ]
        ],
        'subject' => 'You’ve been invited to join',
        'template_id' => $templateId,
        'personalization' => [
            [
                'email' => $email,
                'data' => [
                    'name' => $name,
                    'company' => $coname,
                    'action_url' => $actionUrl,
                    'support_email' => 'support@invisibleintercom.com'
                ]
            ]
        ]
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . '/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);

    if ($curlError) {
        throw new Exception("MailerSend CURL Error: " . $curlError);
    } elseif ($httpCode >= 400) {
        throw new Exception("MailerSend HTTP Error $httpCode: " . $response);
    }

    curl_close($ch);
    return "Success";
}
