<?php

namespace App\Controllers;

use Core\Request;
use Core\Redirect;
use Core\DB;


include realpath(dirname(__DIR__) . '/include/function.php');

class SmtpSettings
{

    public function saveSmtpSettings()
    {
        if (!isset($_POST['save_smtp_settings'])) {
            return;
        }
        // Get database connection
        $db = new DB();
        $conn = $db->getConnection();

        $smtp_settings = [
            'smtp_host' => Request::getPost('smtp_host', 'string'),
            'smtp_port' => Request::getPost('smtp_port', 'int'),
            'smtp_user' => Request::getPost('smtp_user', 'string'),
            'smtp_pass' => Request::getPost('smtp_pass', 'string'),
        ];

        $stmt =  $conn->prepare("INSERT INTO settings (setting_name, setting_value) VALUES (?, ?) 
                                        ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
        if (!$stmt) {
            Redirect::redirectError('email_smtp_settings', "Failed to prepare statement: " .  $conn->error);
        }

        foreach ($smtp_settings as $setting_name => $setting_value) {
            $stmt->bind_param("ss", $setting_name, $setting_value);
            if (!$stmt->execute()) {
                Redirect::redirectError('email_smtp_settings', "Failed to execute statement: " . $stmt->error);
            }
        }

        $stmt->close();
        $conn->close();

        $message = "SMTP settings have been updated successfully.";
        Redirect::redirectSuccess('email_smtp_settings', $message);
    }

    public function testSmtpSettings()
    {
        if (!isset($_POST['test_smtp_settings'])) {
            return;
        }

        // Get database connection
        $db = new DB();
        $conn = $db->getConnection();

        $test_email = filter_var($_POST['test_email'], FILTER_SANITIZE_EMAIL);
        if (!filter_var($test_email, FILTER_VALIDATE_EMAIL)) {
             Redirect::redirectError('email_smtp_settings', "Invalid email address.");
        }
        $response = sendEmail($conn, $test_email, 'Test Email', 'This is a test email.');
        if ($response) {
            $message = "Test email sent successfully to $test_email.";
            Redirect::redirectSuccess('email_smtp_settings', $message);
        } else {
            Redirect::redirectError('email_smtp_settings', "Failed to send test email.");
        }
    }


   
}
