<?php
session_start();
require '../includes/config.php';
require '../pdf/invoice-pdf-generator.php';

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

require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';


/* =========================
   SESSION VALIDATION
========================= */
if (!isset($_SESSION['company_id'])) {
    echo "
        <script>
            alert('Company context missing. Please re-login.');
            window.location.href = '../invoice-list.php';
        </script>
        ";
    exit;
}

$company_id = (int) $_SESSION['company_id'];
$sender_email = $_SESSION['email'];


/* =========================
   INPUT
========================= */
$invoice   = trim($_POST['invoice'] ?? '');
$emailsRaw = trim($_POST['emails'] ?? '');

if ($invoice === '' || $emailsRaw === '') {
           	echo "
        <script>
            alert('Missing Data');
            window.location.href = '../sign-in.php';
        </script>
        ";
    exit;
}

/* =========================
       FETCH COMPANY
    ========================== */
    $stmt = $mysqli->prepare("
        SELECT *
        FROM company
        WHERE id = ?
        LIMIT 1
    ");
    $stmt->bind_param("i", $company_id);
    $stmt->execute();
    $company = $stmt->get_result()->fetch_assoc();

    if (!$company) {
        throw new Exception("Company not found");
    }
$invoice_prefix = htmlspecialchars($company['invoice_prefix']);
$sender_email_manager = $company['company_email'];

/* =========================
   PARSE EMAILS
========================= */
$emails = array_filter(array_map('trim', explode(',', $emailsRaw)));

if (empty($emails)) {
           	echo "
        <script>
            alert('Invalid Email list');
            window.location.href = '../invoice-list.php';
        </script>
        ";
    exit;
}

/* =========================
   DB CONNECTION
========================= */
$mysqli = new mysqli(
    DATABASE_HOST,
    DATABASE_USER,
    DATABASE_PASS,
    DATABASE_NAME
);

if ($mysqli->connect_error) {
    die('Database connection failed');
}

/* =========================
   FETCH COMPANY NAME
========================= */
$stmt = $mysqli->prepare("
    SELECT company_name
    FROM company
    WHERE id = ?
    LIMIT 1
");
$stmt->bind_param("i", $company_id);
$stmt->execute();
$company = $stmt->get_result()->fetch_assoc();

$companyName = $company['company_name'];




/* =========================
   GENERATE PDF (NO HTTP)
========================= */
try {

    $pdfData = generateInvoicePdf(
        $mysqli,
        $company_id,
        $invoice
    );

} catch (Throwable $e) {
    die("Failed to generate invoice PDF");
}

$mysqli->close();

/* =========================
   SEND EMAIL
========================= */
$mail = new PHPMailer(true);

try {

    $mail->isSMTP();
    $mail->Host       = 'smtppro.zoho.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'docsupport@docadvisory.com';
    $mail->Password   = 'DegitechSolutions@2025';
    $mail->SMTPSecure = 'ssl';
    $mail->Port       = 465;

    $mail->setFrom(
        'docsupport@docadvisory.com',
        $companyName
    );
    $mail->addReplyTo($sender_email, $companyName);
    $mail->addReplyTo($sender_email_manager, $companyName);

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

    $mail->isHTML(true);
$mail->Subject = "New Invoice from {$companyName} (Invoice {$invoice_prefix}-{$invoice})";

$mail->Body = '
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>New Invoice</title>
</head>

<body style="
    margin:0;
    padding:0;
    background-color:#f4f6f8;
    font-family: Arial, Helvetica, sans-serif;
">

<table width="100%" cellpadding="0" cellspacing="0" style="background-color:#f4f6f8; padding:20px 0;">
<tr>
<td align="center">

    <table width="600" cellpadding="0" cellspacing="0" style="
        background:#ffffff;
        border-radius:6px;
        overflow:hidden;
        box-shadow:0 2px 8px rgba(0,0,0,0.05);
    ">

        <!-- HEADER -->
        <tr>
            <td style="
                background:#0f172a;
                color:#ffffff;
                padding:20px;
                text-align:center;
                font-size:20px;
                font-weight:bold;
            ">
                New Invoice
            </td>
        </tr>

        <!-- BODY -->
        <tr>
            <td style="padding:30px; color:#333333; font-size:14px; line-height:1.7;">

                <p style="margin-top:0;">Hello,</p>

                <p>
                    You have received a new invoice from
                    <strong>'.$companyName.'</strong>.
                </p>

                <table width="100%" cellpadding="0" cellspacing="0" style="
                    margin:20px 0;
                    border:1px solid #e5e7eb;
                    border-radius:4px;
                ">
                    <tr>
                        <td style="
                            padding:12px;
                            background:#f9fafb;
                            font-weight:bold;
                            width:40%;
                        ">
                            Invoice Number
                        </td>
                        <td style="padding:12px;">
                            '.$invoice_prefix.'-'.$invoice.'
                        </td>
                    </tr>
                </table>

                <p>
                    The invoice is attached to this email as a PDF document.
                    Please review it at your convenience.
                </p>

                <p>
                    If you have any questions regarding this invoice,
                    feel free to contact us.
                </p>

                <p style="margin-bottom:0;">
                    Kind regards,<br>
                    <strong>'.$companyName.'</strong>
                </p>

            </td>
        </tr>

        <!-- FOOTER -->
        <tr>
            <td style="
                background:#f9fafb;
                color:#6b7280;
                padding:15px;
                text-align:center;
                font-size:12px;
            ">
                This invoice was generated automatically by '.$companyName.' using <br>invoice360.ng
            </td>
        </tr>

    </table>

</td>
</tr>
</table>

</body>
</html>
';


    $mail->addStringAttachment(
        $pdfData,
        "Invoice-{$invoice_prefix}-{$invoice}.pdf",
        'base64',
        'application/pdf'
    );

    $mail->send();

    echo "<script>
        alert('Invoice sent successfully!');
        window.location.href = '../invoice-view.php?id={$invoice}';
    </script>";

} catch (Exception $e) {
    die("Email failed: " . $mail->ErrorInfo);
}
