<?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/tecnickcom/tcpdf/tcpdf.php';

$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';
    }
} else {
    error_log("No created_by field found for record ID: $recordId");
}

$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'];


class MYPDF extends TCPDF {
    public $companyDetails;

    public function __construct($companyDetails, $orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding='UTF-8', $diskcache=false, $pdfa=false) {
        parent::__construct($orientation, $unit, $format, $unicode, $encoding, $diskcache, $pdfa);
        $this->companyDetails = $companyDetails;
    }

    public function Header() {
        $logoPath = $this->companyDetails['logo_file'] ?? null;

        if ($logoPath && file_exists($logoPath)) {
            $logoWidth = 30;
            $pageWidth = $this->getPageWidth();
            $logoX = ($pageWidth - $logoWidth) / 2;
            $this->Image($logoPath, $logoX, 8, $logoWidth, 0, '', '', '', false, 300, '', false, false, 0, false, false, false);
            $this->SetY(30);
        } else {
            $this->SetY(15);
        }

        $this->SetFont('helvetica', 'B', 14);
        $this->Cell(0, 6, 'LAYBUY RECEIPT', 0, 1, 'C');
        $this->Ln(1);

        $this->SetFont('helvetica', 'B', 11);
        $this->Cell(0, 5, $this->companyDetails['name'], 0, 1, 'C');
        $this->Ln(1);

        $this->SetFont('helvetica', '', 9);
        $this->Cell(0, 4, $this->companyDetails['address'], 0, 1, 'C');
        $this->Cell(0, 4, $this->companyDetails['phone'], 0, 1, 'C');
        $this->Cell(0, 4, 'Email: ' . $this->companyDetails['email'] . ' | Web: ' . $this->companyDetails['website'], 0, 1, 'C');

        $this->SetFont('helvetica', '', 8);
        $this->MultiCell(0, 3, $this->companyDetails['tagline'], 0, 'C');
        $this->Ln(15);
    }

    public function Footer() {
        $this->SetY(-30);
        $this->SetFont('helvetica', 'I', 8);
        $this->MultiCell(0, 5, 'Thank you for your business! Please contact us at ' . $this->companyDetails['phone'] . ' for any inquiries.', 0, 'C');
        $this->Cell(0, 10, 'Page ' . $this->getPageNumGroupAlias() . '/' . $this->getPageGroupAlias(), 0, 0, 'C');
    }
}

$pdf = new MYPDF($companyDetails, PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor($companyName);
$pdf->SetTitle('Laybuy Receipt ' . $recordData['record_id']);
$pdf->SetSubject('Laybuy Receipt');
$pdf->SetKeywords('Laybuy, Receipt, ' . $companyName);

$pdf->setPrintHeader(true);
$pdf->setPrintFooter(true);

$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetMargins(10, 60, 10);
$pdf->SetHeaderMargin(5);
$pdf->SetFooterMargin(30);
$pdf->SetAutoPageBreak(TRUE, 30);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->setFontSubsetting(true);

$pdf->SetFont('helvetica', '', 10);
$pdf->AddPage();


$html = '
<table style="width: 100%; margin-bottom: 20px;" cellpadding="5">
    <tr>
        <td style="width: 50%; vertical-align: top;">
            <p><strong>Record #:</strong> ' . htmlspecialchars($recordData['record_id']) . '</p>
            <p><strong>Date:</strong> ' . $formattedDate . '</p>
            <p><strong>Prepared By:</strong> ' . htmlspecialchars($creatorName) . '</p>
        </td>
        <td style="width: 50%; vertical-align: top;">
            <p><strong>Customer:</strong> ' . htmlspecialchars($recordData['customer_name']) . '</p>
            <p><strong>Contact:</strong> ' . htmlspecialchars($recordData['customer_contact']) . '</p>
            <p><strong>Valid Until:</strong> ' . $formattedValidUntil . '</p>
            <p><strong>Status:</strong> ' . ucfirst($status) . '</p>
        </td>
    </tr>
</table>';


$html .= '
<table border="1" cellpadding="5" style="width: 100%; border-collapse: collapse;">
    <tr style="background-color: #f5f5f5;">
        <th style="width: 10%; text-align: center;">#</th>
        <th style="width: 60%; text-align: center;">Item Name</th>
        <th style="width: 30%; text-align: center;">Amount (MWK)</th>
    </tr>
    <tr>
        <td style="text-align: center;">1</td>
        <td>' . htmlspecialchars($recordData['item_name']) . '</td>
        <td style="text-align: right;">' . number_format($recordData['amount'], 2) . '</td>
    </tr>
    <tr>
        <td colspan="2" style="text-align: right;"><strong>Total:</strong></td>
        <td style="text-align: right;"><strong>MWK ' . number_format($recordData['amount'], 2) . '</strong></td>
    </tr>
</table>';


$html .= '
<div style="margin-top: 20px;">
    <h4>Notes:</h4>
    <p>' . htmlspecialchars($recordData['notes'] ?? 'No additional notes provided.') . '</p>
</div>
<div style="margin-top: 20px; font-style: italic;">
    <p>This lay-buy is valid until ' . $formattedValidUntil . '.</p>
</div>';

$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output('LAYBUY_Receipt_' . $recordData['record_id'] . '.pdf', 'I');
?>
