<?php
/**
 * Email Helper Functions for Work Planner
 * Uses PHPMailer for sending email notifications
 */

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

require_once __DIR__ . '/../vendor/autoload.php';

/**
 * Send reminder email to user
 * 
 * @param string $to_email Recipient email address
 * @param string $to_name Recipient name
 * @param array $task_data Task information (title, start_datetime, description)
 * @param string $reminder_time When the reminder is for
 * @return bool Success status
 */
function sendReminderEmail($to_email, $to_name, $task_data, $reminder_time) {
    $config = require __DIR__ . '/email_config.php';
    
    // Check if email is enabled
    if (!$config['enabled']) {
        return false;
    }
    
    $mail = new PHPMailer(true);
    
    try {
        // Server settings
        if ($config['debug_mode']) {
            $mail->SMTPDebug = 2;
        }
        $mail->isSMTP();
        $mail->Host       = $config['smtp_host'];
        $mail->SMTPAuth   = true;
        $mail->Username   = $config['smtp_username'];
        $mail->Password   = $config['smtp_password'];
        $mail->SMTPSecure = $config['smtp_secure'];
        $mail->Port       = $config['smtp_port'];
        
        // Recipients
        $mail->setFrom($config['from_email'], $config['from_name']);
        $mail->addAddress($to_email, $to_name);
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Reminder: ' . $task_data['title'];
        
        // Format the email body
        $start_time = new DateTime($task_data['start_datetime']);
        $now = new DateTime();
        $diff = $now->diff($start_time);
        
        // Calculate time until task
        if ($start_time > $now) {
            if ($diff->days > 0) {
                $time_until = $diff->days . ' day' . ($diff->days > 1 ? 's' : '');
            } else {
                $time_until = $diff->h . ' hour' . ($diff->h > 1 ? 's' : '');
            }
        } else {
            $time_until = 'Now';
        }
        
        $body = '
        <html>
        <head>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    line-height: 1.6;
                    color: #333;
                }
                .container {
                    max-width: 600px;
                    margin: 0 auto;
                    padding: 20px;
                    background-color: #f9f9f9;
                }
                .header {
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    color: white;
                    padding: 30px;
                    text-align: center;
                    border-radius: 10px 10px 0 0;
                }
                .content {
                    background: white;
                    padding: 30px;
                    border-radius: 0 0 10px 10px;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                }
                .task-title {
                    font-size: 24px;
                    color: #2c3e50;
                    margin-bottom: 20px;
                }
                .task-info {
                    background: #ecf0f1;
                    padding: 15px;
                    border-radius: 8px;
                    margin: 15px 0;
                }
                .task-info p {
                    margin: 8px 0;
                }
                .time-badge {
                    display: inline-block;
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    color: white;
                    padding: 8px 16px;
                    border-radius: 20px;
                    font-weight: bold;
                    margin: 10px 0;
                }
                .footer {
                    text-align: center;
                    margin-top: 20px;
                    padding-top: 20px;
                    border-top: 2px solid #ecf0f1;
                    color: #7f8c8d;
                    font-size: 14px;
                }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>Task Reminder</h1>
                </div>
                <div class="content">
                    <p>Hi ' . htmlspecialchars($to_name) . ',</p>
                    
                    <p>This is a friendly reminder about your upcoming task:</p>
                    
                    <div class="task-title">
                        ' . htmlspecialchars($task_data['title']) . '
                    </div>
                    
                    <div class="task-info">
                        <p><strong>Starts in:</strong> <span class="time-badge">' . $time_until . '</span></p>
                        <p><strong>Start Time:</strong> ' . $start_time->format('l, F j, Y - g:i A') . '</p>
                        ' . (!empty($task_data['description']) ? '<p><strong>Description:</strong><br>' . nl2br(htmlspecialchars($task_data['description'])) . '</p>' : '') . '
                    </div>
                    
                    <p>Don\'t forget to prepare for your task!</p>
                    
                    <div class="footer">
                        <p>You received this email because you have notifications enabled in your Work Planner account.</p>
                        <p>To manage your notification preferences, visit your profile settings.</p>
                    </div>
                </div>
            </div>
        </body>
        </html>
        ';
        
        $mail->Body = $body;
        
        // Plain text alternative
        $mail->AltBody = "Hi $to_name,\n\n" .
                        "Reminder: {$task_data['title']}\n" .
                        "Starts in: $time_until\n" .
                        "Start Time: " . $start_time->format('l, F j, Y - g:i A') . "\n" .
                        (!empty($task_data['description']) ? "Description: {$task_data['description']}\n" : '') .
                        "\nWork Planner";
        
        $mail->send();
        return true;
        
    } catch (Exception $e) {
        // Log error (in production, use proper logging)
        error_log("Email sending failed: {$mail->ErrorInfo}");
        return false;
    }
}

