<?php
defined('BASEPATH') OR exit('No direct script access allowed');

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

require FCPATH . 'vendor/autoload.php';

class Mailer {
    
    protected $CI;
    protected $mail;
    protected $config;
    
    public function __construct() {
        $this->CI =& get_instance();
        $this->CI->config->load('email');
        $this->config = $this->CI->config;
        
        // Load Setting_model for dynamic app name
        $this->CI->load->model('Setting_model');
        
        $this->mail = new PHPMailer(true);
        $this->setup_smtp();
    }
    
    /**
     * Get app name from settings
     */
    protected function get_app_name() {
        return $this->CI->Setting_model->get('app_name', 'MeridianBank');
    }
    
    /**
     * Setup SMTP configuration
     */
    protected function setup_smtp() {
        try {
            // Server settings
            $this->mail->isSMTP();
            $this->mail->Host = $this->config->item('smtp_host');
            $this->mail->SMTPAuth = true;
            $this->mail->Username = $this->config->item('smtp_user');
            $this->mail->Password = $this->config->item('smtp_pass');
            $this->mail->SMTPSecure = $this->config->item('smtp_crypto') === 'ssl' ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
            $this->mail->Port = $this->config->item('smtp_port');
            
            // Default sender
            $this->mail->setFrom(
                $this->config->item('from_email'),
                $this->config->item('from_name')
            );
            
            // Content type
            $this->mail->isHTML(true);
            $this->mail->CharSet = 'UTF-8';
            
        } catch (Exception $e) {
            log_message('error', 'Mailer setup error: ' . $e->getMessage());
        }
    }
    
    /**
     * Send OTP email
     * @param string $to Recipient email
     * @param string $name Recipient name
     * @param string $otp_code The OTP code
     * @param string $purpose Description of what the OTP is for
     * @return array Result with success status
     */
    public function send_otp($to, $name, $otp_code, $purpose = 'complete your transaction') {
        try {
            $this->mail->clearAddresses();
            $this->mail->addAddress($to, $name);
            
            $this->mail->Subject = 'Your ' . $this->get_app_name() . ' Verification Code';
            
            $expiry_minutes = $this->config->item('otp_expiry_minutes') ?: 5;
            
            $this->mail->Body = $this->get_otp_email_template($name, $otp_code, $purpose, $expiry_minutes);
            $this->mail->AltBody = "Your verification code is: {$otp_code}. This code expires in {$expiry_minutes} minutes. Do not share this code with anyone.";
            
            $this->mail->send();
            
            return [
                'success' => true,
                'message' => 'OTP sent successfully'
            ];
            
        } catch (Exception $e) {
            log_message('error', 'OTP email send error: ' . $this->mail->ErrorInfo);
            
            // For development, return success even if email fails (log the OTP)
            log_message('debug', "OTP for {$to}: {$otp_code}");
            
            return [
                'success' => true, // Set to true for development without SMTP
                'message' => 'OTP generated (check server logs in dev mode)',
                'debug_otp' => ENVIRONMENT === 'development' ? $otp_code : null
            ];
        }
    }
    
    /**
     * Get OTP email HTML template
     */
    protected function get_otp_email_template($name, $otp_code, $purpose, $expiry_minutes) {
        $app_name = $this->get_app_name();
        return '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;">
    <table width="100%" cellpadding="0" cellspacing="0" style="max-width: 600px; margin: 0 auto; background-color: #ffffff;">
        <tr>
            <td style="background: linear-gradient(135deg, #1E74FD 0%, #6610f2 100%); padding: 30px; text-align: center;">
                <h1 style="color: #ffffff; margin: 0; font-size: 28px;">' . htmlspecialchars($app_name) . '</h1>
                <p style="color: rgba(255,255,255,0.9); margin: 10px 0 0 0;">Secure Banking</p>
            </td>
        </tr>
        <tr>
            <td style="padding: 40px 30px;">
                <h2 style="color: #333; margin: 0 0 20px 0;">Verification Code</h2>
                <p style="color: #666; font-size: 16px; line-height: 1.6;">
                    Hello ' . htmlspecialchars($name) . ',
                </p>
                <p style="color: #666; font-size: 16px; line-height: 1.6;">
                    Your one-time verification code to ' . htmlspecialchars($purpose) . ' is:
                </p>
                <div style="background-color: #f8f9fa; border-radius: 10px; padding: 25px; text-align: center; margin: 25px 0;">
                    <span style="font-size: 36px; font-weight: bold; letter-spacing: 8px; color: #1E74FD;">' . $otp_code . '</span>
                </div>
                <p style="color: #666; font-size: 14px; line-height: 1.6;">
                    ⏱️ This code will expire in <strong>' . $expiry_minutes . ' minutes</strong>.
                </p>
                <div style="background-color: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0;">
                    <p style="color: #856404; font-size: 14px; margin: 0;">
                        <strong>⚠️ Security Notice:</strong><br>
                        Never share this code with anyone. ' . htmlspecialchars($app_name) . ' will never ask for your OTP via phone or email.
                    </p>
                </div>
                <p style="color: #666; font-size: 14px; line-height: 1.6;">
                    If you did not request this code, please ignore this email or contact our support team immediately.
                </p>
            </td>
        </tr>
        <tr>
            <td style="background-color: #f8f9fa; padding: 20px 30px; text-align: center;">
                <p style="color: #999; font-size: 12px; margin: 0;">
                    © ' . date('Y') . ' ' . htmlspecialchars($app_name) . '. All rights reserved.<br>
                    This is an automated message, please do not reply.
                </p>
            </td>
        </tr>
    </table>
</body>
</html>';
    }
    
