<?php
session_start();
include 'layouts/dbconn.php';
require 'vendor/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/src/SMTP.php';
require 'vendor/phpmailer/src/Exception.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Check if the user is not logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Function to check user permissions
function hasPermission($role_id, $permission) {
    // Define permissions for different roles
    $permissions = [
        '1' => ['view', 'edit', 'delete', 'approve', 'invoice'], // Admin has all permissions
        '2' => ['view', 'edit', 'approve', 'invoice'], // General Manager
        '3' => ['view', 'edit', 'invoice'], // Operations
        '4' => ['view', 'invoice'], // Finance
        '5' => ['view', 'edit'], // Declaration Officer
        '6' => ['view'], // Shipping Line Clerk
        '7' => ['view'], // Transport Supervisor
    ];
    
    if (isset($permissions[$role_id]) && in_array($permission, $permissions[$role_id])) {
        return true;
    }
    
    return false;
}

// Get user details and verify permissions
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, role_id, email FROM users WHERE user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param('i', $user_id);
$stmt_user->execute();
$result_user = $stmt_user->get_result();

if ($result_user->num_rows === 0) {
    $_SESSION['error_message'] = "User not found";
    header('Location: file_list.php');
    exit();
}

$user = $result_user->fetch_assoc();
$username = $user['username'];
$role_id = $user['role_id'];
$user_email = $user['email'];

// Verify user has invoice permissions
if (!hasPermission($role_id, 'invoice')) {
    $_SESSION['error_message'] = "You don't have permission to send invoices";
    header('Location: file_list.php');
    exit();
}

// Check if form is submitted
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['send_invoice'])) {
    $_SESSION['error_message'] = "Invalid request";
    header('Location: file_list.php');
    exit();
}

// Get email details from POST
$invoice_id = isset($_POST['invoice_id']) ? intval($_POST['invoice_id']) : 0;
$recipient_email = isset($_POST['recipient_email']) ? $_POST['recipient_email'] : '';
$cc_email = isset($_POST['cc_email']) ? $_POST['cc_email'] : '';
$subject = isset($_POST['subject']) ? $_POST['subject'] : '';
$message = isset($_POST['message']) ? $_POST['message'] : '';
$attach_pdf = isset($_POST['attach_pdf']) && $_POST['attach_pdf'] == '1';

// Validate input
if ($invoice_id <= 0 || empty($recipient_email) || empty($subject) || empty($message)) {
    $_SESSION['error_message'] = "Invalid email details";
    header("Location: view_invoice.php?id=$invoice_id");
    exit();
}

// Get invoice details
$invoice_query = "SELECT i.*, c.first_name as customer_name, f.id as file_id, f.currency as file_currency
                 FROM invoices i 
                 LEFT JOIN customers c ON i.customer_id = c.customer_id
                 LEFT JOIN files f ON i.file_number = f.file_number
                 WHERE i.invoice_id = ?";
$invoice_stmt = $conn->prepare($invoice_query);
$invoice_stmt->bind_param('i', $invoice_id);
$invoice_stmt->execute();
$invoice_result = $invoice_stmt->get_result();

if ($invoice_result->num_rows === 0) {
    $_SESSION['error_message'] = "Invoice not found";
    header('Location: file_list.php');
    exit();
}

$invoice = $invoice_result->fetch_assoc();
$file_id = $invoice['file_id'];
$file_number = $invoice['file_number'];

// Get company email settings
$settings_query = "SELECT * FROM settings WHERE setting_key IN ('system_name', 'address', 'tel_1', 'email_host', 'email_port', 'email_username', 'email_password', 'email_sender')";
$settings_result = $conn->query($settings_query);
$settings = [];

