<?php
require_once __DIR__ . '/daily_report_pdf.php';

/*
|--------------------------------------------------------------------------
| Load PHPMailer if available
|--------------------------------------------------------------------------
*/
$vendorAutoload = __DIR__ . '/vendor/autoload.php';
if (file_exists($vendorAutoload)) {
    require_once $vendorAutoload;
}

function sendDailyReportMail($date = null) {
    global $conn;

    $date = $date ?: date('Y-m-d');
    $pdfPath = generateDailyReportPdf($date, 'F');
    $recipients = getAdminReportRecipients($conn);

    if (empty($recipients)) {
        return [
            'status' => false,
            'message' => 'No Admin recipients found in user table.'
        ];
    }

    $subject = 'KSP Daily Report - ' . reportDisplayDate($date);
    $body = "Dear Admin,\n\nPlease find attached the daily bunisess report.\n\nDate: " . reportDisplayDate($date) . "\n\nGenerated by KSP System.\n\nRegards,\nKrushi Sewa Piyasa";

    /*
    |--------------------------------------------------------------------------
    | Try PHPMailer first if available
    |--------------------------------------------------------------------------
    */
    if (class_exists('\PHPMailer\PHPMailer\PHPMailer')) {
        try {
            $mail = new \PHPMailer\PHPMailer\PHPMailer(true);

            if (SMTP_PASSWORD !== '') {
                $mail->isSMTP();
                $mail->Host = SMTP_HOST;
                $mail->SMTPAuth = true;
                $mail->Username = SMTP_USERNAME;
                $mail->Password = SMTP_PASSWORD;
                $mail->Port = SMTP_PORT;

                if (SMTP_SECURE !== '') {
                    $mail->SMTPSecure = SMTP_SECURE;
                }
            } else {
                $mail->isMail();
            }

            $mail->setFrom(REPORT_FROM_EMAIL, REPORT_FROM_NAME);

            foreach ($recipients as $email) {
                $mail->addAddress($email);
            }

            $mail->Subject = $subject;
            $mail->Body = $body;
            $mail->isHTML(false);
            $mail->addAttachment($pdfPath, basename($pdfPath));
            $mail->send();

            return [
                'status' => true,
                'message' => 'Daily report sent successfully with PHPMailer.',
                'file' => $pdfPath,
                'recipients' => $recipients
            ];
        } catch (Exception $e) {
            // Continue to fallback below
        }
    }

    /*
    |--------------------------------------------------------------------------
    | Fallback to PHP mail()
    |--------------------------------------------------------------------------
    */
    $separator = md5((string)time());
    $filename = basename($pdfPath);
    $pdfContent = chunk_split(base64_encode(file_get_contents($pdfPath)));

    $headers = "From: " . REPORT_FROM_NAME . " <" . REPORT_FROM_EMAIL . ">\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"";

    $message = "--" . $separator . "\r\n";
    $message .= "Content-Type: text/plain; charset=\"utf-8\"\r\n";
    $message .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $message .= $body . "\r\n";

    $message .= "--" . $separator . "\r\n";
    $message .= "Content-Type: application/pdf; name=\"" . $filename . "\"\r\n";
    $message .= "Content-Transfer-Encoding: base64\r\n";
    $message .= "Content-Disposition: attachment; filename=\"" . $filename . "\"\r\n\r\n";
    $message .= $pdfContent . "\r\n";
    $message .= "--" . $separator . "--";

    $success = mail(implode(',', $recipients), $subject, $message, $headers);

    return [
        'status' => $success,
        'message' => $success ? 'Daily report sent successfully with PHP mail().' : 'Failed to send report email.',
        'file' => $pdfPath,
        'recipients' => $recipients
    ];
}

if (php_sapi_name() !== 'cli') {
    $result = sendDailyReportMail(date('Y-m-d'));
    header('Content-Type: text/plain; charset=utf-8');
    echo $result['message'];
}
?>