<?php
// admin/includes/EmailService.php

// ============================================================
// 0. NAMESPACE USE STATEMENTS (MUST BE AT TOP)
// ============================================================
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// ============================================================
// 1. TRY TO LOAD COMPOSER AUTOLOADER (from project root)
// ============================================================
$composer_autoload = __DIR__ . '/../../vendor/autoload.php';
if (file_exists($composer_autoload)) {
    require_once $composer_autoload;
}

// ============================================================
// 2. MANUAL FALLBACK (if you manually placed PHPMailer)
// ============================================================
$phpmailer_dir = __DIR__ . '/PHPMailer/';
if (!class_exists('PHPMailer\PHPMailer\PHPMailer') && file_exists($phpmailer_dir . 'PHPMailer.php')) {
    require_once $phpmailer_dir . 'PHPMailer.php';
    require_once $phpmailer_dir . 'SMTP.php';
    require_once $phpmailer_dir . 'Exception.php';
}

class EmailService {
    private $settings;
    private $templates;
    private $pdo;
    private $use_phpmailer = false;

    public function __construct($pdo) {
        $this->pdo = $pdo;
        $this->loadSettings();
        $this->loadTemplates();
        
        // Check if PHPMailer is available
        $this->use_phpmailer = class_exists('PHPMailer\PHPMailer\PHPMailer') || class_exists('PHPMailer');
    }

    private function loadSettings() {
        $settings_file = __DIR__ . '/../../config/email-settings.json';
        if (file_exists($settings_file)) {
            $this->settings = json_decode(file_get_contents($settings_file), true);
        } else {
            $this->settings = [
                'smtp_host'      => 'mail.tipspac.com',
                'smtp_port'      => '465',
                'smtp_user'      => 'no-reply@tipspac.com',
                'smtp_pass'      => '',
                'sender_name'    => 'tipspac Pro AI',
                'email_enabled'  => '0'
            ];
        }
    }

    private function loadTemplates() {
        $templates_file = __DIR__ . '/../../config/email-templates.json';
        if (file_exists($templates_file)) {
            $this->templates = json_decode(file_get_contents($templates_file), true);
        } else {
            $this->templates = [
                'welcome' => [
                    'subject' => 'Welcome to tipspac!',
                    'body' => "Hello {user_name},\n\nWelcome to tipspac!\n\nBest,\nThe tipspac Team"
                ]
            ];
        }
    }

    /**
     * Send an email using a template, with optional custom subject and custom body.
     *
     * @param string      $template_key   The template key (e.g., 'welcome', 'system_notification').
     * @param string      $to_email       Recipient email address.
     * @param array       $placeholders   Associative array of placeholder values.
     * @param string|null $custom_subject Override the template subject.
     * @param string|null $custom_body    Override the template body.
     * @return bool
     */
    public function sendTemplateEmail($template_key, $to_email, $placeholders = [], $custom_subject = null, $custom_body = null) {
        if (empty($this->settings['email_enabled']) || $this->settings['email_enabled'] != '1') {
            error_log("Email disabled: skipping " . $template_key . " to " . $to_email);
            return false;
        }

        if (!isset($this->templates[$template_key])) {
            error_log("Email template not found: " . $template_key);
            return false;
        }

        $template = $this->templates[$template_key];
        $subject = $custom_subject ?? $template['subject'];
        $body = $custom_body ?? $template['body'];

        // Replace placeholders
        foreach ($placeholders as $key => $value) {
            $subject = str_replace('{' . $key . '}', $value, $subject);
            $body = str_replace('{' . $key . '}', $value, $body);
        }

        // Standard placeholders
        if (defined('SITE_URL')) {
            $body = str_replace('{site_url}', SITE_URL, $body);
            $subject = str_replace('{site_url}', SITE_URL, $subject);
        }

        // Send using available method
        if ($this->use_phpmailer) {
            return $this->sendWithPHPMailer($to_email, $subject, $body);
        } else {
            return $this->sendWithNativeMail($to_email, $subject, $body);
        }
    }

    private function sendWithPHPMailer($to, $subject, $body) {
        try {
            if (class_exists('PHPMailer\PHPMailer\PHPMailer')) {
                $mail = new PHPMailer\PHPMailer\PHPMailer(true);
            } else {
                $mail = new PHPMailer(true);
            }
            
            $mail->isSMTP();
            $mail->Host       = $this->settings['smtp_host'];
            $mail->SMTPAuth   = true;
            $mail->Username   = $this->settings['smtp_user'];
            $mail->Password   = $this->settings['smtp_pass'];
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port       = $this->settings['smtp_port'];
            $mail->setFrom($this->settings['smtp_user'], $this->settings['sender_name']);
            $mail->addAddress($to);
            $mail->Subject = $subject;
            $mail->Body    = $body;
            $mail->isHTML(false);

            $mail->send();
            $this->logEmail($to, $subject, 'sent');
            return true;
        } catch (Exception $e) {
            error_log("PHPMailer Error: " . $e->getMessage());
            $this->logEmail($to, $subject, 'failed');
            return false;
        }
    }

    private function sendWithNativeMail($to, $subject, $body) {
        $headers = "From: " . $this->settings['sender_name'] . " <" . $this->settings['smtp_user'] . ">\r\n";
        $headers .= "Reply-To: " . $this->settings['smtp_user'] . "\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
        
        $result = mail($to, $subject, $body, $headers);
        $this->logEmail($to, $subject, $result ? 'sent' : 'failed');
        return $result;
    }

    private function logEmail($to, $subject, $status) {
        if (!$this->pdo) return;
        try {
            $stmt = $this->pdo->prepare("SHOW TABLES LIKE 'email_logs'");
            $stmt->execute();
            if ($stmt->rowCount() > 0) {
                $stmt = $this->pdo->prepare("INSERT INTO email_logs (to_email, subject, status) VALUES (?, ?, ?)");
                $stmt->execute([$to, $subject, $status]);
            }
        } catch (PDOException $e) {
            error_log("Email log failed: " . $e->getMessage());
        }
    }
}