<?php
require '../helper_functions/data_request.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST['email'];
    $token = bin2hex(random_bytes(50));

    $matchedTable = null;

    if (count(fetchData('users', ['email' => $email])) > 0) {
        $matchedTable = 'users';
    } elseif (count(fetchData('property_users', ['email' => $email])) > 0) {
        $matchedTable = 'property_users';
    } elseif (count(fetchData('dealer_admins', ['email' => $email])) > 0) {
        $matchedTable = 'dealer_admins';
    } else {
        echo "Email address not found.";
        if (!headers_sent()) {
            header("refresh:3;url=../../login.php");
        }
        exit();
    }

    switch ($matchedTable) {
        case 'users':
            $userData = fetchData('users', ['email' => $email]);
            $name = $userData[0]['firstname'] ?? 'Unknown';
            break;

        case 'property_users':
            $userData = fetchData('property_users', ['email' => $email]);
            $usersid = $userData[0]['id'];
            $nameData = fetchData('property_users_data', ['property_user' => $usersid]);
            $name = $nameData[0]['firstname'];
            break;

        case 'dealer_admins':
            $userData = fetchData('dealer_admins', ['email' => $email]);
            $name = $userData[0]['firstname'] ?? 'Unknown';
            break;
    }

    $result = insertData('password_resets', ['email' => $email, 'token' => $token]);

    if ($result) {

        $resetLink = "https://yourdomain.com/recover-password.php?token=" . $token;
        $apiKey = 'MAILERSEND_API_KEY';
        $templateId = 'ynrw7gye2vk42k8e';
        $fromEmail = 'noreply@yourdomain.com';
        $fromName = 'Your Application';

        $data = [
            'from' => [
                'email' => $fromEmail,
                'name' => $fromName
            ],
            'to' => [
                [
                    'email' => $email,
                    'name' => $name
                ]
            ],
            'subject' => 'Password Reset Request',
            'template_id' => $templateId,
            'personalization' => [
                [
                    'email' => $email,
                    'data' => [
                        'name' => $name,
                        'action_url' => $resetLink,
                        'email' => $email,
                        '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);
        curl_close($ch);

        if ($curlError) {
            echo "MailerSend CURL Error: $curlError";
        } elseif ($httpCode >= 400) {
            echo "MailerSend HTTP Error $httpCode: $response";
        } else {
            echo 'Password reset link has been sent to your email.';
            header("refresh:5;url=../../login.php");
        }
    } else {
        throw new Exception("Failed to create a Reset Password Token in the database.");
    }
}
