<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || $_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

include '../layouts/dbconn.php';

// Use PHPMailer for email sending (you'll need to install via Composer: composer require phpmailer/phpmailer)
// For now, I'll show the complete implementation with mail() function and include PHPMailer option

$invoice_id = intval($_POST['invoice_id']);
$to_email = trim($_POST['to_email']);
$cc_email = !empty($_POST['cc_email']) ? trim($_POST['cc_email']) : null;
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
$attach_pdf = isset($_POST['attach_pdf']);
$mark_as_sent = isset($_POST['mark_as_sent']);

// Validate email
if (!filter_var($to_email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'message' => 'Invalid email address']);
    exit();
}

// Get system settings
$settings = [];
$settings_sql = "SELECT setting_key, setting_value FROM system_settings 
                 WHERE setting_key IN ('site_name', 'company_email', 'smtp_host', 
                 'smtp_port', 'smtp_username', 'smtp_password', 'smtp_encryption', 'company_logo')";
$settings_result = $conn->query($settings_sql);
while ($row = $settings_result->fetch_assoc()) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

$from_email = $settings['company_email'] ?? 'noreply@caregiving.com';
$from_name = $settings['site_name'] ?? 'Caregiving Services';

// Get invoice details
$invoice_sql = "SELECT i.*, 
                JSON_UNQUOTE(JSON_EXTRACT(cl.personal_info, '$.first_name')) as client_first_name,
                JSON_UNQUOTE(JSON_EXTRACT(cl.personal_info, '$.last_name')) as client_last_name
                FROM invoices i
                INNER JOIN clients cl ON i.client_id = cl.client_id
                WHERE i.invoice_id = ?";
$stmt = $conn->prepare($invoice_sql);
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$invoice = $stmt->get_result()->fetch_assoc();

if (!$invoice) {
    echo json_encode(['success' => false, 'message' => 'Invoice not found']);
    exit();
}

// Create HTML email template
$html_message = getEmailTemplate($invoice, $message, $settings);

try {
    // Option 1: Using PHPMailer (RECOMMENDED for production)
    if (file_exists('../vendor/autoload.php')) {
        require '../vendor/autoload.php';
        
        use PHPMailer\PHPMailer\PHPMailer;
        use PHPMailer\PHPMailer\Exception;
        
        $mail = new PHPMailer(true);
        
        // Server settings
        if (!empty($settings['smtp_host'])) {
            $mail->isSMTP();
            $mail->Host = $settings['smtp_host'];
            $mail->SMTPAuth = true;
            $mail->Username = $settings['smtp_username'] ?? '';
            $mail->Password = $settings['smtp_password'] ?? '';
            $mail->SMTPSecure = $settings['smtp_encryption'] ?? 'tls';
            $mail->Port = $settings['smtp_port'] ?? 587;
        }
        
        // Recipients
        $mail->setFrom($from_email, $from_name);
        $mail->addAddress($to_email);
        if ($cc_email) {
            $mail->addCC($cc_email);
        }
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body = $html_message;
        $mail->AltBody = strip_tags($message);
        
        // Attach PDF if requested
        if ($attach_pdf) {
            $pdf_path = generateInvoicePDF($invoice_id, $conn, $settings);
            if ($pdf_path && file_exists($pdf_path)) {
                $mail->addAttachment($pdf_path, 'Invoice_' . $invoice['invoice_number'] . '.pdf');
            }
        }
        
        $mail->send();
        $email_sent = true;
        
        // Clean up PDF
        if ($attach_pdf && isset($pdf_path) && file_exists($pdf_path)) {
            unlink($pdf_path);
        }
        
    } else {
        // Option 2: Using PHP mail() function (FALLBACK - less reliable)
        $headers = "From: $from_name <$from_email>\r\n";
        $headers .= "Reply-To: $from_email\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
        
        if ($cc_email) {
            $headers .= "Cc: $cc_email\r\n";
        }
        
        $email_sent = mail($to_email, $subject, $html_message, $headers);
    }
    
    if ($email_sent) {
        // Update invoice status if requested
        if ($mark_as_sent && $invoice['status'] === 'draft') {
            $update_sql = "UPDATE invoices SET status = 'sent', sent_date = CURDATE() WHERE invoice_id = ?";
            $update_stmt = $conn->prepare($update_sql);
            $update_stmt->bind_param("i", $invoice_id);
            $update_stmt->execute();
        }
        
        // Log the activity
        $log_sql = "INSERT INTO audit_log (user_id, action_type, entity_type, entity_id, description, ip_address, created_at) 
                    VALUES (?, 'EMAIL', 'invoices', ?, ?, ?, NOW())";
        $log_stmt = $conn->prepare($log_sql);
        $description = "Invoice #{$invoice['invoice_number']} sent to {$to_email}";
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $log_stmt->bind_param("iiss", $_SESSION['user_id'], $invoice_id, $description, $ip_address);
        $log_stmt->execute();
        
        echo json_encode([
            'success' => true,
            'message' => 'Invoice sent successfully',
            'sent_to' => $to_email
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Failed to send email. Please check your SMTP settings.'
        ]);
    }
    
} catch (Exception $e) {
    error_log("Email Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error sending email: ' . $e->getMessage()
    ]);
}

