<?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
}


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 {
  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 */
}
</style>
<div class="container-fluid">
    <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 ($rdta['formnumber'] == $rget['reptype']) {
                    $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 }?> border border-info rounded-end-3">
            <?php if($groupedForms==1){?><p class="mt-2">Single Reports</p><?php }?>
            <div class="row">
                <?php foreach ($reps as $dta) {
                    if ($dta['formnumber'] == $rget['reptype']) {
                        $col = "active";
                    } else {
                        $col = "";
                    } ?>
                <div class="col-6 col-md-3 d-flex 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>