<?php
// Checked for PHP5.6 / 8.x compatibility
include("../../operainfo/getq2.php");

$stkref = safetext2(isset($_GET['stkref']) ? $_GET['stkref'] : '');
$type = safetext2(isset($_GET['type']) ? $_GET['type'] : '');
$hostcompanyid = safetext2(isset($_GET['hostcompanyid']) ? $_GET['hostcompanyid'] : 0);

if (empty($stkref) || empty($type)) {
    echo "<p>No documents found.</p>";
    exit;
}

$documents = array();

// 1. Get documents directly linked to this stock ref with the specific type
$sql = "SELECT
        ISO_quality_manual_files.docid,
        ISO_quality_manual_files.description,
        ISO_quality_manual_files.filename,
        ISO_quality_manual_files.revisionconrtol,
        ISO_quality_manual_files.addedon,
        ISO_quality_manual_files.addedby,
        'Direct' as link_type
    FROM ISO_quality_manual_files
    INNER JOIN ISO_quality_manual_stock_links ON ISO_quality_manual_files.docid = ISO_quality_manual_stock_links.docid
    WHERE ISO_quality_manual_stock_links.stock_ref = ?
    AND ISO_quality_manual_files.type = ?
    AND ISO_quality_manual_files.archived = ''
    ORDER BY ISO_quality_manual_files.addedon DESC";

$stmt = pdoquery($sql, array($stkref, $type));
$direct_docs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$documents = array_merge($documents, $direct_docs);

// 2. Get documents linked via stock groups
// First, find what groups this stock ref belongs to
$sql_groups = "SELECT DISTINCT groupcode FROM viamed_customer_stock_references_groupcodes_links WHERE stockref = ?";
$stmt_groups = pdoquery($sql_groups, array($stkref));
$groups = $stmt_groups->fetchAll(PDO::FETCH_COLUMN);

if (!empty($groups)) {
    // For each group, get documents linked to that group with the specific type
    foreach ($groups as $groupcode) {
        $sql_group_docs = "SELECT
                ISO_quality_manual_files.docid,
                ISO_quality_manual_files.description,
                ISO_quality_manual_files.filename,
                ISO_quality_manual_files.revisionconrtol,
                ISO_quality_manual_files.addedon,
                ISO_quality_manual_files.addedby,
                CONCAT('Group: ', ?) as link_type
            FROM ISO_quality_manual_files
            INNER JOIN regulatory_group_documents ON ISO_quality_manual_files.docid = regulatory_group_documents.docid
            WHERE regulatory_group_documents.groupcode = ?
            AND ISO_quality_manual_files.type = ?
            AND ISO_quality_manual_files.archived = ''
            ORDER BY ISO_quality_manual_files.addedon DESC";

        $stmt_group_docs = pdoquery($sql_group_docs, array($groupcode, $groupcode, $type));
        $group_docs = $stmt_group_docs->fetchAll(PDO::FETCH_ASSOC);
        $documents = array_merge($documents, $group_docs);
    }
}

// 3. Get documents from regulatory_stock_provided_documents (individual stock docs)
$sql_regulatory = "SELECT
        ISO_quality_manual_files.docid,
        ISO_quality_manual_files.description,
        ISO_quality_manual_files.filename,
        ISO_quality_manual_files.revisionconrtol,
        ISO_quality_manual_files.addedon,
        ISO_quality_manual_files.addedby,
        'Regulatory' as link_type
    FROM ISO_quality_manual_files
    INNER JOIN regulatory_stock_provided_documents ON ISO_quality_manual_files.docid = regulatory_stock_provided_documents.docid
    WHERE regulatory_stock_provided_documents.stockref = ?
    AND ISO_quality_manual_files.archived = ''
    ORDER BY ISO_quality_manual_files.addedon DESC";

$stmt_regulatory = pdoquery($sql_regulatory, array($stkref));
$regulatory_docs = $stmt_regulatory->fetchAll(PDO::FETCH_ASSOC);
$documents = array_merge($documents, $regulatory_docs);

