<?php

namespace SSCI\Classes;

use PHPMailer\PHPMailer\PHPMailer;

/**
 * Invoice Manager Class
 * Handles invoice operations including sending via email, WhatsApp, and in-app notifications
 */
class InvoiceManager
{
    private $db;
    private $auth;
    private $mailer;

    public function __construct($db, $auth)
    {
        $this->db = $db;
        $this->auth = $auth;
        $this->initializeMailer();
    }

    /**
     * Initialize PHPMailer with system SMTP settings
     */
    private function initializeMailer()
    {
        $this->mailer = new PHPMailer(true);
        
        try {
            // Get SMTP settings from database
            $smtpSettings = $this->getSMTPSettings();
            
            if ($smtpSettings) {
                $this->mailer->isSMTP();
                $this->mailer->Host = $smtpSettings['host'] ?? 'smtp.gmail.com';
                $this->mailer->Port = $smtpSettings['port'] ?? 587;
                $this->mailer->SMTPAuth = true;
                $this->mailer->Username = $smtpSettings['username'] ?? '';
                $this->mailer->Password = $smtpSettings['password'] ?? '';
                $this->mailer->SMTPSecure = $smtpSettings['encryption'] ?? PHPMailer::ENCRYPTION_STARTTLS;
            }
        } catch (\Exception $e) {
            error_log('PHPMailer initialization error: ' . $e->getMessage());
        }
    }

    /**
     * Get SMTP settings from database settings table
     */
    private function getSMTPSettings()
    {
        try {
            $settings = $this->db->fetch(
                "SELECT * FROM settings LIMIT 1"
            );
            
            if ($settings) {
                return [
                    'host' => $settings['smtp_host'] ?? 'smtp.gmail.com',
                    'port' => $settings['smtp_port'] ?? 587,
                    'username' => $settings['smtp_user'] ?? '',
                    'password' => $settings['smtp_password'] ?? '',
                    'encryption' => $settings['smtp_encryption'] ?? PHPMailer::ENCRYPTION_STARTTLS,
                    'from_email' => $settings['smtp_from'] ?? 'noreply@ssci.local',
                    'from_name' => $settings['site_name'] ?? 'SSCI Office'
                ];
            }
        } catch (\Exception $e) {
            error_log('Error fetching SMTP settings: ' . $e->getMessage());
        }
        return null;
    }

