<?php
// admin/email_functions.php

// ============================================================
// INCLUDE KONFIGURASI EMAIL
// ============================================================
require_once 'email_config.php';

// ============================================================
// INCLUDE PHPMailer
// ============================================================
require_once $_SERVER['DOCUMENT_ROOT'] . '/phpmailer/src/Exception.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/phpmailer/src/PHPMailer.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/phpmailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// ============================================================
// FUNGSI SEND EMAIL
// ============================================================
function sendEmail($to, $subject, $message) {
    $mail = new PHPMailer(true);
    
    try {
        $mail->isSMTP();
        $mail->Host       = SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USERNAME;
        $mail->Password   = SMTP_PASSWORD;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port       = SMTP_PORT;
        $mail->AuthType   = 'LOGIN';
        
        $mail->setFrom(SMTP_FROM_EMAIL, SMTP_FROM_NAME);
        $mail->addAddress($to);
        $mail->isHTML(false);
        $mail->Subject = $subject;
        $mail->Body    = $message;
        
        $mail->send();
        return ['success' => true, 'message' => 'Email berhasil dikirim'];
        
    } catch (Exception $e) {
        return ['success' => false, 'error' => $mail->ErrorInfo];
    }
}

// ============================================================
// FUNGSI SEND REPLY (untuk membalas email)
// ============================================================
function sendReply($to, $subject, $message, $reply_to_id = null) {
    $mail = new PHPMailer(true);
    
    try {
        $mail->isSMTP();
        $mail->Host       = SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USERNAME;
        $mail->Password   = SMTP_PASSWORD;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port       = SMTP_PORT;
        $mail->AuthType   = 'LOGIN';
        
        $mail->setFrom(SMTP_FROM_EMAIL, SMTP_FROM_NAME);
        $mail->addAddress($to);
        $mail->isHTML(false);
        $mail->Subject = $subject;
        $mail->Body    = $message;
        
        $mail->send();
        
        if ($reply_to_id) {
            $db = $GLOBALS['db'];
            $stmt = $db->prepare("UPDATE email_messages SET status = 'replied' WHERE id = ?");
            $stmt->execute([$reply_to_id]);
        }
        
        return ['success' => true, 'message' => 'Email berhasil dikirim'];
        
    } catch (Exception $e) {
        return ['success' => false, 'error' => $mail->ErrorInfo];
    }
}
?>