<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require __DIR__.'/phpmailer/autoload.php';
require_once __DIR__.'/tcpdf/tcpdf.php';  // Ensure TCPDF is in the correct folder

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

error_reporting(E_ALL);
ini_set('display_errors', 0);

// force JSON output on error
set_exception_handler(function ($e) {
    echo json_encode(['error' => 'Exception: '.$e->getMessage()]);
    exit;
});
set_error_handler(function ($severity, $message, $file, $line) {
    echo json_encode(['error' => "PHP Error: $message in $file line $line"]);
    exit;
});

$action = $_POST['action'] ?? '';

try {
    switch ($action) {
        case 'save_config':
            $_SESSION['mailer_config'] = [
                'from_name'    => $_POST['from_name'] ?? '',
                'from_email'   => $_POST['from_email'] ?? '',
                'bounce_email' => $_POST['bounce_email'] ?? '',
                'subject'      => $_POST['subject'] ?? '',
                'message'      => $_POST['message'] ?? '',
                'email_list'   => preg_split('/\r\n|\r|\n/', trim($_POST['email_list'] ?? '')),
                'smtp_host'    => $_POST['smtp_host'] ?? '',
                'smtp_user'    => $_POST['smtp_user'] ?? '',
                'smtp_pass'    => $_POST['smtp_pass'] ?? '',
                'smtp_port'    => $_POST['smtp_port'] ?? '',
                'smtp_secure'  => $_POST['smtp_secure'] ?? ''
            ];
            $_SESSION['status'] = [
                'status'=>'idle',
                'queue_length'=>count($_SESSION['mailer_config']['email_list']),
                'current_index'=>0,
                'sent_count'=>0,
                'failed_count'=>0,
                'sent_emails'=>[],
                'failed_emails'=>[]
            ];
            echo json_encode($_SESSION['status']);
            break;

        case 'get_status':
            echo json_encode($_SESSION['status'] ?? []);
            break;

        case 'start_sending':
            $_SESSION['status']['status'] = 'running';
            echo json_encode($_SESSION['status']);
            break;

        case 'process_batch':
            $cfg = $_SESSION['mailer_config'] ?? [];
            $st  =& $_SESSION['status'];
            $emails = $cfg['email_list'] ?? [];

            $processed = 0;

            if ($st['current_index'] < count($emails)) {
                $recipient = trim($emails[$st['current_index']]);
                if ($recipient) {
                    // Generate personalized PDF for this recipient
                    $pdfFilePath = generatePDF($recipient, $cfg);
                    $pdfFileName = basename($pdfFilePath);  // Get file name

                    // Apply tags after generating PDF, including {pdf_filename}
                    $subjectWithTags = applyTags($cfg['subject'], $recipient, $cfg, $pdfFileName);
                    $messageWithTags = applyTags($cfg['message'], $recipient, $cfg, $pdfFileName);

                    $ok = sendEmail(
                        $cfg['from_email'],
                        $cfg['from_name'],
                        $recipient,
                        $subjectWithTags,
                        $messageWithTags,
                        $cfg,
                        $pdfFilePath,
                        $pdfFileName
                    );

                    if ($ok) {
                        $st['sent_count']++;
                        $st['sent_emails'][] = [
                            'email'=>$recipient,
                            'subject'=>$subjectWithTags,
                            'timestamp'=>time()
                        ];
                    } else {
                        $st['failed_count']++;
                        $st['failed_emails'][$recipient] = [
                            'subject'=>$subjectWithTags,
                            'attempts'=>($st['failed_emails'][$recipient]['attempts']??0)+1,
                            'last_attempt'=>time()
                        ];
                    }
                    $processed++;
                }
                $st['current_index']++;

                // 🚦 enforce delay of 5 seconds
                sleep(5);
            }

            if ($st['current_index'] >= count($emails)) {
                $st['status'] = 'idle';
            }

            $st['processed'] = $processed;
            echo json_encode($st);
            break;

        case 'pause_sending':
            $_SESSION['status']['status'] = 'paused';
            echo json_encode($_SESSION['status']);
            break;

        case 'resume_sending':
            $_SESSION['status']['status'] = 'running';
            echo json_encode($_SESSION['status']);
            break;

        case 'stop_sending':
            $_SESSION['status']['status'] = 'idle';
            echo json_encode($_SESSION['status']);
            break;

        case 'reset_counters':
            $_SESSION['status']['sent_count'] = 0; 
            $_SESSION['status']['failed_count'] = 0;
            $_SESSION['status']['sent_emails'] = []; 
            $_SESSION['status']['failed_emails'] = [];
            $_SESSION['status']['current_index'] = 0;
            echo json_encode($_SESSION['status']);
            break;

        case 'retry_failed':
            $retry = array_keys($_SESSION['status']['failed_emails'] ?? []);
            $_SESSION['mailer_config']['email_list'] = array_merge($_SESSION['mailer_config']['email_list'] ?? [], $retry);
            $_SESSION['status']['queue_length'] = count($_SESSION['mailer_config']['email_list']);
            $_SESSION['status']['failed_emails'] = [];
            echo json_encode($_SESSION['status']);
            break;

        default:
            echo json_encode(['error'=>'Unknown action']);
    }
} catch (Exception $e) {
    echo json_encode(['error' => 'Caught exception: '.$e->getMessage()]);
}