    /**
     * Send invoice via email
     */
    public function sendViaEmail($invoiceId, $toEmail = null)
    {
        try {
            $invoice = $this->db->fetch(
                "SELECT i.*, u.name as owner_name, u.email, p.name as post_name
                 FROM invoices i
                 LEFT JOIN users u ON i.owner_id = u.id
                 LEFT JOIN posts p ON i.post_id = p.id
                 WHERE i.id = ?",
                [$invoiceId]
            );

            if (!$invoice) {
                return ['success' => false, 'error' => 'Invoice not found'];
            }

            $smtpSettings = $this->getSMTPSettings();
            if (!$smtpSettings) {
                return ['success' => false, 'error' => 'SMTP settings not configured'];
            }

            // Use provided email or get from invoice owner
            $recipientEmail = $toEmail ?? $invoice['email'];
            if (!$recipientEmail) {
                return ['success' => false, 'error' => 'No recipient email found'];
            }

            // Set email properties
            $this->mailer->setFrom($smtpSettings['from_email'], $smtpSettings['from_name']);
            $this->mailer->addAddress($recipientEmail, $invoice['owner_name']);
            $this->mailer->Subject = "Invoice {$invoice['invoice_number']} from SSCI";
            
            // Create email body
            $emailBody = $this->generateEmailBody($invoice);
            $this->mailer->msgHTML($emailBody);
            
            // Add invoice PDF as attachment (if PDF generation is implemented)
            // $pdfPath = $this->generateInvoicePDF($invoiceId);
            // if ($pdfPath && file_exists($pdfPath)) {
            //     $this->mailer->addAttachment($pdfPath, "Invoice_{$invoice['invoice_number']}.pdf");
            // }

            $this->mailer->send();

            // Mark invoice as sent
            $this->db->query(
                "UPDATE invoices SET status = 'Sent', updated_at = NOW() WHERE id = ?",
                [$invoiceId]
            );

            return ['success' => true, 'message' => 'Invoice sent successfully'];
        } catch (\Exception $e) {
            error_log('Email send error: ' . $e->getMessage());
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }

    /**
     * Send invoice via WhatsApp using UltraMsg API
     */
    public function sendViaWhatsApp($invoiceId, $phoneNumber = null)
    {
        try {
            $invoice = $this->db->fetch(
                "SELECT i.*, u.name as owner_name, u.phone, u.whatsapp, p.name as post_name
                 FROM invoices i
                 LEFT JOIN users u ON i.owner_id = u.id
                 LEFT JOIN posts p ON i.post_id = p.id
                 WHERE i.id = ?",
                [$invoiceId]
            );

            if (!$invoice) {
                return ['success' => false, 'error' => 'Invoice not found'];
            }

            // Get WhatsApp token from environment
            $whatsappToken = getenv('WHATSAPP_API_TOKEN') ?: $_ENV['WHATSAPP_API_TOKEN'] ?? null;
            if (!$whatsappToken) {
                return ['success' => false, 'error' => 'WhatsApp API token not configured'];
            }

            // Use provided phone or get from invoice owner
            $phone = $phoneNumber ?? $invoice['whatsapp'] ?? $invoice['phone'];
            if (!$phone) {
                return ['success' => false, 'error' => 'No recipient phone number found'];
            }

            // Format phone number (remove spaces, dashes, etc.)
            $phone = preg_replace('/[^0-9]/', '', $phone);
            
            // Prepare message
            $message = "Hello {$invoice['owner_name']},\n\n";
            $message .= "Your invoice {$invoice['invoice_number']} has been generated.\n";
            $message .= "Invoice Date: " . date('M d, Y', strtotime($invoice['invoice_date'])) . "\n";
            $message .= "Amount: " . number_format($invoice['total_amount'], 2) . " " . ($invoice['currency'] ?? 'FCFA') . "\n";
            $message .= "Status: {$invoice['status']}\n\n";
            $message .= "Please log in to your account to view the full invoice details.\n";
            $message .= "Thank you for using SSCI services.";

            // Call UltraMsg API
            $instanceId = getenv('WHATSAPP_INSTANCE_ID') ?: $_ENV['WHATSAPP_INSTANCE_ID'] ?? null;
            $apiUrl = "https://api.ultramsg.com/{$instanceId}/messages/chat";

            $postData = [
                'token' => $whatsappToken,
                'to' => $phone,
                'body' => $message
            ];

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $apiUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            $response = curl_exec($ch);
            curl_close($ch);

            $responseData = json_decode($response, true);

            if ($responseData['success'] ?? false) {
                return ['success' => true, 'message' => 'WhatsApp message sent successfully'];
            } else {
                return ['success' => false, 'error' => $responseData['message'] ?? 'Failed to send WhatsApp message'];
            }
        } catch (\Exception $e) {
            error_log('WhatsApp send error: ' . $e->getMessage());
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }

    /**
     * Create in-app notification for invoice sent
     */
    public function createInAppNotification($invoiceId)
    {
        try {
            $invoice = $this->db->fetch(
                "SELECT i.*, u.name as owner_name FROM invoices i
                 LEFT JOIN users u ON i.owner_id = u.id
                 WHERE i.id = ?",
                [$invoiceId]
            );

            if (!$invoice) {
                return ['success' => false, 'error' => 'Invoice not found'];
            }

            // Create notification
            $this->db->query(
                "INSERT INTO notifications (user_id, type, title, message, reference_id, reference_type, created_at)
                 VALUES (?, ?, ?, ?, ?, ?, NOW())",
                [
                    $invoice['owner_id'],
                    'invoice_sent',
                    'Invoice Sent',
                    "Your invoice {$invoice['invoice_number']} has been sent to you.",
                    $invoiceId,
                    'invoice'
                ]
            );

            return ['success' => true, 'message' => 'In-app notification created'];
        } catch (\Exception $e) {
            error_log('Notification creation error: ' . $e->getMessage());
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }

    /**
     * Generate email body HTML
     */
    private function generateEmailBody($invoice)
    {
        $currencySymbol = $invoice['currency'] === 'USD' ? '$' : (getenv('CURRENCY_SYMBOL') ?: '₣');
        
        return "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background-color: #2563eb; color: white; padding: 20px; text-align: center; border-radius: 5px 5px 0 0; }
                .content { background-color: #f9fafb; padding: 20px; border: 1px solid #e5e7eb; }
                .invoice-details { margin: 20px 0; }
                .detail-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #e5e7eb; }
                .detail-row:last-child { border-bottom: none; }
                .label { font-weight: bold; color: #666; }
                .amount { color: #2563eb; font-weight: bold; font-size: 18px; }
                .footer { text-align: center; padding: 20px; font-size: 12px; color: #666; }
            </style>
        </head>
        <body>
            <div class=\"container\">
                <div class=\"header\">
                    <h1>SSCI Invoice</h1>
                </div>
                <div class=\"content\">
                    <p>Dear {$invoice['owner_name']},</p>
                    <p>We are pleased to send you the following invoice:</p>
                    
                    <div class=\"invoice-details\">
                        <div class=\"detail-row\">
                            <span class=\"label\">Invoice Number:</span>
                            <span>{$invoice['invoice_number']}</span>
                        </div>
                        <div class=\"detail-row\">
                            <span class=\"label\">Invoice Date:</span>
                            <span>" . date('F d, Y', strtotime($invoice['invoice_date'])) . "</span>
                        </div>
                        <div class=\"detail-row\">
                            <span class=\"label\">Due Date:</span>
                            <span>" . ($invoice['due_date'] ? date('F d, Y', strtotime($invoice['due_date'])) : 'N/A') . "</span>
                        </div>
                        <div class=\"detail-row\">
                            <span class=\"label\">Post/Location:</span>
                            <span>{$invoice['post_name'] ?? 'N/A'}</span>
                        </div>
                        <div class=\"detail-row\">
                            <span class=\"label\">Amount:</span>
                            <span class=\"amount\">{$currencySymbol} " . number_format($invoice['total_amount'], 2) . "</span>
                        </div>
                    </div>
                    
                    <p>Please log in to your account to view the complete invoice details and download a PDF copy.</p>
                    <p>If you have any questions about this invoice, please don't hesitate to contact us.</p>
                    
                    <p>Best regards,<br/>SSCI Office Platform</p>
                </div>
                <div class=\"footer\">
                    <p>This is an automated message. Please do not reply to this email.</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }

    /**
     * Send invoice using multiple channels
     */
    public function sendInvoice($invoiceId, $channels = ['email'])
    {
        $results = [];

        foreach ($channels as $channel) {
            switch ($channel) {
                case 'email':
                    $results['email'] = $this->sendViaEmail($invoiceId);
                    break;
                case 'whatsapp':
                    $results['whatsapp'] = $this->sendViaWhatsApp($invoiceId);
                    break;
                case 'notification':
                    $results['notification'] = $this->createInAppNotification($invoiceId);
                    break;
            }
        }

        return $results;
    }
}
