<?php
$data = urldecode($_REQUEST['data']);
$d = explode("|", $data);
$scheduleUrl = 'index.php?t=includes/master&p=client.php&clientnumber=' . (int)$d[0] . '&view=asset';

function renderReportEmptyState($mode, $itemName, $scheduleUrl)
{
    $isArchive = ($mode === 'archive');
    $title = $isArchive ? 'No archived reports yet' : 'No active reports yet';
    $body = $isArchive
        ? 'Archived inspection reports for this item will appear here once older reports are moved out of the active list.'
        : 'Completed inspection reports for this item will appear here once a report has been created and saved.';
    $icon = $isArchive ? 'fa-box-archive' : 'fa-file-circle-plus';
?>
<div class="report-empty-state">
    <div class="report-empty-icon">
        <i class="fad <?= $icon ?>" aria-hidden="true"></i>
    </div>
    <div class="report-empty-copy">
        <h5><?= $title ?></h5>
        <p><?= $body ?></p>
        <span class="report-empty-item">Item: <strong><?= htmlspecialchars($itemName, ENT_QUOTES) ?></strong></span>
    </div>
</div>
<?php
}
?>
<script>
document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&view=list">Client List</a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li><li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $d['0'] ?>&view=asset"><?= getClientName($d[0]) ?></a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li><li class="breadcrumb-item active">Completed Reports: <?= getItemName($d[2]) ?></li>';
</script>
<style>
.report-empty-state {
    align-items: center;
    background: linear-gradient(135deg, #ffffff 0%, #f8fbfd 100%);
    border: 1px solid #d7e1ea;
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    gap: 16px;
    justify-content: center;
    margin: 28px auto 38px;
    max-width: 760px;
    min-height: 250px;
    padding: 38px 42px;
    text-align: center;
    box-shadow: 0 8px 24px rgba(31, 41, 51, 0.08);
}

.report-empty-icon {
    align-items: center;
    background: #f4f7fa;
    border: 1px solid #dce6ee;
    border-radius: 50%;
    color: #9f6a12;
    display: inline-flex;
    flex: 0 0 72px;
    font-size: 31px;
    height: 72px;
    justify-content: center;
    width: 72px;
}

.report-empty-copy {
    flex: 1 1 auto;
    max-width: 560px;
    min-width: 0;
}

.report-empty-copy h5 {
    color: #17212b;
    font-size: 20px;
    font-weight: 600;
    margin: 0 0 8px;
}

.report-empty-copy p {
    color: #4f5f6f;
    font-size: 15px;
    line-height: 1.55;
    margin: 0 0 16px;
}

.report-empty-item {
    background: #eef3f7;
    border: 1px solid #dce6ee;
    border-radius: 4px;
    color: #52616b;
    display: inline-flex;
    font-size: 13px;
    justify-content: center;
    line-height: 1.25;
    padding: 5px 8px;
}

.report-list-toolbar {
    background: #fff;
    display: flex;
    justify-content: flex-start !important;
    padding: 12px 18px;
}

.report-list-content {
    background: transparent;
    border: 0;
    box-shadow: none;
    padding: 0 18px 18px;
}

.report-tabs {
    background: #fff !important;
    border: 0;
    gap: 8px;
    padding: 18px 18px 0;
}

.report-tabs .nav-item {
    flex: 1 1 0;
}

.report-tabs .nav-link {
    align-items: center;
    background: #eef3f7;
    border: 1px solid #d6e0e8;
    border-radius: 6px;
    color: #22384d !important;
    display: flex;
    font-size: 13px;
    font-weight: 600;
    gap: 8px;
    justify-content: center;
    letter-spacing: 0;
    min-height: 46px;
    text-transform: none;
    transition: background-color .15s ease, border-color .15s ease, box-shadow .15s ease;
}

.report-tabs .nav-link:hover,
.report-tabs .nav-link:focus {
    background: #e3ebf2;
    border-color: #b8c9d7;
    box-shadow: 0 3px 10px rgba(31, 56, 77, 0.12);
}

.report-tabs .nav-link.active {
    background: #274058;
    border-color: #274058;
    box-shadow: 0 7px 18px rgba(39, 64, 88, 0.2);
    color: #fff !important;
}

.report-tabs .tab-action-text {
    white-space: nowrap;
}

.report-section-intro {
    margin: 12px 0 18px;
    padding: 0;
}

.report-section-intro p {
    color: #22303c;
    font-size: 19px;
    line-height: 1.35;
    margin-bottom: 4px;
}

.report-section-intro small {
    color: #52616b;
    font-size: 14px;
}

.report-card-grid {
    display: grid;
    gap: 18px;
    grid-template-columns: repeat(auto-fill, 285px);
    justify-content: start;
}

.report-card-grid > div {
    display: flex;
    min-width: 285px;
}

.report-card {
    background: #fff;
    height: 100%;
    min-height: 310px;
    min-width: 285px;
    width: 100%;
}

.report-card .report-card-actions {
    display: flex;
    flex-wrap: nowrap;
    gap: 5px;
    justify-content: center;
}

.report-card .report-card-actions .btn {
    align-items: center;
    display: inline-flex;
    flex: 0 0 38px;
    height: 38px;
    justify-content: center;
    margin: 0;
    min-width: 38px;
    padding: 8px 10px;
}

@media (min-width: 1200px) {
    .report-card-grid {
        grid-template-columns: repeat(auto-fill, 285px);
    }

    .report-card-grid > div,
    .report-card {
        min-width: 285px;
    }
}

@media (max-width: 767.98px) {
    .report-empty-state {
        gap: 14px;
        margin: 18px auto 24px;
        min-height: 220px;
        padding: 28px 20px;
    }

    .report-list-toolbar {
        justify-content: stretch;
        padding: 12px;
    }

    .report-list-toolbar .btn {
        width: 100%;
    }

    .report-tabs {
        gap: 6px;
        padding: 12px 12px 0;
    }

    .report-tabs .nav-link {
        font-size: 12px;
        min-height: 44px;
        padding-left: 8px;
        padding-right: 8px;
    }

    .report-card-grid {
        grid-template-columns: 1fr;
    }

    .report-card-grid > div,
    .report-card {
        min-width: 0;
    }
}
</style>

<ul class="nav nav-tabs nav-justified report-tabs mt-0" id="myTab" role="tablist">
    <li class="nav-item" role="presentation">
        <a data-mdb-tab-init id="reptab" class="nav-link active" data-mdb-toggle="tab"
            href="#repcard" role="tab" aria-controls="repcard" aria-selected="true">
            <i class="fad fa-file-check" aria-hidden="true"></i>
            <span class="tab-action-text">View active reports</span>
        </a>
    </li>
    <li class="nav-item" role="presentation">
        <a data-mdb-tab-init id="wstab" class="nav-link" data-mdb-toggle="tab" href="#wscard"
            role="tab" aria-controls="wscard" aria-selected="false">
            <i class="fad fa-box-archive" aria-hidden="true"></i>
            <span class="tab-action-text">View archived reports</span>
        </a>
    </li>
</ul>

<div class="report-list-toolbar">
    <a href="<?= htmlspecialchars($scheduleUrl, ENT_QUOTES) ?>" class="btn btn-secondary btn-sm">
        <i class="fad fa-arrow-left"></i> Back to schedule
    </a>
</div>

<div class="tab-content report-list-content">


    <div class="tab-pane fade show active" id="repcard" role="tabpanel" aria-labelledby="reptab">
        <?php
        $stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`repitem`,`repnumber`,`reptype`,`itemnumber`,`insdate`,`delivery`,`result`,`reportdata` FROM `reportitems` WHERE `itemnumber`=? AND `clientnumber`=? ORDER BY ABS(`repnumber`) DESC") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('ii', $d[2], $d[0]);
        $stmt->execute();
        $r = $stmt->get_result();
        $stmt->close();
        $rnum = mysqli_num_rows($r);
        if ($rnum < 1) {
            renderReportEmptyState('active', getItemName($d[2]), $scheduleUrl);
        } else { ?>
        <div class="report-section-intro">
            <p>Completed reports for <strong><?= getItemName($d[2]) ?></strong><br><small>Hover over the icons for
                    additional information</small></p>
        </div>

        <div class="report-card-grid">
            <?php
                $c = 1;
                while ($dta = mysqli_fetch_array($r)) {
                    $tag = "";
                    $clientcall = mysqli_query($GLOBALS['con'], "SELECT * FROM `clientdetails` WHERE `clientnumber`='" . $dta['clientnumber'] . "'");
                    $cd = mysqli_fetch_array($clientcall);
                    //$conv=strtotime($dta['insdate']);
                    $date = date('d-m-Y', $dta['insdate']);
                    $rd = enrepReportDataFromRow($dta);
                    $adefect = explode("|", (string)($rd['adefect'] ?? ''));

                    if ($dta['result'] == "DEFECTS") {
                        $col = "#F4AA09";
                        $title = "DEFECTS<br>" . ($rd['bdefect'] ?? '');
                        $file = "file-exclamation";
                    }
                    if ($dta['result'] == "URGENT") {
                        $col = "#e96152";
                        $title = "URGENT<br>" . $adefect[0];
                        $file = "file-excel";
                    }
                    if ($dta['result'] == "PASS") {
                        $col = "#007E33";
                        $tag = "Pass";
                        $title = "Pass";
                        $file = "file-powerpoint";
                    }
                    if ($dta['result'] == "OBS") {
                        $col = "#333333";
                        $tag = "Obs";
                        $title = "OBS<br>" . ($rd['obs'] ?? '');
                        $file = "file-alt";
                    }
                    if ($dta['result'] == "PNA") {
                        $col = "#00695c";
                        $tag = "PNA";
                        $title = "PNA";
                        $file = "file-minus";
                    }
                    if ($dta['result'] == "") {
                        $col = "#9211E8";
                        $tag = "P2UD";
                        $title = "P2UD";
                        $file = "file";
                    }
                    $relativeFile = 'reports/' . $dta['clientnumber'] . '/' . $dta['repnumber'] . '_' . $dta['itemnumber'] . '.pdf';

                    $email_values = [
                        'clientNumber'   => (string)$dta['clientnumber'],
                        'clientName'     => (string)$cd['pri_contact_name'],
                        'primaryEmail'   => (string)$cd['email'],
                        'secondaryEmail' => '',
                        'subject'        => 'emailing documents',
                        'message'        => '',
                        'mode'           => 'output',
                        'filePath'       => 'output',
                        'fileName'       => $relativeFile
                    ];

                    $email64_values = base64_encode(json_encode($email_values));

                ?>
            <div id="R<?= $dta['repnumber'] ?>">
                <div class="card card-body report-card fileIcon text-center mb-4 border  hover-info">

                    <a href="index.php?t=includes/master&p=items.php&view=view&repnumber=<?= $dta['repnumber'] ?>&data=<?= $_REQUEST['data'] ?>&mode=reportitems"
                        data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" data-mdb-html="true"
                        title="<?= $title ?>"><i style="color:<?= $col ?>" class="fad fa-<?= $file ?>"
                            aria-hidden="true"></i></a><br />
                    <p><strong><?= $dta['repnumber'] ?></strong><br><?= getReportDesc($dta['reptype'], 'formtype') ?><br><?= $date ?><br>
                    </p>
                    <div class="report-card-actions">
                        <a href="javascript:void(0)" class="btn btn-secondary noprint emailButton"
                            data-values="<?= $email64_values ?>" data-href="<?= ROOT_URL ?>/includes/master/mailer.php"
                            data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                            title="Email Client"><i class="fad fa-envelope"></i></a>
                        <a href="index.php?t=includes/master&p=items.php&view=view&repnumber=<?= $dta['repnumber'] ?>&data=<?= $_REQUEST['data'] ?>&mode=reportitems"
                            class="btn btn-secondary" data-mdb-tooltip-init data-mdb-placement="bottom"
                            data-mdb-trigger="hover" title="View  Report"><i class="fad fa-eye"></i></a>
                        <?php if ($dta['delivery'] == "0") { ?>
                        <button type="button" class="btn btn-secondary" data-mdb-tooltip-init
                            data-mdb-placement="bottom" data-mdb-trigger="hover" title="Report not delivered"><i
                                class="fad fa-paper-plane" aria-hidden="true"> </i></button>
                        <?php } else { ?>
                        <button type="button" class="btn btn-info" data-mdb-tooltip-init data-mdb-placement="bottom"
                            data-mdb-trigger="hover" title="Report delivered <?= date('d-m-y', $dta['delivery']) ?>"><i
                                class="fad fa-paper-plane" aria-hidden="true"> </i></button>
                        <?php } ?>

                        <a href="index.php?t=includes/master&p=formgen.php&mode=reload&formnumber=<?= $dta['reptype'] ?>&repnumber=<?= $dta['repnumber'] ?>&data=<?= $_REQUEST['data'] ?>&savemode=edit"
                            class="btn btn-secondary" data-mdb-tooltip-init data-mdb-placement="bottom"
                            data-mdb-trigger="hover" title="Edit  Report"><i class="fad fa-pencil"></i></a>

                        <button type="button" class="btn btn-secondary" data-mdb-tooltip-init
                            data-mdb-placement="bottom" data-mdb-trigger="hover" title="Report Qr"
                            onclick="loadQR(<?= $dta['repnumber'] ?>)"><i class="fad fa-qrcode" aria-hidden="true">
                            </i></button>
                    </div>
                    <?php if (($_SESSION['access'] == 1 || $_SESSION['access'] == 2 || $_SESSION['access'] == 999) && $c == 1) { ?>
                    <div style="position:absolute; top:3px; right:3px">
                        <button onclick="delRep('<?= $dta['repitem'] ?>','<?= $_REQUEST['data'] ?>')" type="button"
                            class="btn btn-sm btn-danger m-0 px-3 py-2 " data-mdb-tooltip-init
                            data-mdb-placement="bottom" data-mdb-trigger="hover" title="Delete Report"><i
                                class="fad fa-times" aria-hidden="true" style="--fa-secondary-opacity: 1.0">
                            </i></button>
                    </div>

                    <?php } ?>
                </div>
            </div>

            <?php $c++;
                } ?>
        </div>
        <?php } ?>
    </div>
    <div class="tab-pane fade" id="wscard" role="tabpanel" aria-labelledby="wstab">
        <?php
        $stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`repitem`,`repnumber`,`reptype`,`itemnumber`,`insdate`,`delivery`,`result`,`reportdata` FROM `archiveitems` WHERE `itemnumber`=? ORDER BY ABS(`repnumber`) DESC") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $d[2]);
        $stmt->execute();
        $r = $stmt->get_result();
        $stmt->close();
        $rnum = mysqli_num_rows($r);

        if ($rnum < 1) {
            renderReportEmptyState('archive', getItemName($d[2]), $scheduleUrl);
        } else { ?>
        <div class="report-section-intro">
            <p>Archived reports for <strong><?= getItemName($d[2]) ?></strong><br><small>Hover over the icons for
                    additional information</small></p>
        </div>

        <div class="report-card-grid">
        <?php
            while ($dta = mysqli_fetch_array($r)) {
                if ($dta['reptype'] == "") {
                } else {
                    $tag = "";
                    $clientcall = mysqli_query($GLOBALS['con'], "SELECT * FROM `clientdetails` WHERE `clientnumber`='" . $dta['clientnumber'] . "'");
                    $cd = mysqli_fetch_array($clientcall);
                    //$conv=strtotime($dta['insdate']);
                    $date = date('d-m-Y', $dta['insdate']);
                    $rd = enrepReportDataFromRow($dta);
                    $adefect = explode("|", (string)($rd['adefect'] ?? ''));

                    if ($dta['result'] == "DEFECTS") {
                        $col = "#F4AA09";
                        $title = "DEFECTS<br>" . ($rd['bdefect'] ?? '');
                        $file = "file-exclamation";
                    }
                    if ($dta['result'] == "URGENT") {
                        $col = "#e96152";
                        $title = "URGENT<br>" . $adefect[0];
                        $file = "file-excel";
                    }
                    if ($dta['result'] == "PASS") {
                        $col = "#007E33";
                        $tag = "Pass";
                        $title = "Pass";
                        $file = "file-powerpoint";
                    }
                    if ($dta['result'] == "OBS") {
                        $col = "#333333";
                        $tag = "Obs";
                        $title = "OBS<br>" . ($rd['obs'] ?? '');
                        $file = "file-alt";
                    }
                    if ($dta['result'] == "PNA") {
                        $col = "#cccccc";
                        $tag = "PNA";
                        $title = "PNA";
                        $file = "file";
                    }
                    if ($dta['result'] == "") {
                        $col = "#9211E8";
                        $tag = "P2UD";
                        $title = "P2UD";
                        $file = "file";
                    }
            ?>
        <div id="R<?= $dta['repnumber'] ?>" class="">
            <div class="card card-body report-card fileIcon text-center mb-4">
                <a href="index.php?t=includes/master&p=items.php&view=view&repnumber=<?= $dta['repnumber'] ?>&data=<?= $_REQUEST['data'] ?>&mode=reportitems"
                    data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" data-mdb-html="true"
                    title="<?= $title ?>"><i style="color:<?= $col ?>" class="fad fa-<?= $file ?>"
                        aria-hidden="true"></i></a><br />
                <p><strong><?= $dta['repnumber'] ?></strong><br><?= getReportDesc($dta['reptype'], 'formtype') ?><br><?= $date ?><br>
                </p>
                <div class="report-card-actions">

                    <a href="index.php?t=includes/master&p=items.php&view=view&repnumber=<?= $dta['repnumber'] ?>&data=<?= $_REQUEST['data'] ?>&mode=archiveitems"
                        class="btn btn-secondary" data-mdb-tooltip-init data-mdb-placement="bottom"
                        data-mdb-trigger="hover" title="View  Report"><i class="fad fa-eye"></i></a>
                    <?php if ($dta['delivery'] == "0" || $dta['delivery'] == "") { ?>
                    <button type="button" class="btn btn-secondary" data-mdb-tooltip-init data-mdb-placement="bottom"
                        data-mdb-trigger="hover" title="Report not delivered"><i class="fad fa-paper-plane"
                            aria-hidden="true"> </i></button>
                    <?php } else { ?>
                    <button type="button" class="btn btn-info" data-mdb-tooltip-init data-mdb-placement="bottom"
                        data-mdb-trigger="hover" title="Report delivered <?= date('d-m-y', $dta['delivery']) ?>"><i
                            class="fad fa-paper-plane" aria-hidden="true"> </i></button>
                    <?php } ?>

                    <a href="index.php?t=includes/master&p=formgen.php&mode=archiveReload&formnumber=<?= $dta['reptype'] ?>&repnumber=<?= $dta['repnumber'] ?>&data=<?= $_REQUEST['data'] ?>&savemode=edit"
                        class="btn btn-secondary" data-mdb-tooltip-init data-mdb-placement="bottom"
                        data-mdb-trigger="hover" title="Edit  Report"><i class="fad fa-pencil"></i></a>

                    <button type="button" class="btn btn-secondary" data-mdb-tooltip-init data-mdb-placement="bottom"
                        data-mdb-trigger="hover" title="Report Qr" onclick="loadQR(<?= $dta['repnumber'] ?>)"><i
                            class="fad fa-qrcode" aria-hidden="true"> </i></button>
                </div>
            </div>
        </div>

        <?php }
            } ?>
        </div>

        <?php } ?>
    </div>
</div>
<script>
function loadQR(repnumber) {
    var target = ROOT_URL + '/includes/asset/asset_qr.php'
    var dest = encodeURI(target + "?repnumber=" + repnumber + "&tenant=" + TENANT_URL);
    loadModalContent(dest, "qrBox", "modal-xl", 1060, "true", "Report Security QR");
}

function getChecks() {
    var selected = ''
    $('input[type=checkbox]').each(function() {
        if ($(this).is(":checked")) {
            selected = selected + ($(this).attr('name') + '|');
        }

    });
    // alert(selected)
}

function delRep(r, d) {
    var dest = '<p></p>Are you sue you want to remove this inspection registration?</p>';
    loadModalContent(dest, "popupBox", "modal-xl", 1060, "true", 'Inspection Removal', "cancelConfirm", () =>
        delConfirm(r, d));
}

function delConfirm(r, d) {
    $('#R' + r).fadeOut()
    $.post('<?= ROOT_URL ?>/includes/master/item_functions.php', {
        FUNCTION: 'remove',
        rep: r,
        dataSet: d,
        tenant: TENANT_URL
    }, function(ret) {
        //debug(ret)
        window.location.href = "index.php?t=includes/master&p=items.php&data=<?= $_REQUEST['data'] ?>&view=list"
    })
}
</script>
