<?php
session_start();
include_once('../includes/config.php');

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

$invoiceNumber = isset($_GET['invoice']) ? mysqli_real_escape_string($con, $_GET['invoice']) : '';
if ($invoiceNumber === '') {
    die('Invalid invoice number');
}

$autoprint = isset($_GET['autoprint']) && $_GET['autoprint'] === '1' ? '1' : '0';

// Determine sales type for template selection
$saleTypeQuery = "SELECT SalesType FROM tblsales WHERE InvoiceNumber = '$invoiceNumber' LIMIT 1";
$saleTypeResult = mysqli_query($con, $saleTypeQuery);

if (!$saleTypeResult || mysqli_num_rows($saleTypeResult) === 0) {
    die('Invoice not found: ' . htmlspecialchars($invoiceNumber));
}

$saleRow = mysqli_fetch_assoc($saleTypeResult);
$salesType = isset($saleRow['SalesType']) ? strtoupper(trim($saleRow['SalesType'])) : '';
$salesTypeKey = str_replace([' ', '-', '_'], '', $salesType);
$isNonGstSale = strpos($salesTypeKey, 'NONGST') !== false;

$defaultGstTemplate = 'sale-invoice-template1.php';
$defaultNonGstTemplate = 'nongst-sale-invoice-template1.php';
$gstTemplate = $defaultGstTemplate;
$nonGstTemplate = $defaultNonGstTemplate;

$templateQuery = "SELECT GstInvoiceTemplate, NonGstInvoiceTemplate FROM tblinvoice_settings WHERE StoreCode = 'ST0002' LIMIT 1";
$templateResult = mysqli_query($con, $templateQuery);

if ($templateResult && mysqli_num_rows($templateResult) > 0) {
    $templateData = mysqli_fetch_assoc($templateResult);
    if (!empty($templateData['GstInvoiceTemplate'])) {
        $gstTemplate = basename($templateData['GstInvoiceTemplate']);
    }
    if (!empty($templateData['NonGstInvoiceTemplate'])) {
        $nonGstTemplate = basename($templateData['NonGstInvoiceTemplate']);
    }
} else {
    // Fallback for legacy installations where migration is pending
    $legacyQuery = "SELECT InvoiceTemplate FROM tblinvoice_settings WHERE StoreCode = 'ST0002' LIMIT 1";
    $legacyResult = mysqli_query($con, $legacyQuery);
    if ($legacyResult && mysqli_num_rows($legacyResult) > 0) {
        $legacyData = mysqli_fetch_assoc($legacyResult);
        if (!empty($legacyData['InvoiceTemplate'])) {
            $gstTemplate = basename($legacyData['InvoiceTemplate']);
        }
    }
}

$allowedPattern = '/^[a-z0-9\-]+\.php$/i';
if (!preg_match($allowedPattern, $gstTemplate)) {
    $gstTemplate = $defaultGstTemplate;
}
if (!preg_match($allowedPattern, $nonGstTemplate)) {
    $nonGstTemplate = $defaultNonGstTemplate;
}

$relativePath = $isNonGstSale
    ? sprintf('templates/nongst-sales-invoice-templates/%s', $nonGstTemplate)
    : sprintf('templates/%s', $gstTemplate);

$targetUrl = sprintf('%s?invoice=%s', $relativePath, urlencode($invoiceNumber));
$targetUrl .= '&autoprint=' . $autoprint;

header('Location: ' . $targetUrl);
exit();
