<?php
namespace App\Controllers;

use App\Services\LeadService;

class HomeController 
{
    private $leadService;
    
    public function __construct() 
    {
        global $pdo;
        $this->leadService = new LeadService($pdo);
    }
    
    /**
     * Display the front landing page
     */
    public function index() 
    {
        $hideSidebar = true;
        
        ob_start();
        include APP_ROOT . '/resources/views/pages/landing.php';
        $content = ob_get_clean();
        
        $pageTitle = 'Airunner • AI-Powered Lead Management';
        include APP_ROOT . '/resources/views/layouts/landing.php';
    }
    
    /**
     * Handle landing page form submissions
     */
    public function captureLead() 
    {
        header('Content-Type: application/json');
        
        try {
            $name = trim($_POST['name'] ?? '');
            $email = trim($_POST['email'] ?? '');
            $company = trim($_POST['company'] ?? '');
            
            // Validate required fields
            if (empty($name) || empty($email)) {
                throw new \Exception('Name and email are required');
            }
            
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                throw new \Exception('Please enter a valid email address');
            }
            
            // Prepare lead data
            $leadData = [
                'name' => $name,
                'email' => $email,
                'company' => $company,
                'source' => 'landing_page',
                'ip_address' => $_SERVER['REMOTE_ADDR'] ?? 'Unknown',
                'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown'
            ];
            
            // Store in database
            $result = $this->leadService->captureLandingPageLead($leadData);
            
            // Send email notifications
            $this->sendEmailNotifications($name, $email, $company);
            
            $this->sendJsonResponse(true, 'Thank you! We\'ll be in touch soon. A confirmation has been sent to your email.');
            
        } catch (\Exception $e) {
            error_log("Landing page lead capture error: " . $e->getMessage());
            $this->sendJsonResponse(false, $e->getMessage());
        }
    }
    
    /**
     * Send email notifications to admin and user
     */
    private function sendEmailNotifications(string $name, string $email, string $company): void 
    {
        try {
            // Email to admin
            $this->sendAdminNotification($name, $email, $company);
            
            // Confirmation email to user
            $this->sendUserConfirmation($name, $email, $company);
            
        } catch (\Exception $e) {
            // Log email errors but don't fail the lead capture
            error_log("Email notification error: " . $e->getMessage());
        }
    }
    
    /**
     * Send notification to admin
     */
    private function sendAdminNotification(string $name, string $email, string $company): void 
    {
        $adminEmail = 'admin@yourapp.com'; // Change this to your admin email
        $subject = "🎯 New Lead Captured: {$name}";
        
        $message = "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: linear-gradient(135deg, #7865f3, #6a58d6); color: white; padding: 20px; border-radius: 10px 10px 0 0; }
                .content { background: #f9fafb; padding: 20px; border-radius: 0 0 10px 10px; }
                .lead-detail { background: white; padding: 15px; margin: 10px 0; border-radius: 8px; border-left: 4px solid #7865f3; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>🚀 New Lead Captured!</h1>
                    <p>Someone just signed up on your landing page</p>
                </div>
                <div class='content'>
                    <div class='lead-detail'>
                        <h3>Lead Details:</h3>
                        <p><strong>Name:</strong> {$name}</p>
                        <p><strong>Email:</strong> {$email}</p>
                        <p><strong>Company:</strong> " . ($company ?: 'Not provided') . "</p>
                        <p><strong>Source:</strong> Landing Page</p>
                        <p><strong>Time:</strong> " . date('F j, Y g:i A') . "</p>
                        <p><strong>IP Address:</strong> " . ($_SERVER['REMOTE_ADDR'] ?? 'Unknown') . "</p>
                    </div>
                    
                    <div style='margin-top: 20px; padding: 15px; background: #e8f4fd; border-radius: 8px;'>
                        <h4>Next Steps:</h4>
                        <ul>
                            <li>Add lead to your CRM</li>
                            <li>Send welcome sequence</li>
                            <li>Schedule follow-up</li>
                        </ul>
                    </div>
                    
                    <p style='margin-top: 20px; color: #666;'>
                        <a href='http://localhost/lead-management/public/app/leads' style='color: #7865f3;'>View in Airunner Dashboard</a>
                    </p>
                </div>
            </div>
        </body>
        </html>
        ";
        
        $headers = [
            'MIME-Version: 1.0',
            'Content-type: text/html; charset=utf-8',
            'From: Airunner <noreply@yourapp.com>',
            'Reply-To: ' . $email
        ];
        
        mail($adminEmail, $subject, $message, implode("\r\n", $headers));
    }
    
    /**
     * Send confirmation email to user
     */
    private function sendUserConfirmation(string $name, string $email, string $company): void 
    {
        $subject = "Welcome to Airunner! 🚀";
        
        $firstName = explode(' ', $name)[0]; // Get first name for personalization
        
        $message = "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: linear-gradient(135deg, #7865f3, #6a58d6); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
                .content { background: #f9fafb; padding: 30px; border-radius: 0 0 10px 10px; }
                .cta-button { display: inline-block; background: linear-gradient(135deg, #ffb703, #f97316); color: white; padding: 12px 30px; text-decoration: none; border-radius: 8px; font-weight: bold; margin: 20px 0; }
                .feature { background: white; padding: 15px; margin: 10px 0; border-radius: 8px; border-left: 4px solid #7865f3; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>Welcome to Airunner, {$firstName}! 🎉</h1>
                    <p>Get ready to transform your lead management with AI</p>
                </div>
                <div class='content'>
                    <p>Hi <strong>{$firstName}</strong>,</p>
                    
                    <p>Thank you for your interest in Airunner! We're excited to help you automate your lead management process with AI-powered insights.</p>
                    
                    <div class='feature'>
                        <h3>🚀 What's Next:</h3>
                        <ul>
                            <li>Access your Airunner dashboard</li>
                            <li>Set up your first AI-powered form</li>
                            <li>Start capturing and scoring leads automatically</li>
                            <li>Generate smart email responses with AI</li>
                        </ul>
                    </div>
                    
                    <div style='text-align: center; margin: 30px 0;'>
                        <a href='http://localhost/lead-management/public/app' class='cta-button'>Launch Your Dashboard</a>
                    </div>
                    
                    <div class='feature'>
                        <h3>📞 Need Help?</h3>
                        <p>Our team is here to help you get started:</p>
                        <ul>
                            <li>📧 Email: support@airunner.com</li>
                            <li>🕐 Response time: Usually within 2 hours</li>
                            <li>🎥 <a href='#' style='color: #7865f3;'>Watch getting started guide</a></li>
                        </ul>
                    </div>
                    
                    <p style='color: #666; margin-top: 30px;'>
                        Best regards,<br>
                        <strong>The Airunner Team</strong>
                    </p>
                    
                    <hr style='margin: 30px 0; border: none; border-top: 1px solid #e5e7eb;'>
                    
                    <p style='font-size: 12px; color: #999;'>
                        You're receiving this email because you signed up for Airunner on our landing page.<br>
                        If this wasn't you, please ignore this email.
                    </p>
                </div>
            </div>
        </body>
        </html>
        ";
        
        $headers = [
            'MIME-Version: 1.0',
            'Content-type: text/html; charset=utf-8',
            'From: Airunner <noreply@airunner.com>',
            'Reply-To: support@airunner.com'
        ];
        
        mail($email, $subject, $message, implode("\r\n", $headers));
    }
    
    private function sendJsonResponse(bool $success, string $message, array $data = []) 
    {
        echo json_encode([
            'success' => $success,
            'message' => $message,
            'data' => $data
        ]);
    }
}