<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

require_once 'connect.php';
require __DIR__ . '/../vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

$WEBSITE_URL = 'https://digifunzi.com';
function getFirstWords($content, $wordCount = 100)
{

    $plainText = strip_tags($content);

    $words = preg_split('/\s+/', $plainText);

    $firstWords = array_slice($words, 0, $wordCount);
    return implode(' ', $firstWords) . '...';
}

try {
    $conn = getDatabaseConnection();
    $input = json_decode(file_get_contents('php://input'), true);

    if (!isset($input['blog_id'])) {
        throw new Exception('Blog ID is required');
    }

    $blogId = (int) $input['blog_id'];
    $customMessage = $input['custom_message'] ?? '';

    $conn->beginTransaction();

    try {
        $stmt = $conn->prepare("
    SELECT b.id, b.title, b.slug, b.content, b.cover_image, b.created_at, c.name AS category_name
    FROM blogs b
    LEFT JOIN categories c ON b.category = c.id
    WHERE b.id = ?
");

        $stmt->execute([$blogId]);
        $blog = $stmt->fetch();

        if (!$blog) {
            throw new Exception("Blog post not found (ID: $blogId)");
        }
        $excerpt = getFirstWords($blog['content'], 100);
        $subject = "{$blog['title']}";
        $message = $customMessage;


        $stmt = $conn->prepare(
            'INSERT INTO notifications (blog_id, subject, message) VALUES (?, ?, ?)'
        );
        $stmt->execute([$blogId, $subject, $message]);
        $notificationId = $conn->lastInsertId();

        $stmt = $conn->prepare(
            'SELECT id, email FROM subscribers WHERE is_active = 1'
        );
        $stmt->execute();
        $subscribers = $stmt->fetchAll();

        if (empty($subscribers)) {
            throw new Exception('No active subscribers found');
        }

        $sentCount = 0;
        $failedEmails = [];
        $stmt = $conn->prepare("INSERT INTO notification_recipients (notification_id, subscriber_id, sent_status) VALUES (?, ?, ?)");


        foreach ($subscribers as $subscriber) {
            try {
                $mail = new PHPMailer(true);

                // Server settings
                $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
                $mail->isSMTP(); // Send using SMTP
                $mail->Host = 'digifunzi.com'; // Set the SMTP server to send through
                $mail->SMTPAuth = true; // Enable SMTP authentication
                $mail->Username = 'support@digifunzi.com'; // SMTP username
                $mail->Password = 'ZS4nGyfzf(aj'; // SMTP password
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // Enable implicit TLS encryption
                $mail->Port = 465;
                $email = trim($subscriber['email']);
                $mail->addAddress($email);

                // TCP port to connect to

                // Recipients
                $mail->setFrom('support@digifunzi.com', 'Digifunzi');
                $mail->addReplyTo('support@digifunzi.com', 'Information');

                // Content
                $mail->isHTML(true);
                $mail->Subject = $subject;

                $mail->Body = <<<EOD

                    <!DOCTYPE html>
                <html>
                <head>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                        <meta name="viewport" content="width=device-width, initial-scale=1">
                        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
                         <meta name="keywords" content="Digifunzi, digital skills education, robotics for kids, AI for kids, coding for kids, STEM education, digital literacy programs, future skills for children, school technology programs, learn robotics AI coding, {$categoryName}, {$blog['title']}" />
                        <meta name="description" content="{$excerpt}" />
                        <link href="https://fonts.googleapis.com/css2?family=Comfortaa:wght@300;400;500;700&display=swap" rel="stylesheet">

                                     <style>
                                    body { font-family: Comfortaa; margin:0; padding:0; background:#f9f9f9; }
                                    .container { max-width:650px; margin:0 auto; padding:20px; }
                                    .card { background:#fff; border:1px solid #C0C0C0; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.1); padding:12px; }
                                    .blog-title { font-family: Comfortaa; font-size:24px; color:#000; margin:12px 0 10px; }
                                    .excerpt { font-size:14px; line-height:1.6; color:#444; margin-bottom:20px; font-family: Comfortaa;}
                                    .button {
                                        display:inline-block; padding:12px 24px; background:#38aae1; color:#fff !important;
                                        text-decoration:none; border-radius:4px; font-weight:bold;
                                    }
                                    .blog-header { background:#38aae1; border-radius:8px; color:#fff; padding:10px 10px; text-align:center; }
                                    .footer { margin-top:30px; padding-top:20px; border-top:1px solid #eee; font-size:12px; color:#777; text-align:center; }
                                    .logo {
                                        width: 200px;
                                        height: 80px;
                                        margin: 10px auto;
                                        display: block;
                                        object-fit: contain;          
                                        max-width: 100%;             
                                        }
                                                                        
                                        @media (max-width:600px){
                                        .blog-title{font-size:20px;}
                                        .cover-img{max-height:200px;}
                                    }
                                </style>
                                                                
                </head>
                <body>
                <div class="container">
                    <div class="card">
                        <div class="blog-header">
                            <h2>We are Excited to Share with you our new blog!</h2>
                        </div>
                        <h3 class="blog-title">{$blog['title']}</h3>
                        
                        <div class="excerpt">
                            {$excerpt}
                        </div>
                        <p style="text-align:center;">
                            <a href="{$WEBSITE_URL}/blog/{$blog['slug']}" class="button">Read Full Article</a>
                        </p>

                    </div>
                                <div class="footer">
                                    <p>You received this email because you subscribed to DigiFunzi updates</p>
                                    <p><a href="{$WEBSITE_URL}/unsubscribe/{$subscriber['id']}">Unsubscribe</a></p>
                                    <img src="https://app.digifunzi.com/assets/images/digifunzi-web-banner.png" alt="DigiFunzi" class="logo">
                                    <div class="social-links">
                                        <a href="https://www.facebook.com/digifunzi">Facebook</a> |
                                        <a href="https://www.linkedin.com/company/digifunzi/">LinkedIn</a> |
                                        <a href="https://www.instagram.com/digifunzi/">Instagram</a>
                                    </div>
                                    <p>© 2025 DigiFunzi. All rights reserved.</p>
                                </div>
                            </div>
                        </body>
                </html>
                EOD;

                $mail->SMTPDebug = 0;
                $mail->send();
                $sentCount++;
            } catch (Exception $e) {
                $failedEmails[] = [
                    'email' => $subscriber['email'],
                    'error' => $mail->ErrorInfo,
                ];
            }
        }

        $conn->commit();

        echo json_encode([
            'success' => true,
            'message' => 'Newsletter sent successfully',
            'notification_id' => $notificationId,
            'recipient_count' => count($subscribers),
            'sent_count' => $sentCount,
            'failed_count' => count($failedEmails),
            'failed_emails' => $failedEmails,
            'blog_title' => $blog['title'],
        ]);
    } catch (Exception $e) {
        $conn->rollBack();
        throw $e;
    }
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage(),
    ]);
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