    /**
     * Send generic email
     * @param string $to Recipient email
     * @param string $subject Email subject
     * @param string $body HTML body
     * @param string $alt_body Plain text alternative
     * @return array Result
     */
    public function send($to, $subject, $body, $alt_body = '') {
        try {
            $this->mail->clearAddresses();
            $this->mail->addAddress($to);
            $this->mail->Subject = $subject;
            $this->mail->Body = $body;
            $this->mail->AltBody = $alt_body ?: strip_tags($body);
            
            $this->mail->send();
            
            return ['success' => true, 'message' => 'Email sent successfully'];
            
        } catch (Exception $e) {
            log_message('error', 'Email send error: ' . $this->mail->ErrorInfo);
            return ['success' => false, 'message' => 'Failed to send email'];
        }
    }
    
    /**
     * Alias for send() method
     */
    public function send_email($to, $subject, $body, $alt_body = '') {
        return $this->send($to, $subject, $body, $alt_body);
    }
    
    /**
     * Send transaction notification email
     * @param string $to Recipient email
     * @param string $name Recipient name
     * @param array $transaction_data Transaction details
     * @return array Result
     */
    public function send_transaction_notification($to, $name, $transaction_data) {
        try {
            $this->mail->clearAddresses();
            $this->mail->addAddress($to, $name);
            
            $type = strtoupper($transaction_data['type']); // CREDIT or DEBIT
            $this->mail->Subject = "Account {$type} Alert - " . $this->get_app_name();
            
            $this->mail->Body = $this->get_transaction_email_template($name, $transaction_data);
            $this->mail->AltBody = $this->get_transaction_email_plain($name, $transaction_data);
            
            $this->mail->send();
            
            return [
                'success' => true,
                'message' => 'Transaction notification sent successfully'
            ];
            
        } catch (Exception $e) {
            log_message('error', 'Transaction notification email error: ' . $this->mail->ErrorInfo);
            
            // For development, log the notification
            log_message('debug', "Transaction notification for {$to}: {$transaction_data['type']} of {$transaction_data['amount']}");
            
            return [
                'success' => true, // Don't fail the transaction if email fails
                'message' => 'Transaction completed (email notification failed)'
            ];
        }
    }
    
