<?php
/**
 * Email Functions
 * Email functions for the ticketing system using SMTP
 */

require_once 'email_config.php';

// Function to send email using SMTP
function sendEmail($to, $subject, $message, $from = NO_REPLY_EMAIL) {
    // Log email attempt
    error_log("Email attempt to: $to, Subject: $subject, From: $from");
    
    // Try to use PHPMailer if available
    if (file_exists(dirname(__FILE__) . '/PHPMailer/src/PHPMailer.php')) {
        return sendEmailViaPHPMailer($to, $subject, $message, $from);
    } else {
        // Fallback to improved mail() function
        $headers = buildEmailHeaders($from);
        
        // Add additional headers for better deliverability
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
        $headers .= "X-Priority: 3\r\n";
        
        // Use error suppression but log errors
        $result = @mail($to, $subject, $message, $headers);
        
        // Log result
        error_log("Email result to: $to, Subject: $subject, Result: " . ($result ? 'Success' : 'Failed'));
        
        return $result;
    }
}

// Function to send email via PHPMailer
function sendEmailViaPHPMailer($to, $subject, $message, $from = NO_REPLY_EMAIL) {
    try {
        // Include PHPMailer classes
        require_once dirname(__FILE__) . '/PHPMailer/src/PHPMailer.php';
        require_once dirname(__FILE__) . '/PHPMailer/src/SMTP.php';
        require_once dirname(__FILE__) . '/PHPMailer/src/Exception.php';
        
        $mail = new PHPMailer\PHPMailer\PHPMailer();
        
        // SMTP configuration
        $mail->isSMTP();
        $mail->Host       = SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USERNAME;
        $mail->Password   = SMTP_PASSWORD;
        $mail->SMTPSecure = SMTP_ENCRYPTION;
        $mail->Port       = SMTP_PORT;
        
        // Recipients
        $mail->setFrom($from, SITE_NAME);
        $mail->addAddress($to);
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $message;
        $mail->CharSet = 'UTF-8';
        
        $result = $mail->send();
        error_log("PHPMailer email result to: $to, Subject: $subject, Result: " . ($result ? 'Success' : 'Failed'));
        
        return $result;
    } catch (Exception $e) {
        error_log("PHPMailer email error: " . $e->getMessage());
        return false;
    }
}

// Function to build email headers
function buildEmailHeaders($from) {
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8" . "\r\n";
    $headers .= "From: " . $from . "\r\n";
    $headers .= "Reply-To: " . $from . "\r\n";
    $headers .= "X-Mailer: StoreWeb E-commerce" . "\r\n";
    $headers .= "X-Priority: 3" . "\r\n";
    $headers .= "Return-Path: " . $from . "\r\n";
    return $headers;
}

// Function to notify customer when ticket is created
function notifyTicketCreated($pdo, $ticket_id) {
    // Get ticket details
    $stmt = $pdo->prepare("
        SELECT t.*, tt.name as type_name, u.username as customer_name, u.email as customer_email
        FROM tickets t
        LEFT JOIN ticket_types tt ON t.type_id = tt.id
        LEFT JOIN users u ON t.user_id = u.id
        WHERE t.id = ?
    ");
    $stmt->execute([$ticket_id]);
    $ticket = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$ticket) {
        return false;
    }
    
    // Prepare email
    $subject = "Support Ticket #" . $ticket_id . " Created";
    $message = getTicketCreatedEmailTemplate($ticket_id, $ticket['subject'], $ticket['customer_name']);
    
    // Send email
    return sendEmail($ticket['customer_email'], $subject, $message);
}

// Function to notify customer when ticket status is updated
function notifyTicketStatusUpdated($pdo, $ticket_id, $old_status, $new_status) {
    // Only notify if status actually changed
    if ($old_status === $new_status) {
        return true;
    }
    
    // Get ticket details
    $stmt = $pdo->prepare("
        SELECT t.*, tt.name as type_name, u.username as customer_name, u.email as customer_email
        FROM tickets t
        LEFT JOIN ticket_types tt ON t.type_id = tt.id
        LEFT JOIN users u ON t.user_id = u.id
        WHERE t.id = ?
    ");
    $stmt->execute([$ticket_id]);
    $ticket = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$ticket) {
        return false;
    }
    
    // Prepare email
    $subject = "Support Ticket #" . $ticket_id . " Status Updated";
    $message = getTicketStatusUpdatedEmailTemplate($ticket_id, $ticket['subject'], $new_status, $ticket['customer_name']);
    
    // Send email
    return sendEmail($ticket['customer_email'], $subject, $message);
}