if ($settings_result->num_rows > 0) {
    while ($row = $settings_result->fetch_assoc()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
}

// If no email settings found, try to use user's email
if (empty($settings['email_sender'])) {
    $settings['email_sender'] = $user_email;
}

// Create temp directory for PDF if needed
$pdf_path = '';
if ($attach_pdf) {
    // Include PDF generation function
    require_once 'print_invoice_function.php';
    
    // Get PDF content
    try {
        $pdf_content = generateInvoicePDF($invoice_id, $conn);
        // Sanitize the filename by replacing slashes with underscores
        $sanitized_invoice_number = str_replace(['/', '\\', ':', '*', '?', '"', '<', '>', '|'], '_', $invoice['invoice_number']);
        $pdf_filename = 'Invoice_' . $sanitized_invoice_number . '.pdf';
        
        // Get system temp directory or use a custom one if system temp is not accessible
        $temp_dir = sys_get_temp_dir();
        if (!is_writable($temp_dir)) {
            // Fallback to a custom directory within the application
            $temp_dir = __DIR__ . '/temp';
            if (!file_exists($temp_dir)) {
                mkdir($temp_dir, 0755, true);
            }
        }
        
        $pdf_path = $temp_dir . '/' . $pdf_filename;
        
        // Use file_put_contents with error checking
        if (file_put_contents($pdf_path, $pdf_content) === false) {
            throw new Exception("Failed to save PDF file to: $pdf_path");
        }
    } catch (Exception $e) {
        $_SESSION['error_message'] = "Error generating invoice PDF: " . $e->getMessage();
        header("Location: view_invoice.php?id=$invoice_id");
        exit();
    }
}

// Send email using PHPMailer
$mail = new PHPMailer(true);

try {
    // Server settings
    if (!empty($settings['email_host']) && !empty($settings['email_port'])) {
        $mail->isSMTP();
        $mail->Host = $settings['email_host'];
        $mail->Port = $settings['email_port'];
        
        if (!empty($settings['email_username']) && !empty($settings['email_password'])) {
            $mail->SMTPAuth = true;
            $mail->Username = $settings['email_username'];
            $mail->Password = $settings['email_password'];
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Changed from SMTPS to STARTTLS for better compatibility
        }
    }
    
    // Recipients
    $from_email = !empty($settings['email_sender']) ? $settings['email_sender'] : $user_email;
    $from_name = !empty($settings['system_name']) ? $settings['system_name'] : 'Royal Freight System';
    
    $mail->setFrom($from_email, $from_name);
    $mail->addAddress($recipient_email);
    if (!empty($cc_email)) {
        $mail->addCC($cc_email);
    }
    $mail->addReplyTo($from_email, $from_name);
    
    // Content
    $mail->isHTML(true);
    $mail->Subject = $subject;
    
    // Create HTML message with nice formatting
    $html_message = '
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; }
            .header { background-color: #f8f9fa; padding: 20px; border-bottom: 3px solid #405189; }
            .content { padding: 20px; }
            .footer { margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; font-size: 12px; color: #777; }
            .invoice-details { background-color: #f8f9fa; padding: 15px; margin: 20px 0; border-left: 4px solid #405189; }
            .button { display: inline-block; padding: 10px 20px; background-color: #405189; color: white; text-decoration: none; border-radius: 4px; }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h2>' . htmlspecialchars($from_name) . '</h2>
            </div>
            <div class="content">
                ' . nl2br(htmlspecialchars($message)) . '
                
                <div class="invoice-details">
                    <p><strong>Invoice Number:</strong> ' . htmlspecialchars($invoice['invoice_number']) . '</p>
                    <p><strong>Amount:</strong> ' . htmlspecialchars($invoice['file_currency'] . ' ' . number_format($invoice['total_amount'], 2)) . '</p>
                    <p><strong>Due Date:</strong> ' . date('d M Y', strtotime($invoice['due_date'])) . '</p>
                </div>
                
                ' . ($attach_pdf ? '<p>Please find the invoice attached to this email.</p>' : '') . '
            </div>
            <div class="footer">
                <p>This is an automated message from ' . htmlspecialchars($from_name) . '.</p>
                <p>If you have any questions, please contact us at ' . htmlspecialchars($from_email) . '</p>
            </div>
        </div>
    </body>
    </html>';
    
    $mail->Body = $html_message;
    $mail->AltBody = strip_tags(str_replace('<br>', "\n", $message));
    
    // Attach PDF if generated
    if ($attach_pdf && file_exists($pdf_path)) {
        $mail->addAttachment($pdf_path, $pdf_filename);
    }
    
    // Send email
    if ($mail->send()) {
        // Record email sending in the database
        $record_query = "INSERT INTO invoice_emails (
            invoice_id, sent_date, recipient_email, cc_email, 
            subject, message, attachment, sent_by
        ) VALUES (?, NOW(), ?, ?, ?, ?, ?, ?)";
        
        $attachment = $attach_pdf ? $pdf_filename : '';
        
        $record_stmt = $conn->prepare($record_query);
        if ($record_stmt) {
            $record_stmt->bind_param(
                'isssssi',
                $invoice_id,
                $recipient_email,
                $cc_email,
                $subject,
                $message,
                $attachment,
                $user_id
            );
            $record_stmt->execute();
        }
        
        // Create notification
        $notif_message = "Invoice {$invoice['invoice_number']} sent to $recipient_email by {$username}.";
        $notif_query = "INSERT INTO notifications (file_id, file_number, notif_message, notif_message_id, created_at) 
                        VALUES (?, ?, ?, 2, NOW())";
        
        $notif_stmt = $conn->prepare($notif_query);
        if ($notif_stmt) {
            $notif_message_id = 2; // Assuming 2 is for updates
            $notif_stmt->bind_param('iss', $file_id, $file_number, $notif_message);
            $notif_stmt->execute();
        }
        
        $_SESSION['success_message'] = "Invoice sent successfully to $recipient_email";
    } else {
        throw new Exception("Mailer Error: " . $mail->ErrorInfo);
    }
} catch (Exception $e) {
    $_SESSION['error_message'] = "Error sending email: " . $e->getMessage();
}

// Clean up temp file
if ($attach_pdf && file_exists($pdf_path)) {
    unlink($pdf_path);
}

// Redirect back to invoice view
header("Location: view_invoice.php?id=$invoice_id");
exit();
?>