/**
 * Send welcome email to new user
 * 
 * @param string $to_email Recipient email address
 * @param string $to_name Recipient name
 * @return bool Success status
 */
function sendWelcomeEmail($to_email, $to_name) {
    $config = require __DIR__ . '/email_config.php';
    
    if (!$config['enabled']) {
        return false;
    }
    
    $mail = new PHPMailer(true);
    
    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host       = $config['smtp_host'];
        $mail->SMTPAuth   = true;
        $mail->Username   = $config['smtp_username'];
        $mail->Password   = $config['smtp_password'];
        $mail->SMTPSecure = $config['smtp_secure'];
        $mail->Port       = $config['smtp_port'];
        
        // Recipients
        $mail->setFrom($config['from_email'], $config['from_name']);
        $mail->addAddress($to_email, $to_name);
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Welcome to Work Planner!';
        
        $body = '
        <html>
        <head>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    line-height: 1.6;
                    color: #333;
                }
                .container {
                    max-width: 600px;
                    margin: 0 auto;
                    padding: 20px;
                    background-color: #f9f9f9;
                }
                .header {
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    color: white;
                    padding: 30px;
                    text-align: center;
                    border-radius: 10px 10px 0 0;
                }
                .content {
                    background: white;
                    padding: 30px;
                    border-radius: 0 0 10px 10px;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                }
                .feature {
                    margin: 15px 0;
                    padding: 15px;
                    background: #ecf0f1;
                    border-radius: 8px;
                }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>Welcome to Work Planner!</h1>
                </div>
                <div class="content">
                    <p>Hi ' . htmlspecialchars($to_name) . ',</p>
                    
                    <p>Thank you for joining Work Planner! We\'re excited to help you organize your tasks and stay on top of your schedule.</p>
                    
                    <h3>Getting Started:</h3>
                    
                    <div class="feature">
                        <strong>Create Calendars</strong><br>
                        Organize your tasks by creating multiple calendars for work, personal life, or projects.
                    </div>
                    
                    <div class="feature">
                        <strong>Add Tasks</strong><br>
                        Create tasks with detailed information, time slots, and color coding.
                    </div>
                    
                    <div class="feature">
                        <strong>Set Reminders</strong><br>
                        Get notified before your tasks start. Customize reminder times in your profile.
                    </div>
                    
                    <div class="feature">
                        <strong>Collaborate</strong><br>
                        Share calendars with friends and work in teams.
                    </div>
                    
                    <p style="margin-top: 30px;">Ready to get organized? Log in and start planning!</p>
                    
                    <p style="color: #7f8c8d; font-size: 14px; margin-top: 30px; padding-top: 20px; border-top: 2px solid #ecf0f1;">
                        If you didn\'t create this account, please ignore this email.
                    </p>
                </div>
            </div>
        </body>
        </html>
        ';
        
        $mail->Body = $body;
        $mail->AltBody = "Welcome to Work Planner, $to_name!\n\nThank you for joining us. Start organizing your tasks today!";
        
        $mail->send();
        return true;
        
    } catch (Exception $e) {
        error_log("Welcome email sending failed: {$mail->ErrorInfo}");
        return false;
    }
}