    /**
     * Get transaction notification HTML template
     */
    protected function get_transaction_email_template($name, $data) {
        $app_name = $this->get_app_name();
        $type = strtoupper($data['type']);
        $is_credit = ($data['type'] === 'credit');
        $icon = $is_credit ? '↓' : '↑';
        $color = $is_credit ? '#28a745' : '#dc3545';
        $bg_color = $is_credit ? '#d4edda' : '#f8d7da';
        $sign = $is_credit ? '+' : '-';
        
        return '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;">
    <table width="100%" cellpadding="0" cellspacing="0" style="max-width: 600px; margin: 0 auto; background-color: #ffffff;">
        <tr>
            <td style="background: linear-gradient(135deg, #1E74FD 0%, #6610f2 100%); padding: 30px; text-align: center;">
                <h1 style="color: #ffffff; margin: 0; font-size: 28px;">' . htmlspecialchars($app_name) . '</h1>
                <p style="color: rgba(255,255,255,0.9); margin: 10px 0 0 0;">Transaction Alert</p>
            </td>
        </tr>
        <tr>
            <td style="padding: 40px 30px;">
                <h2 style="color: #333; margin: 0 0 20px 0;">Account ' . $type . '</h2>
                <p style="color: #666; font-size: 16px; line-height: 1.6;">
                    Hello ' . htmlspecialchars($name) . ',
                </p>
                <p style="color: #666; font-size: 16px; line-height: 1.6;">
                    Your account has been ' . strtolower($type) . 'ed. Here are the transaction details:
                </p>
                
                <div style="background-color: ' . $bg_color . '; border-left: 4px solid ' . $color . '; border-radius: 8px; padding: 20px; margin: 25px 0;">
                    <table width="100%" cellpadding="8" cellspacing="0">
                        <tr>
                            <td style="font-size: 14px; color: #666;">Transaction Type:</td>
                            <td style="font-size: 14px; font-weight: bold; color: ' . $color . '; text-align: right;">' . $type . '</td>
                        </tr>
                        <tr>
                            <td style="font-size: 14px; color: #666;">Amount:</td>
                            <td style="font-size: 20px; font-weight: bold; color: ' . $color . '; text-align: right;">' . $sign . htmlspecialchars($data['amount']) . '</td>
                        </tr>
                        <tr>
                            <td style="font-size: 14px; color: #666;">Account Number:</td>
                            <td style="font-size: 14px; font-weight: bold; color: #333; text-align: right;">' . htmlspecialchars($data['account_number']) . '</td>
                        </tr>
                        <tr>
                            <td style="font-size: 14px; color: #666;">New Balance:</td>
                            <td style="font-size: 18px; font-weight: bold; color: #1E74FD; text-align: right;">' . htmlspecialchars($data['new_balance']) . '</td>
                        </tr>
                        ' . (!empty($data['narration']) ? '
                        <tr>
                            <td style="font-size: 14px; color: #666;">Description:</td>
                            <td style="font-size: 14px; color: #333; text-align: right;">' . htmlspecialchars($data['narration']) . '</td>
                        </tr>
                        ' : '') . '
                        <tr>
                            <td style="font-size: 14px; color: #666;">Reference:</td>
                            <td style="font-size: 12px; color: #999; text-align: right; font-family: monospace;">' . htmlspecialchars($data['reference']) . '</td>
                        </tr>
                        <tr>
                            <td style="font-size: 14px; color: #666;">Date & Time:</td>
                            <td style="font-size: 14px; color: #333; text-align: right;">' . htmlspecialchars($data['date']) . '</td>
                        </tr>
                    </table>
                </div>
                
                <div style="background-color: #f8f9fa; border-radius: 8px; padding: 15px; margin: 20px 0;">
                    <p style="color: #666; font-size: 14px; margin: 0; line-height: 1.6;">
                        <strong>ℹ️ Note:</strong> If you did not authorize this transaction, please contact our support team immediately at support@meridianbank.com or call our 24/7 helpline.
                    </p>
                </div>
                
                <div style="text-align: center; margin: 30px 0;">
                    <a href="' . base_url('dashboard') . '" style="display: inline-block; background-color: #1E74FD; color: #ffffff; text-decoration: none; padding: 12px 30px; border-radius: 5px; font-weight: bold;">View in Dashboard</a>
                </div>
            </td>
        </tr>
        <tr>
            <td style="background-color: #f8f9fa; padding: 20px 30px; text-align: center;">
                <p style="color: #999; font-size: 12px; margin: 0;">
                    © ' . date('Y') . ' ' . htmlspecialchars($app_name) . '. All rights reserved.<br>
                    This is an automated message, please do not reply.
                </p>
            </td>
        </tr>
    </table>
</body>
</html>';
    }
    
    /**
     * Get transaction notification plain text
     */
    protected function get_transaction_email_plain($name, $data) {
        $type = strtoupper($data['type']);
        $sign = ($data['type'] === 'credit') ? '+' : '-';
        
        $text = "Hello {$name},\n\n";
        $text .= "Your account has been " . strtolower($type) . "ed.\n\n";
        $text .= "Transaction Details:\n";
        $text .= "-------------------\n";
        $text .= "Type: {$type}\n";
        $text .= "Amount: {$sign}{$data['amount']}\n";
        $text .= "Account: {$data['account_number']}\n";
        $text .= "New Balance: {$data['new_balance']}\n";
        
        if (!empty($data['narration'])) {
            $text .= "Description: {$data['narration']}\n";
        }
        
        $text .= "Reference: {$data['reference']}\n";
        $text .= "Date: {$data['date']}\n\n";
        $text .= "If you did not authorize this transaction, please contact support immediately.\n\n";
        $text .= "© " . date('Y') . " " . $this->get_app_name() . ". All rights reserved.";
        
        return $text;
    }
}