// Function to notify customer when there's a new reply
function notifyNewReply($pdo, $ticket_id, $reply_author_id) {
    // Get ticket details
    $stmt = $pdo->prepare("
        SELECT t.*, tt.name as type_name, u.username as customer_name, u.email as customer_email
        FROM tickets t
        LEFT JOIN ticket_types tt ON t.type_id = tt.id
        LEFT JOIN users u ON t.user_id = u.id
        WHERE t.id = ?
    ");
    $stmt->execute([$ticket_id]);
    $ticket = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$ticket) {
        return false;
    }
    
    // Get reply author details
    $stmt = $pdo->prepare("SELECT username FROM users WHERE id = ?");
    $stmt->execute([$reply_author_id]);
    $reply_author = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$reply_author) {
        return false;
    }
    
    // Prepare email
    $subject = "New Reply to Support Ticket #" . $ticket_id;
    $message = getNewReplyEmailTemplate($ticket_id, $ticket['subject'], $reply_author['username'], $ticket['customer_name']);
    
    // Send email
    return sendEmail($ticket['customer_email'], $subject, $message);
}

// Function to notify support agents of new ticket
function notifyNewTicketToAgents($pdo, $ticket_id) {
    // Get ticket details
    $stmt = $pdo->prepare("
        SELECT t.*, tt.name as type_name, u.username as customer_name
        FROM tickets t
        LEFT JOIN ticket_types tt ON t.type_id = tt.id
        LEFT JOIN users u ON t.user_id = u.id
        WHERE t.id = ?
    ");
    $stmt->execute([$ticket_id]);
    $ticket = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$ticket) {
        return false;
    }
    
    // Get all support agents/admins
    $stmt = $pdo->query("SELECT email, username FROM users WHERE role = 'admin'");
    $agents = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $success = true;
    
    foreach ($agents as $agent) {
        $subject = "تذكرة دعم جديدة #" . $ticket_id . " تم إنشاؤها";
        $message = getAdminNewTicketNotificationTemplate(
            $ticket_id, 
            $ticket['customer_name'], 
            $ticket['type_name'], 
            $ticket['subject'], 
            $ticket['priority']
        );
        
        if (!sendEmail($agent['email'], $subject, $message, SUPPORT_EMAIL)) {
            $success = false;
        }
    }
    
    return $success;
}

// Function to send welcome email to new users
function sendWelcomeEmail($pdo, $user_id) {
    // Get user details
    $stmt = $pdo->prepare("SELECT username, email FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        return false;
    }
    
    // Prepare email
    $subject = "مرحبا بك في " . SITE_NAME . "!";
    $message = getWelcomeEmailTemplate($user['username'], SITE_NAME);
    
    // Send email
    return sendEmail($user['email'], $subject, $message, NO_REPLY_EMAIL);
}

// Function to send order confirmation email
function sendOrderConfirmationEmail($pdo, $order_id) {
    try {
        // Get order details with user information
        $stmt = $pdo->prepare("
            SELECT o.*, u.username as customer_name, u.email as customer_email, u.id as user_id
            FROM orders o 
            JOIN users u ON o.user_id = u.id 
            WHERE o.id = ?
        ");
        $stmt->execute([$order_id]);
        $order = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$order) {
            error_log("Order not found for ID: " . $order_id);
            return false;
        }
        
        // Get order items with product information
        $stmt = $pdo->prepare("
            SELECT oi.*, p.name
            FROM order_items oi
            JOIN products p ON oi.product_id = p.id
            WHERE oi.order_id = ?
        ");
        $stmt->execute([$order_id]);
        $order_items = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Get user's favorite products (limit to 5 for email)
        $stmt = $pdo->prepare("
            SELECT p.name, p.price, p.id
            FROM favorites f
            JOIN products p ON f.product_id = p.id
            WHERE f.user_id = ?
            ORDER BY f.created_at DESC
            LIMIT 5
        ");
        $stmt->execute([$order['user_id']]);
        $favorite_products = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Prepare email
        $subject = "تأكيد الطلب #" . $order_id . " - " . SITE_NAME;
        $message = getOrderConfirmationEmailTemplate(
            $order_id, 
            $order['customer_name'], 
            $order['total_amount'], 
            $order['payment_method'], 
            $order_items,
            $favorite_products
        );
        
        // Send email
        $result = sendEmail($order['customer_email'], $subject, $message, NO_REPLY_EMAIL);
        
        if ($result) {
            error_log("Order confirmation email sent successfully to: " . $order['customer_email']);
        } else {
            error_log("Failed to send order confirmation email to: " . $order['customer_email']);
        }
        
        return $result;
    } catch (Exception $e) {
        error_log("Error sending order confirmation email: " . $e->getMessage());
        return false;
    }
}
?>