<?php
require_once '../config/database.php';
require_once '../includes/mail_config.php';
require_once '../includes/company_config.php';
secureSessionStart();
requireLogin();

header('Content-Type: application/json');

$conn = getConnection();
$admin_id = $_SESSION['admin_user'];
$company = getCompanyDetails($conn);

// Get POST data
$user_id = mysqli_real_escape_string($conn, $_POST['user_id'] ?? '');
$to_email = mysqli_real_escape_string($conn, $_POST['to_email'] ?? '');
$subject = mysqli_real_escape_string($conn, $_POST['subject'] ?? '');
$message = $_POST['message'] ?? ''; // This is now HTML formatted

// Validate
if (empty($to_email) || empty($subject) || empty($message)) {
    echo json_encode(['success' => false, 'error' => 'All fields are required']);
    exit();
}

// Get user details
$user_query = mysqli_query($conn, "SELECT name FROM users WHERE user_id = '$user_id'");
$user = mysqli_fetch_assoc($user_query);

// Load PHPMailer
require_once '../../PHPMailer/src/Exception.php';
require_once '../../PHPMailer/src/PHPMailer.php';
require_once '../../PHPMailer/src/SMTP.php';

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

$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->isSMTP();
    $mail->Host       = SMTP_HOST;
    $mail->SMTPAuth   = true;
    $mail->Username   = SMTP_USERNAME;
    $mail->Password   = SMTP_PASSWORD;
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = SMTP_PORT;
    $mail->CharSet    = 'UTF-8';
    
    // Recipients
    $mail->setFrom(SMTP_FROM_EMAIL, $company['name']);
    $mail->addAddress($to_email, $user['name'] ?? 'User');
    $mail->addReplyTo($company['email'], $company['name']);
    
    // Create full HTML email with proper styling
    $htmlBody = '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body { 
            font-family: Arial, Helvetica, sans-serif; 
            line-height: 1.6; 
            color: #333333; 
            margin: 0; 
            padding: 0; 
            background-color: #f4f4f4;
        }
        .container { 
            max-width: 600px; 
            margin: 20px auto; 
            background: #ffffff; 
            border-radius: 10px; 
            overflow: hidden; 
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .header { 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            color: white; 
            padding: 30px 20px; 
            text-align: center; 
        }
        .header h1 { 
            margin: 0; 
            font-size: 28px; 
            font-weight: 600;
        }
        .content { 
            padding: 30px 25px; 
            background: #ffffff; 
        }
        .content p { 
            margin: 15px 0; 
            font-size: 16px;
        }
        .content p:first-child { 
            margin-top: 0; 
        }
        .content p:last-child { 
            margin-bottom: 0; 
        }
        .content br { 
            display: block; 
            content: ""; 
            margin: 5px 0; 
        }
        .footer { 
            background: #f8f9fa; 
            padding: 25px 20px; 
            text-align: center; 
            font-size: 14px; 
            color: #666; 
            border-top: 1px solid #e9ecef; 
        }
        .footer p { 
            margin: 5px 0; 
        }
        .footer strong { 
            color: #667eea; 
        }
        .info-box { 
            background: #f8f9fa; 
            border-left: 4px solid #667eea; 
            padding: 15px 20px; 
            margin: 20px 0; 
            border-radius: 0 5px 5px 0; 
        }
        .info-box p { 
            margin: 8px 0; 
        }
        ul, ol { 
            margin: 15px 0 15px 25px; 
            padding-left: 10px; 
        }
        li { 
            margin-bottom: 8px; 
            font-size: 16px;
        }
        strong { 
            color: #667eea; 
            font-weight: 600;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>' . $company['name'] . '</h1>
        </div>
        <div class="content">
            ' . $message . '
        </div>
        <div class="footer">
            <p><strong>' . $company['name'] . '</strong></p>
            <p>' . ($company['address'] ?? '') . '</p>
            <p>📧 ' . $company['email'] . ' | 📞 ' . $company['mobile'] . '</p>
            <p style="font-size: 12px; margin-top: 15px; color: #999;">This is an automated message. Please do not reply to this email.</p>
        </div>
    </div>
</body>
</html>';
    
    // Send as HTML
    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body    = $htmlBody;
    $mail->AltBody = strip_tags(str_replace(['<br>', '<br/>', '<br />'], "\n", $message)); // Plain text version with line breaks
    
    $mail->send();
    
    // Log success
    $raw_message = mysqli_real_escape_string($conn, $_POST['raw_message'] ?? $message);
    $log_query = "INSERT INTO email_logs (user_id, admin_id, subject, message, status, sent_at) 
                  VALUES ('$user_id', '$admin_id', '$subject', '$raw_message', 'sent', NOW())";
    mysqli_query($conn, $log_query);
    
    echo json_encode(['success' => true, 'message' => 'Email sent successfully']);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => 'Mailer Error: ' . $mail->ErrorInfo]);
}
exit();
?>