<?php
// Database configuration
$host = 'dprintdgwdev.mysql.db';
$dbname = 'dprintdgwdev';
$username = 'dprintdgwdev';
$password = 'hv6ABD9zK4tKGaLP';

// Email configuration
$recipient_email = 'twoja@partyplanerka.pl';
$sender_domain = 'partyplanerka.pl';
$company_name = 'Intersnack Poland';
$system_email = 'assystentit@example.pl';

// SMTP Configuration
$smtp_host = '127.0.0.1'; // Change to your SMTP server host
$smtp_port = 25;

function getDatabaseConnection()
{
    global $host, $dbname, $username, $password;
    try {
        $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    } catch (PDOException $e) {
        http_response_code(500);
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Database connection failed: ' . $e->getMessage()]);
        exit;
    }
}

function sendEmailSMTP($from, $to, $subject, $message, $headers_str)
{
    global $smtp_host, $smtp_port;

    $socket = fsockopen($smtp_host, $smtp_port, $errno, $errstr, 10);
    if (!$socket) {
        return false;
    }

    $getResponse = function ($socket) {
        $response = "";
        while ($line = fgets($socket, 512)) {
            $response .= $line;
            if (substr($line, 3, 1) == " ")
                break;
        }
        return $response;
    };

    $sendCommand = function ($socket, $command) use ($getResponse) {
        fputs($socket, $command . "\r\n");
        return $getResponse($socket);
    };

    $getResponse($socket); // Initial greeting
    $sendCommand($socket, "HELO " . $_SERVER['SERVER_NAME']);
    $sendCommand($socket, "MAIL FROM: <$from>");
    $sendCommand($socket, "RCPT TO: <$to>");
    $sendCommand($socket, "DATA");

    // Construct the full email content including headers
    $data = "Subject: $subject\r\n";
    $data .= "To: <$to>\r\n";
    $data .= $headers_str . "\r\n";
    $data .= $message . "\r\n";
    $data .= ".";

    $res = $sendCommand($socket, $data);
    $sendCommand($socket, "QUIT");
    fclose($socket);

    return strpos($res, '250') !== false;
}
?>