<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyName = Branding::companyName();
$companyLogo = Branding::logoUrl();
$companyLogoFile = Branding::logoFilePath();
$settings = Branding::settings();
$vatPercentage = (float)$settings['vat_percentage'];
$vatRate = $vatPercentage / 100;
$profitPercentage = (float)$settings['profit_percentage'];
$profitRate = $profitPercentage / 100;
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Quotation.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../vendor/tecnickcom/tcpdf/tcpdf.php';

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

$auth = new Auth($conn);
$quotation = new Quotation($conn);
$branch = new Branch($conn);

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

$quotationId = isset($_GET['quotation_id']) ? (int)$_GET['quotation_id'] : 0;
$quotationData = $quotation->getQuotationById($quotationId);
if (!$quotationData) {
    header('Location: create_quotation.php?error=' . urlencode('Quotation not found.'));
    exit();
}


$creatorId = $quotationData['created_by'] ?? null;
$creatorName = 'Unknown';
if ($creatorId) {
    $creatorName = $auth->getUserName($creatorId);
    if (!$creatorName) {
        error_log("Failed to retrieve username for user_id: $creatorId in quotation ID: $quotationId");
        $creatorName = 'Unknown';
    }
} else {
    error_log("No created_by field found for quotation ID: $quotationId");
}

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

$documentBranch = $branch->getBranchById((int)($quotationData['branch_id'] ?? 0)) ?: [];
$companyDetails = Branding::documentDetailsForBranch($documentBranch);
$companyDetails['contact_line'] = Branding::contactLine($companyDetails);


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, 'QUOTATION', 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['contact_line'], 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['contact_line'] . ' 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('Quotation ' . $quotationData['quotation_number']);
$pdf->SetSubject('Quotation');
$pdf->SetKeywords('Quotation, ' . $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>Quotation #:</strong> ' . htmlspecialchars($quotationData['quotation_number']) . '</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($quotationData['customer_name']) . '</p>
            <p><strong>Contact:</strong> ' . htmlspecialchars($quotationData['customer_contact']) . '</p>
            <p><strong>Valid Until:</strong> ' . $formattedValidUntil . '</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: 40%; text-align: center;">Item Name</th>
        <th style="width: 15%; text-align: center;">Quantity</th>
        <th style="width: 20%; text-align: center;">Unit Price (MWK)</th>
        <th style="width: 15%; text-align: center;">Total (MWK)</th>
    </tr>';

$items = $quotationData['items'];
foreach ($items as $index => $item) {
    $itemTotal = $item['quantity'] * $item['unit_price'];
    $html .= '
    <tr>
        <td style="text-align: center;">' . ($index + 1) . '</td>
        <td>' . htmlspecialchars($item['item_name']) . '</td>
        <td style="text-align: center;">' . htmlspecialchars($item['quantity']) . '</td>
        <td style="text-align: right;">' . number_format($item['unit_price'], 2) . '</td>
        <td style="text-align: right;">' . number_format($itemTotal, 2) . '</td>
    </tr>';
}

$html .= '
    <tr>
        <td colspan="4" style="text-align: right;"><strong>Subtotal:</strong></td>
        <td style="text-align: right;">MWK ' . number_format($quotationData['subtotal'], 2) . '</td>
    </tr>
    <tr>
        <td colspan="4" style="text-align: right;"><strong>VAT (' . htmlspecialchars(number_format($vatPercentage, 2)) . '%):</strong></td>
        <td style="text-align: right;">MWK ' . number_format($quotationData['surtax'], 2) . '</td>
    </tr>
    <tr>
        <td colspan="4" style="text-align: right;"><strong>Grand Total:</strong></td>
        <td style="text-align: right;"><strong>MWK ' . number_format($quotationData['total_amount'], 2) . '</strong></td>
    </tr>
</table>';


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

$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output('Quotation_' . $quotationData['quotation_number'] . '.pdf', 'I');
?>