function getEmailTemplate($invoice, $message, $settings) {
    $company_name = $settings['site_name'] ?? 'Caregiving Services';
    $company_logo = $settings['company_logo'] ?? 'assets/images/prodigy.png';
    
    $logo_url = 'https://' . $_SERVER['HTTP_HOST'] . '/' . $company_logo;
    
    $html = '
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <style>
            body {
                font-family: Arial, sans-serif;
                line-height: 1.6;
                color: #333;
                margin: 0;
                padding: 0;
            }
            .email-container {
                max-width: 600px;
                margin: 0 auto;
                background: #ffffff;
            }
            .email-header {
                background: linear-gradient(135deg, #8FBC8F 0%, #20B2AA 100%);
                color: white;
                padding: 30px;
                text-align: center;
            }
            .email-header img {
                max-width: 150px;
                margin-bottom: 15px;
            }
            .email-body {
                padding: 30px;
            }
            .invoice-summary {
                background: #f8f9fa;
                padding: 20px;
                border-radius: 8px;
                margin: 20px 0;
            }
            .summary-row {
                display: flex;
                justify-content: space-between;
                padding: 8px 0;
                border-bottom: 1px solid #dee2e6;
            }
            .summary-row:last-child {
                border-bottom: none;
            }
            .total-row {
                background: #8FBC8F;
                color: white;
                padding: 15px;
                margin-top: 10px;
                border-radius: 5px;
                font-size: 18px;
                font-weight: bold;
            }
            .button {
                display: inline-block;
                padding: 12px 30px;
                background: #8FBC8F;
                color: white;
                text-decoration: none;
                border-radius: 5px;
                margin: 20px 0;
            }
            .email-footer {
                background: #f8f9fa;
                padding: 20px;
                text-align: center;
                font-size: 12px;
                color: #666;
            }
        </style>
    </head>
    <body>
        <div class="email-container">
            <div class="email-header">
                <img src="' . htmlspecialchars($logo_url) . '" alt="' . htmlspecialchars($company_name) . '">
                <h2>Invoice Notification</h2>
            </div>
            
            <div class="email-body">
                <p>' . nl2br(htmlspecialchars($message)) . '</p>
                
                <div class="invoice-summary">
                    <h3 style="margin-top: 0; color: #8FBC8F;">Invoice Summary</h3>
                    <div class="summary-row">
                        <span>Invoice Number:</span>
                        <strong>' . htmlspecialchars($invoice['invoice_number']) . '</strong>
                    </div>
                    <div class="summary-row">
                        <span>Invoice Date:</span>
                        <span>' . date('F d, Y', strtotime($invoice['invoice_date'])) . '</span>
                    </div>
                    <div class="summary-row">
                        <span>Due Date:</span>
                        <span>' . date('F d, Y', strtotime($invoice['due_date'])) . '</span>
                    </div>
                    <div class="summary-row">
                        <span>Subtotal:</span>
                        <span>KES ' . number_format($invoice['subtotal'], 2) . '</span>
                    </div>';
    
    if ($invoice['tax_amount'] > 0) {
        $html .= '
                    <div class="summary-row">
                        <span>Tax:</span>
                        <span>KES ' . number_format($invoice['tax_amount'], 2) . '</span>
                    </div>';
    }
    
    if ($invoice['discount_amount'] > 0) {
        $html .= '
                    <div class="summary-row">
                        <span>Discount:</span>
                        <span style="color: #dc3545;">-KES ' . number_format($invoice['discount_amount'], 2) . '</span>
                    </div>';
    }
    
    $html .= '
                    <div class="total-row">
                        <div style="display: flex; justify-content: space-between;">
                            <span>Total Amount:</span>
                            <span>KES ' . number_format($invoice['total_amount'], 2) . '</span>
                        </div>
                    </div>';
    
    if ($invoice['balance_due'] > 0) {
        $html .= '
                    <div style="background: #fff3cd; padding: 15px; margin-top: 10px; border-radius: 5px;">
                        <div style="display: flex; justify-content: space-between;">
                            <strong>Balance Due:</strong>
                            <strong style="color: #dc3545;">KES ' . number_format($invoice['balance_due'], 2) . '</strong>
                        </div>
                    </div>';
    }
    
    $html .= '
                </div>
                
                <p style="text-align: center;">
                    <a href="https://' . $_SERVER['HTTP_HOST'] . '/view_invoice.php?id=' . $invoice['invoice_id'] . '" class="button">View Invoice Online</a>
                </p>
                
                <p style="color: #666; font-size: 14px;">
                    <strong>Note:</strong> The detailed invoice is attached to this email as a PDF document.
                </p>
            </div>
            
            <div class="email-footer">
                <p><strong>' . htmlspecialchars($company_name) . '</strong></p>
                <p>This is an automated email. Please do not reply directly to this message.</p>
                <p style="margin-top: 10px;">
                    &copy; ' . date('Y') . ' ' . htmlspecialchars($company_name) . '. All rights reserved.
                </p>
            </div>
        </div>
    </body>
    </html>';
    
    return $html;
}

function generateInvoicePDF($invoice_id, $conn, $settings) {
    // This function generates a PDF version of the invoice
    // You can use libraries like TCPDF, FPDF, or Dompdf
    
    // For now, we'll create a simple implementation
    // In production, you should use a proper PDF library
    
    $temp_dir = sys_get_temp_dir();
    $pdf_filename = $temp_dir . '/invoice_' . $invoice_id . '_' . time() . '.pdf';
    
    // Get invoice HTML
    ob_start();
    include '../print_invoice.php';
    $html = ob_get_clean();
    
    // Use a PDF library to convert HTML to PDF
    // Example with Dompdf (install via: composer require dompdf/dompdf)
    if (file_exists('../vendor/autoload.php')) {
        require '../vendor/autoload.php';
        
        use Dompdf\Dompdf;
        use Dompdf\Options;
        
        $options = new Options();
        $options->set('isHtml5ParserEnabled', true);
        $options->set('isRemoteEnabled', true);
        
        $dompdf = new Dompdf($options);
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();
        
        file_put_contents($pdf_filename, $dompdf->output());
        
        return $pdf_filename;
    }
    
    return null;
}
?>