// ========= Email Sender ========== 
function sendEmail($from, $name, $to, $subj, $body, $cfg = [], $pdfFilePath = null, $pdfFileName = '') {
    $mail = new PHPMailer(true);
    try {
        if (!empty($cfg['smtp_host']) && !empty($cfg['smtp_user'])) {
            $mail->isSMTP();
            $mail->Host = $cfg['smtp_host'];
            $mail->SMTPAuth = true;
            $mail->Username = $cfg['smtp_user'];
            $mail->Password = $cfg['smtp_pass'];
            $mail->Port     = $cfg['smtp_port'] ?: 587;
            if (!empty($cfg['smtp_secure']) && $cfg['smtp_secure'] !== 'none') {
                $mail->SMTPSecure = ($cfg['smtp_secure'] === 'ssl')
                    ? PHPMailer::ENCRYPTION_SMTPS
                    : PHPMailer::ENCRYPTION_STARTTLS;
            }
        } else {
            $mail->isMail();
        }

        $mail->setFrom($from, $name);
        $mail->addAddress($to);
        if (!empty($cfg['bounce_email'])) $mail->Sender = $cfg['bounce_email'];

        $mail->CharSet  = 'UTF-8';
        $mail->Encoding = 'base64';

        $mail->isHTML(true);
        $mail->Subject = $subj;
        $mail->Body    = $body;
        $mail->AltBody = strip_tags(preg_replace('/<br\s*\/?>/i', "\n", $body));

        // Attach PDF if provided
        if ($pdfFilePath && file_exists($pdfFilePath)) {
            $mail->addAttachment($pdfFilePath, $pdfFileName);
        }

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Mailer Error to {$to}: " . $mail->ErrorInfo);
        return false;
    }
}

// ========= Tag Engine ==========
function applyTags($text, $recipient, $config, $pdfFileName = '') {
    $parts = explode('@', $recipient);
    $username = $parts[0] ?? '';
    $domain   = $parts[1] ?? '';

    $usernameParts = preg_split('/[._]/', $username);
    $firstName = ucfirst($usernameParts[0] ?? '');
    $lastName  = ucfirst(end($usernameParts));

    $tags = [
        '{email}'        => $recipient,
        '{username}'     => $username,
        '{domain}'       => $domain,
        '{first_name}'   => $firstName,
        '{last_name}'    => $lastName,
        '{from_name}'    => $config['from_name'] ?? '',
        '{timestamp}'    => time(),
        '{date}'         => date('Y-m-d'),
        '{pdf_filename}' => $pdfFileName,  // Now this works
    ];

    return strtr($text, $tags);
}

// ========= PDF Generation ==========
function generatePDF($recipient, $config) {
    // Get first and last names
    $user = explode('@', $recipient)[0];
    $usernameParts = preg_split('/[._]/', $user);
    $firstName = ucfirst($usernameParts[0] ?? 'Customer');
    $lastName = ucfirst(end($usernameParts));

    // Setup the directory to save PDFs
    $saveDir = __DIR__ . "/pdfs/";
    if (!is_dir($saveDir)) {
        mkdir($saveDir, 0777, true);
    }

    // Generate PDF file path and name
    $fileName = "Document_{$firstName}_{$lastName}.pdf";
    $filePath = $saveDir . $fileName;

    // Create PDF
    $pdf = new TCPDF();
    $pdf->AddPage();
    $pdf->SetFont('helvetica', '', 12);
    $pdf->Write(0, "Hello $firstName $lastName,\n\nThank you for being a valued customer!");
    $pdf->Output($filePath, 'F');  // Save to file

    return $filePath;
}
