<?php
//Developer: core tech web desighn
//Whatsapp: +234 9162671360
//Telegram: @ jeditech

if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.cookie_httponly', 1);
    ini_set('session.cookie_samesite', 'Strict');
    ini_set('session.use_strict_mode', 1);
    session_start();
}

if (defined('VALID_ACCESS')) {
    return; // Already included, stop here
}

define('VALID_ACCESS', true);

// Check if user is logged in (customize with your auth logic)
if (!function_exists('is_authenticated')) {
    function is_authenticated() {
        return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
    }
}

// Redirect if not logged in
if (!function_exists('require_auth')) {
    function require_auth() {
        if (!is_authenticated()) {
            header('Location: ../index.php');
            exit();
        }
    }
}

$host = "localhost";  // or your server IP
$dbname = "u680871603_emepro";
$username = "root";   // your DB username
$password = "";   // your DB password

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// Create mysqli connection for site settings
$conn = new mysqli($host, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$conn->set_charset("utf8mb4");

// Fetch site settings
$site_sql = $conn->query("SELECT * FROM settings WHERE id='1'");
$site_data = $site_sql ? $site_sql->fetch_assoc() : null;

if (!$site_data) {
    die("Site settings not found. Please ensure the 'settings' table exists and has a row with id=1. Run the SQL import from the SQL/ folder.");
}

// Get protocol and website URL
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') || (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] === '443') ? 'https' : 'http';

// Auto-detect base URL based on the application root folder
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$base_path = '';

if (!empty($_SERVER['DOCUMENT_ROOT'])) {
    $documentRoot = realpath($_SERVER['DOCUMENT_ROOT']);
    $configDir = realpath(__DIR__);

    if ($documentRoot && $configDir && str_starts_with($configDir, $documentRoot)) {
        $base_path = str_replace('\\', '/', substr($configDir, strlen($documentRoot)));
        $base_path = preg_replace('#/include$#', '', $base_path);
    }
}

if ($base_path === '') {
    $base_path = dirname($_SERVER['SCRIPT_NAME'] ?? '');
}

$base_path = str_replace('\\', '/', $base_path);
$base_path = rtrim($base_path, '/');
$base_path = implode('/', array_map('rawurlencode', array_filter(explode('/', ltrim($base_path, '/')), 'strlen')));
if ($base_path !== '') {
    $base_path = '/' . $base_path;
}

$website_url = $protocol . '://' . $host . $base_path;

// Override the database web_url with the correct one
$site_data['web_url'] = $website_url;

// Define commonly used site constants
define("WEBSITE_URL", $website_url);
define("WEB_NAME", $site_data['web_name']);
define("WEB_EMAIL", $site_data['web_email']);
define("LOGO_URL", $site_data['logo_url']);
define("REFER_PERCENT", $site_data['refer_percent']);
define("MIN_REDEEM", $site_data['min_redeem']);

// Social Media Links
define("WEB_TELEGRAM", $site_data['web_telegram']);
define("SUPPORT_URL", $site_data['support_url']);
define("CHANNEL_URL", $site_data['channel_url']);
define("WEB_FACEBOOK", $site_data['web_facebook']);
define("WEB_X", $site_data['web_x']);
define("WEB_INSTAGRAM", $site_data['web_instagram']);
define("WEB_TIKTOK", $site_data['web_tiktok']);

// Payment Gateway Keys (Paystack)
define("PAYSTACK_PUBLIC_KEY", $site_data['paystack_public_key']);
define("PAYSTACK_SECRET_KEY", $site_data['paystack_secret_key']);

// Keep legacy variable for backward compatibility
$web_name = $site_data['web_name'];

if (!function_exists('get_mail_settings')) {
    function get_mail_settings($pdo = null, $site_data = null) {
        $settings = [];

        if (!$pdo instanceof PDO) {
            $pdo = $GLOBALS['pdo'] ?? null;
        }

        if ($pdo instanceof PDO) {
            try {
                $pdo->exec("ALTER TABLE settings ADD COLUMN IF NOT EXISTS smtp_host VARCHAR(255) NOT NULL DEFAULT ''");
                $pdo->exec("ALTER TABLE settings ADD COLUMN IF NOT EXISTS smtp_port INT NOT NULL DEFAULT 587");
                $pdo->exec("ALTER TABLE settings ADD COLUMN IF NOT EXISTS smtp_username VARCHAR(255) NOT NULL DEFAULT ''");
                $pdo->exec("ALTER TABLE settings ADD COLUMN IF NOT EXISTS smtp_password VARCHAR(255) NOT NULL DEFAULT ''");
                $pdo->exec("ALTER TABLE settings ADD COLUMN IF NOT EXISTS smtp_encryption VARCHAR(20) NOT NULL DEFAULT 'tls'");
                $pdo->exec("ALTER TABLE settings ADD COLUMN IF NOT EXISTS smtp_from_email VARCHAR(255) NOT NULL DEFAULT ''");
                $pdo->exec("ALTER TABLE settings ADD COLUMN IF NOT EXISTS smtp_from_name VARCHAR(255) NOT NULL DEFAULT ''");
                $pdo->exec("ALTER TABLE settings ADD COLUMN IF NOT EXISTS flutterwave_enabled TINYINT(1) NOT NULL DEFAULT 0");
                $pdo->exec("ALTER TABLE settings ADD COLUMN IF NOT EXISTS flutterwave_public_key VARCHAR(255) NOT NULL DEFAULT ''");
                $pdo->exec("ALTER TABLE settings ADD COLUMN IF NOT EXISTS flutterwave_secret_key VARCHAR(255) NOT NULL DEFAULT ''");
                $pdo->exec("ALTER TABLE settings ADD COLUMN IF NOT EXISTS flutterwave_minimum DECIMAL(10,2) NOT NULL DEFAULT 100.00");
                $pdo->exec("ALTER TABLE settings ADD COLUMN IF NOT EXISTS flutterwave_default_currency VARCHAR(10) NOT NULL DEFAULT 'NGN'");

                $stmt = $pdo->prepare("SELECT smtp_host, smtp_port, smtp_username, smtp_password, smtp_encryption, smtp_from_email, smtp_from_name, web_name, web_email FROM settings WHERE id = 1 LIMIT 1");
                $stmt->execute();
                $row = $stmt->fetch(PDO::FETCH_ASSOC);
                if ($row) {
                    $settings = $row;
                }
            } catch (PDOException $e) {
                // Ignore schema issues and continue with fallback values.
            }
        }

        if (is_array($site_data) && !empty($site_data)) {
            // Merge site_data as base, then overlay DB smtp values on top
            $smtp_keys = ['smtp_host','smtp_port','smtp_username','smtp_password','smtp_encryption','smtp_from_email','smtp_from_name'];
            $smtp_from_db = array_intersect_key($settings, array_flip($smtp_keys));
            $settings = array_merge($site_data, $settings);
            // Ensure DB smtp values are not overwritten by site_data
            foreach ($smtp_keys as $k) {
                if (!empty($smtp_from_db[$k])) {
                    $settings[$k] = $smtp_from_db[$k];
                }
            }
        }

        $settings['smtp_host'] = trim($settings['smtp_host'] ?? '');
        $settings['smtp_port'] = intval($settings['smtp_port'] ?? 587);
        $settings['smtp_username'] = trim($settings['smtp_username'] ?? '');
        $settings['smtp_password'] = trim($settings['smtp_password'] ?? '');
        $settings['smtp_encryption'] = trim($settings['smtp_encryption'] ?? 'tls');
        $settings['smtp_from_email'] = trim($settings['smtp_from_email'] ?? '');
        $settings['smtp_from_name'] = trim($settings['smtp_from_name'] ?? '');

        return $settings;
    }
}

if (!function_exists('get_phpmailer_source_path')) {
    function get_phpmailer_source_path() {
        $base = dirname(__DIR__);
        $paths = [
            $base . '/PHPMailer/src/',
            $base . '/PHPMailer1/src/',
            $base . '/vendor/phpmailer/phpmailer/src/',
            $base . '/mailer/src/',
        ];

        foreach ($paths as $path) {
            if (file_exists($path . 'PHPMailer.php') && file_exists($path . 'SMTP.php') && file_exists($path . 'Exception.php')) {
                return $path;
            }
        }

        return null;
    }
}

if (!function_exists('send_system_email')) {
    function send_system_email($to, $subject, $message, $pdo = null, $site_data = null, $options = []) {
        $mail_settings = get_mail_settings($pdo, $site_data);

        $smtp_host = trim($mail_settings['smtp_host'] ?? '');
        $smtp_port = intval($mail_settings['smtp_port'] ?? 587);
        $smtp_username = trim($mail_settings['smtp_username'] ?? '');
        $smtp_password = trim($mail_settings['smtp_password'] ?? '');
        $smtp_encryption = trim($mail_settings['smtp_encryption'] ?? 'tls');

        $reply_to_email = trim($options['reply_to'] ?? $options['from_email'] ?? $mail_settings['smtp_from_email'] ?? $mail_settings['web_email'] ?? (defined('WEB_EMAIL') && filter_var(WEB_EMAIL, FILTER_VALIDATE_EMAIL) ? WEB_EMAIL : '') ?? '');
        $from_name = trim($options['from_name'] ?? $mail_settings['smtp_from_name'] ?? $mail_settings['web_name'] ?? (defined('WEB_NAME') ? WEB_NAME : '') ?? 'Website');
        $from_email = trim($mail_settings['smtp_from_email'] ?? $smtp_username ?? $mail_settings['web_email'] ?? (defined('WEB_EMAIL') && filter_var(WEB_EMAIL, FILTER_VALIDATE_EMAIL) ? WEB_EMAIL : '') ?? '');

        if (!empty($options['from_email']) && filter_var($options['from_email'], FILTER_VALIDATE_EMAIL)) {
            $reply_to_email = trim($options['from_email']);
        }

        $from_email = (!empty($from_email) && filter_var($from_email, FILTER_VALIDATE_EMAIL)) ? $from_email : ((defined('WEB_EMAIL') && filter_var(WEB_EMAIL, FILTER_VALIDATE_EMAIL)) ? WEB_EMAIL : ($smtp_username ?: 'noreply@localhost'));
        $from_name = $from_name ?: 'Website';

        if (!empty($smtp_host) && !empty($smtp_username) && !empty($smtp_password)) {
            $phpmailer_path = get_phpmailer_source_path();
            if ($phpmailer_path !== null) {
                if (!defined('FILTER_FLAG_HOST_REQUIRED')) {
                    define('FILTER_FLAG_HOST_REQUIRED', 8);
                }
                require_once $phpmailer_path . 'Exception.php';
                require_once $phpmailer_path . 'PHPMailer.php';
                require_once $phpmailer_path . 'SMTP.php';

                $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
                try {
                    $mail->isSMTP();
                    $mail->Host = $smtp_host;
                    $mail->Port = $smtp_port ?: 587;
                    $mail->SMTPAuth = true;
                    $mail->Username = $smtp_username;
                    $mail->Password = $smtp_password;
                    if ($smtp_encryption === 'ssl') {
                        $mail->SMTPSecure = 'ssl';
                    } elseif ($smtp_encryption === 'tls') {
                        $mail->SMTPSecure = 'tls';
                    }
                    $mail->SMTPAutoTLS = true;
                    $mail->SMTPDebug = 0;
                    $mail->SMTPOptions = [
                        'ssl' => [
                            'verify_peer' => false,
                            'verify_peer_name' => false,
                            'allow_self_signed' => true,
                        ],
                    ];
                    $mail->setFrom($from_email, $from_name);
                    if (!empty($reply_to_email) && filter_var($reply_to_email, FILTER_VALIDATE_EMAIL)) {
                        $mail->addReplyTo($reply_to_email, $from_name);
                    }
                    $mail->addAddress($to);
                    $mail->isHTML(true);
                    $mail->CharSet = 'UTF-8';
                    $mail->Subject = $subject;
                    $mail->Body = $message;
                    $mail->AltBody = strip_tags($message);
                    $mail->send();
                    return true;
                } catch (\PHPMailer\PHPMailer\Exception $e) {
                    error_log('[Mail] SMTP send failed: ' . $e->getMessage());
                }
            } else {
                error_log('[Mail] PHPMailer not found in any expected path.');
            }
        }

        $headers = "From: {$from_name} <{$from_email}>\r\nReply-To: {$from_email}\r\nMIME-Version: 1.0\r\nContent-Type: text/html; charset=UTF-8\r\n";
        return @mail($to, $subject, $message, $headers);
    }
}

?>