<?php
require_once '../db.php';
session_start();

function getMailboxConnection() {
    $db2 = getDB2Connection();
    $stmt = $db2->prepare("SELECT * FROM mailboxforstaff WHERE user_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $config = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$config) {
        throw new Exception('Mail configuration not found');
    }

    $mailbox = "{" . $config['imap_host'] . ":" . $config['imap_port'] . "/imap/ssl}INBOX";
    $connection = imap_open($mailbox, $config['email'], $config['password']);
    
    if (!$connection) {
        throw new Exception('Cannot connect to mailbox: ' . imap_last_error());
    }
    
    return [
        'connection' => $connection,
        'config' => $config
    ];
}

function getSmtpConnection() {
    $db2 = getDB2Connection();
    $stmt = $db2->prepare("SELECT * FROM mailboxforstaff WHERE user_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $config = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$config) {
        throw new Exception('Mail configuration not found');
    }
    
    $mail = new PHPMailer(true);
    $mail->isSMTP();
    $mail->Host = $config['smtp_host'];
    $mail->SMTPAuth = true;
    $mail->Username = $config['email'];
    $mail->Password = $config['password'];
    $mail->SMTPSecure = $config['smtp_encryption'];
    $mail->Port = $config['smtp_port'];
    $mail->setFrom($config['email']);
    
    return $mail;
}