<?php ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

$data = urldecode($_REQUEST['data']);

$d = explode("|", $data);

$groupedForms = 0;

$stmt = $GLOBALS['con']->prepare("SELECT `repnumber`,`reptype` FROM `reportitems` WHERE `itemnumber`=? ORDER BY abs(repitem) DESC LIMIT 1") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $d[2]);
$stmt->execute();
$get = $stmt->get_result();
$stmt->close();
$rget = mysqli_fetch_array($get);
if (empty($rget['reptype'])) {
    $stmt2 = $GLOBALS['con']->prepare("SELECT `reptype` FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt2->bind_param('i', $d[2]);
    $stmt2->execute();
    $get = $stmt2->get_result();
    $stmt2->close();
    $rget = mysqli_fetch_array($get);
    $ver = "loadNew";
    echo '<div class="row"><div class="alert alert-warning text center p-1 ps-3"><i style="color:#900" class="fad fa-exclamation-triangle" aria-hidden="true"></i> No report has been generated for this asset yet</div></div>';
} else {
    $ver = "checkVer";
    if ($rget['reptype'] == "701") {
        $rget['reptype'] = 700;
    }
    $td['formnumber'] = $rget['reptype'];
}

//SINGLE FORMS
// Get selected form numbers from master_formtypes
$selectedQuery = "SELECT formnumber FROM master_formtypes WHERE toggle = 1";
$selectedResult = mysqli_query($con, $selectedQuery) or die(mysqli_error($con));

// Create an array to store selected form numbers
$selectedFormNumbers = [];
while ($row = mysqli_fetch_assoc($selectedResult)) {
    $selectedFormNumbers[] = $row['formnumber'];
}

// Query form types from ".$GLOBALS['path'].".dd_formtypes
$queryPath = "SELECT * FROM " . $GLOBALS['path'] . ".dd_formtypes ORDER BY formnumber ASC";
$stmtPath = $master->prepare($queryPath) or die(mysqli_error($master));
$stmtPath->execute();
$recallPath = $stmtPath->get_result();
$stmtPath->close();

// Query form types from dd_formtypes 
$queryLocal = "SELECT * FROM dd_formtypes ORDER BY formnumber ASC";
$stmtLocal = $con->prepare($queryLocal) or die("2" . mysqli_error($con));
$stmtLocal->execute();
$recallLocal = $stmtLocal->get_result();
$stmtLocal->close();

// Filter results from ".$GLOBALS['path'].".dd_formtypes and store them in $reps
$reps = [];  // Array to store the final results

// Filter the form types from ".$GLOBALS['path'].".dd_formtypes using selected form numbers
while ($dtaPath = mysqli_fetch_array($recallPath)) {
    if (in_array($dtaPath['formnumber'], $selectedFormNumbers)) {
        $reps[] = $dtaPath;  // Only include those selected in master_formtypes
    }
}

// Add all form types from dd_formtypes (without filtering)
while ($dtaLocal = mysqli_fetch_array($recallLocal)) {
    $reps[] = $dtaLocal;  // Add unconditionally
}

$highlightedFormNumber = (string)($rget['reptype'] ?? '');
$highlightedReps = [];
$otherReps = [];
foreach ($reps as $rep) {
    if ($highlightedFormNumber !== '' && (string)$rep['formnumber'] === $highlightedFormNumber) {
        $highlightedReps[] = $rep;
    } else {
        $otherReps[] = $rep;
    }
}
$hasHighlightedReports = count($highlightedReps) > 0;

if ($groupedForms == 1) {
    //GROUPED FORMS
    $groupReps = array();
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM dd_groupFormtypes ORDER BY formnumber ASC") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $recall = $stmt->get_result();
    $stmt->close();
    while ($rdta = mysqli_fetch_array($recall)) {
        $groupReps[] = $rdta;
    }
}
?>
<style>
    .formoptions .card {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        min-height: 140px;
        /* keeps them usable on small screens */
        height: 100%;
        text-align: center;
    }

    .formoptions .col-6,
    .formoptions .col,
    .formoptions .report-option-col {
        display: flex;
    }

    .formoptions .card .card-text {
        font-size: 0.9rem;
        margin-top: 0.5rem;
    }

    /* Tweak for small screens */
    @media (max-width: 576px) {

        .formoptions .col-6,
        .formoptions .col {
            flex: 1 0 50%;
            /* two cards per row */
            max-width: 50%;
        }

        .formoptions .card {
            min-height: 120px;
            font-size: 0.85rem;
        }

        .form-number-bg {
            font-size: 2.5rem;
            /* shrink overlay number */
        }
    }


    .card-text {
        position: relative;
        /* Keep the card text in front of the background number */
        z-index: 2;
        /* Ensure it's on top of the background number */
    }

    .report-picker {
        --report-highlight-size: 170px;
        --report-other-size: 119px;
    }

    .report-options-highlighted {
        display: flex;
        gap: 1rem;
        justify-content: center;
        margin-left: 0;
        margin-right: 0;
    }

    .report-options-highlighted .report-highlight-col {
        display: flex;
        flex: 0 0 var(--report-highlight-size);
        justify-content: center;
        max-width: var(--report-highlight-size);
        padding-left: 0;
        padding-right: 0;
        width: var(--report-highlight-size);
    }

    .report-options-highlighted .card {
        aspect-ratio: 1 / 1;
        height: var(--report-highlight-size);
        min-height: 0;
        overflow: hidden;
        width: var(--report-highlight-size);
    }

    .report-options-secondary {
        display: grid;
        gap: 1rem;
        grid-template-columns: repeat(auto-fit, var(--report-other-size));
        justify-content: center;
        margin-left: 0;
        margin-right: 0;
    }

    .report-options-secondary .report-option-col {
        display: flex;
        flex: 0 0 var(--report-other-size);
        margin-bottom: 0 !important;
        max-width: var(--report-other-size);
        padding-left: 0;
        padding-right: 0;
        width: var(--report-other-size);
    }

    .report-options-secondary .card {
        aspect-ratio: 1 / 1;
        height: var(--report-other-size);
        margin: 0;
        min-height: 0;
        overflow: hidden;
        padding: .5rem .4rem;
        width: var(--report-other-size);
    }

    .report-options-secondary .fileIcon_small a {
        font-size: 35px !important;
    }

    .report-options-secondary .card i {
        font-size: 1em;
    }

    .report-options-secondary .card .card-text {
        font-size: 10px;
        line-height: 1.15;
        margin-top: .35rem;
    }

    .report-options-secondary .fileIcon_small>a>p {
        font-size: 10px;
        line-height: 10px !important;
    }

    .report-options-secondary .form-number-bg {
        font-size: .55rem;
    }

    @media (min-width: 768px) and (max-width: 1199.98px) {
        .report-picker {
            --report-highlight-size: 160px;
            --report-other-size: 112px;
        }
    }

    @media (max-width: 767.98px) {
        .report-picker {
            --report-highlight-size: 170px;
            --report-other-size: 119px;
        }

        .report-options-secondary .card {
            padding: .55rem .45rem;
        }

        .report-options-secondary .card .card-text {
            font-size: .6rem;
        }

        .report-options-secondary .form-number-bg {
            font-size: .55rem;
        }
    }
</style>
<div class="container-fluid report-picker">
    <div class="row formoptions">
        <?php if ($groupedForms == 1) { ?>
            <!-- New Left Column -->
            <div class="col-12 col-md-2 pb-4 bg-info rounded-start-3 mx-0">
                <p class="text-light mt-2">Grouped Reports</p>
                <?php foreach ($groupReps as $rdta) {
                    if ((string)$rdta['formnumber'] === $highlightedFormNumber) {
                        $col = "active";
                    } else {
                        $col = "";
                    } ?>
                    <div class="col d-flex mb-3 mx-0">
                        <div
                            class="card card-body fileIcon_small text-center <?= $col ?> border border-info position-relative mx-0">
                            <a href="javascript:void(0)" data-mdb-tooltip-init data-mdb-placement="bottom"
                                data-mdb-trigger="hover" data-mtitle="<?= $rdta['formtype'] ?>"
                                onClick="<?= $ver ?>('<?= $rdta['formnumber'] ?>')">
                                <i class="fad fa-file-alt" aria-hidden="true"></i><br>
                                <p class="card-text"><b><?= $rdta['description'] ?></b></p>
                            </a>
                            <span class="form-number-bg"><?= $rdta['formnumber'] ?></span>
                        </div>
                    </div>
                <?php } ?>

            </div>
        <?php } ?>
        <!-- Existing Right Column -->
        <div class="col-12 <?php if ($groupedForms == 1) { ?>col-md-10<?php } else { ?>col-md-12<?php } ?> ">
            <?php if ($groupedForms == 1) { ?><p class="mt-2">Single Reports</p><?php } ?>
            <?php if ($hasHighlightedReports) { ?>
                <div class="row report-options-highlighted">
                    <?php foreach ($highlightedReps as $dta) { ?>
                        <div class="report-highlight-col report-option-col mb-3">
                            <div class="card card-body fileIcon_small text-center active border border-info position-relative">
                                <a href="javascript:void(0)" data-mdb-tooltip-init data-mdb-placement="bottom"
                                    data-mdb-trigger="hover" data-mtitle="<?= $dta['formtype'] ?>"
                                    onClick="<?= $ver ?>('<?= $dta['formnumber'] ?>')">
                                    <i class="fad fa-file-alt" aria-hidden="true"></i><br>
                                    <p class="card-text"><b><?= $dta['description'] ?></b></p>
                                </a>
                                <span class="form-number-bg"><?= $dta['formnumber'] ?></span>
                            </div>
                        </div>
                    <?php } ?>
                </div>
            <?php } ?>

            <div class="row <?= $hasHighlightedReports ? 'report-options-secondary' : '' ?>">
                <?php foreach (($hasHighlightedReports ? $otherReps : $reps) as $dta) {
                    if ((string)$dta['formnumber'] === $highlightedFormNumber) {
                        $col = "active";
                    } else {
                        $col = "";
                    }
                    $gridClass = $hasHighlightedReports ? '' : 'col-6 col-md-3';
                ?>
                    <div class="<?= $gridClass ?> report-option-col mb-3">
                        <div
                            class="card card-body fileIcon_small text-center <?= $col ?> border border-info position-relative">
                            <a href="javascript:void(0)" data-mdb-tooltip-init data-mdb-placement="bottom"
                                data-mdb-trigger="hover" data-mtitle="<?= $dta['formtype'] ?>"
                                onClick="<?= $ver ?>('<?= $dta['formnumber'] ?>')">
                                <i class="fad fa-file-alt" aria-hidden="true"></i><br>
                                <p class="card-text"><b><?= $dta['description'] ?></b></p>
                            </a>
                            <span class="form-number-bg"><?= $dta['formnumber'] ?></span>
                        </div>
                    </div>
                <?php } ?>
            </div>
        </div>
    </div>
</div>





<div id="erm" class="text-center"></div>
<script>
    function checkVer(i) {

        var dest = encodeURI(ROOT_URL + '/includes/master/formgen.php?mode=check&formnumber=' + i +
            '&data=<?= urlencode($_REQUEST['data']) ?>&tenant=<?= $_REQUEST['tenant'] ?>');
        loadModalContent(dest, "optionBox", "modal-xl", 1070, "true", "Load Options");

    }

    function loadNew(i) {
        window.location.href = 'index.php?t=includes/master/&p=formgen.php&mode=new&formnumber=' + i +
            '&data=<?= $_REQUEST['data'] ?>';

    }
</script>