<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyName = Branding::companyName();
$companyLogo = Branding::logoUrl();
$companyLogoFile = Branding::logoFilePath();
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/LoanLaybuy.php';
require_once __DIR__ . '/../../vendor/autoload.php';

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

$database = new Database();
$conn = $database->getConnection();

$auth = new Auth($conn);
$loanLaybuy = new LoanLaybuy($conn);

if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}

$recordId = isset($_GET['record_id']) ? (int)$_GET['record_id'] : 0;
$recordData = $loanLaybuy->getLoanLaybuyById($recordId);
if (!$recordData) {
    header('Location: laybuy_and_loans.php?error=' . urlencode('Lay-buy not found.'));
    exit();
}


$creatorId = $recordData['created_by'] ?? null;
$creatorName = 'Unknown';
if ($creatorId) {
    $creatorName = $auth->getUserName($creatorId);
    if (!$creatorName) {
        error_log("Failed to retrieve username for user_id: $creatorId in record ID: $recordId");
        $creatorName = 'Unknown';
    }
}

$dateTime = new DateTime($recordData['created_at']);
$formattedDate = $dateTime->format('Y-m-d');
$validUntil = new DateTime($recordData['valid_until']);
$formattedValidUntil = $validUntil->format('Y-m-d');

$status = (new DateTime() > $validUntil) ? 'expired' : ($recordData['status'] ?? 'pending');

$companyDetails = Branding::documentDetailsForBranchId($conn, (int)($recordData['branch_id'] ?? 0));
$companyName = $companyDetails['name'];
$companyLogo = $companyDetails['logo'];
$companyLogoFile = $companyDetails['logo_file'];


ob_start();
require_once 'generate_loan_laybuy_pdf.php';
$pdfContent = ob_get_clean();


$tempPdfPath = __DIR__ . '/../../temp/LAYBUY_Receipt_' . $recordData['record_id'] . '.pdf';
file_put_contents($tempPdfPath, $pdfContent);


$mail = new PHPMailer(true);
try {

    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your_email@gmail.com';
    $mail->Password = 'your_password';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;


    $mail->setFrom($companyDetails['email'], $companyDetails['name']);
    $mail->addAddress($recordData['customer_email'] ?? $companyDetails['email']);
    $mail->addReplyTo($companyDetails['email'], $companyDetails['name']);


    $mail->addAttachment($tempPdfPath, 'LAYBUY_Receipt_' . $recordData['record_id'] . '.pdf');


    $mail->isHTML(true);
    $mail->Subject = 'LAYBUY Receipt #' . $recordData['record_id'] . ' from ' . $companyName;
    $mail->Body = '
        <h2>LAYBUY Receipt</h2>
        <p>Dear ' . htmlspecialchars($recordData['customer_name']) . ',</p>
        <p>Thank you for your business with ' . htmlspecialchars($companyName) . '. Please find attached the lay-buy receipt for your records.</p>
        <h3>Details:</h3>
        <ul>
            <li><strong>Record #:</strong> ' . htmlspecialchars($recordData['record_id']) . '</li>
            <li><strong>Date:</strong> ' . $formattedDate . '</li>
            <li><strong>Prepared By:</strong> ' . htmlspecialchars($creatorName) . '</li>
            <li><strong>Customer:</strong> ' . htmlspecialchars($recordData['customer_name']) . '</li>
            <li><strong>Contact:</strong> ' . htmlspecialchars($recordData['customer_contact']) . '</li>
            <li><strong>Valid Until:</strong> ' . $formattedValidUntil . '</li>
            <li><strong>Status:</strong> ' . ucfirst($status) . '</li>
        </ul>
        <h3>Item Details:</h3>
        <table border="1" cellpadding="5" style="width:100%; border-collapse: collapse;">
            <tr style="background-color: #f5f5f5;">
                <th>#</th>
                <th>Item Name</th>
                <th>Amount (MWK)</th>
            </tr>
            <tr>
                <td>1</td>
                <td>' . htmlspecialchars($recordData['item_name']) . '</td>
                <td>' . number_format($recordData['amount'], 2) . '</td>
            </tr>
            <tr>
                <td colspan="2" style="text-align: right;"><strong>Total:</strong></td>
                <td><strong>MWK ' . number_format($recordData['amount'], 2) . '</strong></td>
            </tr>
        </table>
        <h3>Notes:</h3>
        <p>' . htmlspecialchars($recordData['notes'] ?? 'No additional notes provided.') . '</p>
        <p><em>This lay-buy is valid until ' . $formattedValidUntil . '.</em></p>
        <p>Best regards,<br>' . htmlspecialchars($companyName) . ' Team<br>' . htmlspecialchars($companyDetails['phone']) . '<br>' . htmlspecialchars($companyDetails['email']) . '</p>';

    $mail->send();


    unlink($tempPdfPath);

    header('Location: laybuy_and_loans.php?success=' . urlencode('LAYBUY receipt sent successfully.'));
} catch (Exception $e) {

    if (file_exists($tempPdfPath)) {
        unlink($tempPdfPath);
    }
    header('Location: laybuy_and_loans.php?error=' . urlencode('Failed to send email: ' . $mail->ErrorInfo));
}
exit();
?>