// Remove duplicates based on docid
$unique_documents = array();
foreach ($documents as $doc) {
    $unique_documents[$doc['docid']] = $doc;
}
$documents = array_values($unique_documents);

// Sort by addedon descending
usort($documents, function($a, $b) {
    return $b['addedon'] - $a['addedon'];
});

if (count($documents) == 0) {
    echo "<p>No documents found for this stock item.</p>";
} else {
    echo "<table class='document-table'>";
    echo "<thead><tr><th>Description</th><th>Revision</th><th>Added</th><th>Type</th><th>Actions</th></tr></thead><tbody>";
    foreach ($documents as $row) {
        $docid = $row['docid'];
        $description = htmlspecialchars($row['description']);
        $revisioncontrol = htmlspecialchars($row['revisionconrtol']);
        $addedon = date('d/m/Y H:i', $row['addedon']);
        $addedby = htmlspecialchars($row['addedby']);
        $link_type = htmlspecialchars($row['link_type']);

        $link = linkdocid($x, $docid);

        // Build update issue link based on hostcompanyid
        $base_url = "/intranet/databases/agenda/issuesubsection.php" . $x;
        if ($hostcompanyid == 1) {
            $update_url = $base_url . "&sectionid=9&subsectionid=0&meetingid=109&agendaid=272&stkref=" . $stkref . "&docid=" . $docid . "&subject=" . $stkref . " Update of Goods in Document";
        } elseif ($hostcompanyid == 2) {
            $update_url = $base_url . "&sectionid=1&subsectionid=2&meetingid=787&agendaid=815&stkref=" . $stkref . "&docid=" . $docid . "&subject=" . $stkref . " Update of Goods in Document";
        } elseif ($hostcompanyid == 3) {
            $update_url = $base_url . "&sectionid=1&subsectionid=2&meetingid=581&agendaid=609&docid=" . $docid . "&subject=" . $stkref . " Update of Goods in Document";
        } else {
            $update_url = $base_url . "&sectionid=1&subsectionid=2&meetingid=55&agendaid=417&stkref=" . $stkref . "&docid=" . $docid . "&subject=" . $stkref . " Update of Goods in Document";
        }

        echo "<tr>";
        echo "<td>".linkdocid($x,$docid)."<strong>$description</strong></td>";
        echo "<td>$revisioncontrol</td>";
        echo "<td>$addedon by $addedby</td>";
        echo "<td>$link_type</td>";
        echo "<td><span onclick=\"logDocView(" . (int)$docid . ")\">" . show_thumbnail_popup_button($docid, $x) . "</span>  <button onclick=\"window.open('$update_url', '_blank')\">Update Document</button></td>";
        echo "</tr>";
    }
    echo "</tbody></table>";

    // Build issue creation link based on hostcompanyid
    $base_url = "/intranet/databases/agenda/issuesubsection.php" . $x;
    if ($hostcompanyid == 1) {
        $url = $base_url . "&sectionid=9&subsectionid=0&meetingid=109&agendaid=272&stkref=" . $stkref . "&subject=" . $stkref . " New Goods In Document";
    } elseif ($hostcompanyid == 2) {
        $url = $base_url . "&sectionid=1&subsectionid=2&meetingid=787&agendaid=815&stkref=" . $stkref . "&subject=" . $stkref . " New Goods In Document";
    } elseif ($hostcompanyid == 3) {
        $url = $base_url . "&sectionid=1&subsectionid=2&meetingid=581&agendaid=609&subject=" . $stkref . " New Goods In Document";
    } else {
        $url = $base_url . "&sectionid=1&subsectionid=2&meetingid=55&agendaid=417&stkref=" . $stkref . "&subject=" . $stkref . " New Goods In Document";
    }
    echo "<br><button onclick=\"window.open('$url', '_blank')\">ADD New Label / IFU</button>";
}
?>