<?php
session_start();
require_once '../layouts/dbconn.php';
require_once '../layouts/session.php';
require_once '../vendor/phpmailer/src/PHPMailer.php';

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

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method');
    }
    
    $order_test_id = isset($_POST['order_test_id']) ? intval($_POST['order_test_id']) : 0;
    $recipient_email = isset($_POST['recipient_email']) ? trim($_POST['recipient_email']) : '';
    $custom_message = isset($_POST['message']) ? trim($_POST['message']) : '';
    
    if ($order_test_id == 0) {
        throw new Exception('Invalid test ID');
    }
    
    if (empty($recipient_email) || !filter_var($recipient_email, FILTER_VALIDATE_EMAIL)) {
        throw new Exception('Valid email address is required');
    }
    
    // Fetch test details
    $query = "SELECT lot.*, lo.order_number, lo.patient_id,
                     p.patient_number, u.full_name as patient_name,
                     u.email as patient_email,
                     ett.test_name,
                     sender.full_name as sender_name,
                     sender.email as sender_email
              FROM lab_order_tests lot
              JOIN lab_orders lo ON lot.order_id = lo.order_id
              JOIN patients p ON lo.patient_id = p.patient_id
              JOIN users u ON p.user_id = u.user_id
              JOIN ent_test_types ett ON lot.test_type_id = ett.test_type_id
              JOIN users sender ON sender.user_id = ?
              WHERE lot.order_test_id = ? AND lot.status = 'COMPLETED'";
    
    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, "ii", $_SESSION['user_id'], $order_test_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    if (!$test = mysqli_fetch_assoc($result)) {
        throw new Exception('Test not found or not completed');
    }
    
    if (empty($test['report_file'])) {
        throw new Exception('Report file not found');
    }
    
    $report_path = '../reports/audiometry/' . $test['report_file'];
    
    if (!file_exists($report_path)) {
        throw new Exception('Report file does not exist on server');
    }
    
    // Get email settings
    $settings_query = "SELECT setting_key, setting_value 
                      FROM system_settings 
                      WHERE category = 'email' 
                      AND is_active = 1";
    $settings_result = mysqli_query($conn, $settings_query);
    $email_settings = [];
    
    while ($row = mysqli_fetch_assoc($settings_result)) {
        $email_settings[$row['setting_key']] = $row['setting_value'];
    }
    
    // Create PHPMailer instance
    $mail = new PHPMailer(true);
    
    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host = isset($email_settings['smtp_host']) ? $email_settings['smtp_host'] : 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->Username = isset($email_settings['smtp_username']) ? $email_settings['smtp_username'] : '';
        $mail->Password = isset($email_settings['smtp_password']) ? $email_settings['smtp_password'] : '';
        $mail->SMTPSecure = isset($email_settings['smtp_encryption']) ? $email_settings['smtp_encryption'] : 'tls';
        $mail->Port = isset($email_settings['smtp_port']) ? intval($email_settings['smtp_port']) : 587;
        
        // Recipients
        $mail->setFrom(
            isset($email_settings['from_email']) ? $email_settings['from_email'] : $test['sender_email'],
            isset($email_settings['from_name']) ? $email_settings['from_name'] : 'ENT Hospital'
        );
        $mail->addAddress($recipient_email);
        $mail->addReplyTo($test['sender_email'], $test['sender_name']);
        
        // Attachment
        $mail->addAttachment($report_path, $test['report_file']);
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Audiometry Test Report - ' . $test['patient_name'];
        
        // Email body
        $email_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; }
                .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                         color: white; padding: 20px; border-radius: 8px; text-align: center; }
                .content { background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0; }
                .info-row { margin: 10px 0; }
                .label { font-weight: bold; color: #667eea; }
                .footer { text-align: center; color: #6c757d; font-size: 12px; margin-top: 20px; 
                         padding-top: 20px; border-top: 1px solid #dee2e6; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h2>Audiometry Test Report</h2>
                    <p>Pure Tone Audiometry</p>
                </div>
                
                <div class="content">
                    <h3>Patient Information</h3>
                    <div class="info-row">
                        <span class="label">Patient Name:</span> ' . htmlspecialchars($test['patient_name']) . '
                    </div>
                    <div class="info-row">
                        <span class="label">Patient Number:</span> ' . htmlspecialchars($test['patient_number']) . '
                    </div>
                    <div class="info-row">
                        <span class="label">Test Date:</span> ' . date('d M Y', strtotime($test['completed_at'])) . '
                    </div>
                    <div class="info-row">
                        <span class="label">Order Number:</span> ' . htmlspecialchars($test['order_number']) . '
                    </div>
                </div>';
        
        if (!empty($custom_message)) {
            $email_body .= '
                <div class="content">
                    <h3>Message</h3>
                    <p>' . nl2br(htmlspecialchars($custom_message)) . '</p>
                </div>';
        }
        
        $email_body .= '
                <div class="content">
                    <p>Please find attached the complete audiometry test report in PDF format.</p>
                    <p><strong>Note:</strong> This report contains confidential medical information. 
                       Please handle it with appropriate care and security.</p>
                </div>
                
                <div class="footer">
                    <p>This email was sent from ENT Hospital Management System</p>
                    <p>For any questions, please contact us at ' . htmlspecialchars($test['sender_email']) . '</p>
                    <p>&copy; ' . date('Y') . ' ENT Hospital. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>';
        
        $mail->Body = $email_body;
        $mail->AltBody = strip_tags(str_replace(['<br>', '<br/>', '<br />'], "\n", $email_body));
        
        $mail->send();
        
        // Log activity
        $activity_query = "INSERT INTO activity_log (user_id, activity_type, description, ip_address, created_at)
                         VALUES (?, 'EMAIL', ?, ?, NOW())";
        $activity_stmt = mysqli_prepare($conn, $activity_query);
        $activity_desc = "Sent audiometry report for patient " . $test['patient_name'] . " to " . $recipient_email;
        $ip_address = $_SERVER['REMOTE_ADDR'];
        mysqli_stmt_bind_param($activity_stmt, "iss", $_SESSION['user_id'], $activity_desc, $ip_address);
        mysqli_stmt_execute($activity_stmt);
        
        echo json_encode([
            'success' => true,
            'message' => 'Report sent successfully to ' . $recipient_email
        ]);
        
    } catch (Exception $e) {
        throw new Exception('Mail Error: ' . $mail->ErrorInfo);
    }
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>