<?php
require_once(ROOT_URL . '/includes/master/form_functions.php');

$incompleteUserType = (string)($_SESSION['usertype'] ?? '');
$incompleteUserId = (int)($_SESSION['userid'] ?? 0);
$incompleteClientNumber = (int)($_REQUEST['clientnumber'] ?? 0);
$incompleteIsSurveyor = $incompleteUserType === 'surveyor' && $incompleteUserId > 0;
$incompleteIsAdmin = $incompleteUserType === 'admins';

$where = [];
$types = '';
$params = [];

if ($incompleteClientNumber > 0) {
    $where[] = 'a.`clientnumber` = ?';
    $types .= 'i';
    $params[] = $incompleteClientNumber;
}

if ($incompleteIsSurveyor) {
    $where[] = 'a.`esname` = ?';
    $types .= 'i';
    $params[] = $incompleteUserId;
}

$whereSql = empty($where) ? '' : 'WHERE ' . implode(' AND ', $where);

$stmt = $GLOBALS['con']->prepare("
    SELECT
        a.`clientnumber`,
        a.`repitem`,
        a.`repnumber`,
        a.`reptype`,
        a.`itemnumber`,
        a.`insdate`,
        a.`reportdata`,
        a.`result`,
        a.`esname`,
        b.`plantnumber`,
        b.`serialnumber`,
        b.`desc`,
        b.`locnumber`,
        c.`clientname`,
        s.`surname`,
        s.`forename`
    FROM `reportitems_temp` a
    INNER JOIN `itemdetails` b ON b.`itemnumber` = a.`itemnumber`
    LEFT JOIN `clientdetails` c ON c.`clientnumber` = a.`clientnumber`
    LEFT JOIN `surveyor` s ON s.`id` = a.`esname`
    $whereSql
    ORDER BY s.`forename`, s.`surname`, c.`clientname`, ABS(a.`repitem`) DESC
") or die(mysqli_error($GLOBALS['con']));

if ($types !== '') {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$r = $stmt->get_result();
$stmt->close();
$rnum = mysqli_num_rows($r);

$pageTitle = $incompleteClientNumber > 0
    ? 'Incomplete reports for ' . getClientName($incompleteClientNumber)
    : 'Incomplete reports';
?>
<div class="alert alert-info p-2">
    <p class="text-center m-0"><?= htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8') ?></p>
</div>

<div class="tab-content card">
    <div class="tab-pane fade show active" id="repcard" role="tabpanel" aria-labelledby="reptab">
        <div class="card-body">
            <?php if ($rnum < 1) { ?>
            <div class="alert alert-warning text-center p-2">
                <i class="fad fa-exclamation-triangle text-danger" aria-hidden="true"></i>
                No reports on file
                <i class="fad fa-exclamation-triangle text-danger" aria-hidden="true"></i>
            </div>
            <?php } else {
                $currentSurveyor = null;
                while ($dta = mysqli_fetch_array($r)) {
                    $surveyorName = trim((string)($dta['forename'] ?? '') . ' ' . (string)($dta['surname'] ?? ''));
                    if ($surveyorName === '') {
                        $surveyorName = 'Unassigned';
                    }

                    if ($incompleteIsAdmin && $currentSurveyor !== $surveyorName) {
                        if ($currentSurveyor !== null) {
                            echo '</tbody></table></div>';
                        }
                        $currentSurveyor = $surveyorName;
                        echo '<h5 class="mt-3 mb-2"><small>Surveyor: ' . htmlspecialchars($surveyorName, ENT_QUOTES, 'UTF-8') . '</small></h5>';
                        echo '<div class="table-responsive mb-4"><table class="table table-sm table-striped align-middle incomplete-report-table"><thead><tr><th>Client</th><th>Item</th><th>Plant Number</th><th>Serial Number</th><th>Report Type</th><th>Inspection Date</th><th>Result</th><th class="text-end">Action</th></tr></thead><tbody>';
                    } elseif (!$incompleteIsAdmin && $currentSurveyor === null) {
                        $currentSurveyor = $surveyorName;
                        echo '<div class="table-responsive"><table class="table table-sm table-striped align-middle incomplete-report-table"><thead><tr><th>Client</th><th>Item</th><th>Plant Number</th><th>Serial Number</th><th>Report Type</th><th>Inspection Date</th><th>Result</th><th class="text-end">Action</th></tr></thead><tbody>';
                    }

                    $date = !empty($dta['insdate']) ? date('d-m-Y', (int)$dta['insdate']) : '';
                    $result = trim((string)($dta['result'] ?? ''));
                    if ($result === '') {
                        $result = 'P2UD';
                    }
                    $clientName = trim((string)($dta['clientname'] ?? ''));
                    if ($clientName === '') {
                        $clientName = getClientName((int)$dta['clientnumber']);
                    }
                    ?>
                    <tr id="R<?= (int)$dta['repitem'] ?>">
                        <td><?= htmlspecialchars($clientName, ENT_QUOTES, 'UTF-8') ?></td>
                        <td>
                            <strong><?= htmlspecialchars((string)$dta['desc'], ENT_QUOTES, 'UTF-8') ?></strong><br>
                            <small class="text-muted">Report <?= htmlspecialchars((string)$dta['repnumber'], ENT_QUOTES, 'UTF-8') ?></small>
                        </td>
                        <td><?= htmlspecialchars((string)$dta['plantnumber'], ENT_QUOTES, 'UTF-8') ?></td>
                        <td><?= htmlspecialchars((string)$dta['serialnumber'], ENT_QUOTES, 'UTF-8') ?></td>
                        <td><?= htmlspecialchars(getReportDesc($dta['reptype'], 'formtype'), ENT_QUOTES, 'UTF-8') ?></td>
                        <td><?= htmlspecialchars($date, ENT_QUOTES, 'UTF-8') ?></td>
                        <td><?= htmlspecialchars($result, ENT_QUOTES, 'UTF-8') ?></td>
                        <td class="text-end">
                            <a href="index.php?t=includes/master&p=formgen.php&mode=continue&formnumber=<?= urlencode((string)$dta['reptype']) ?>&repnumber=<?= urlencode((string)$dta['repnumber']) ?>&data=<?= (int)$dta['clientnumber'] ?>|<?= (int)$dta['locnumber'] ?>|<?= (int)$dta['itemnumber'] ?>&savemode=edit"
                                class="btn btn-secondary btn-sm" data-mdb-tooltip-init data-mdb-placement="bottom"
                                data-mdb-trigger="hover" title="Edit Report">
                                <i class="fad fa-pencil"></i>
                            </a>
                            <a href="javascript:void(0)" onclick="removeRep('<?= (int)$dta['repitem'] ?>')"
                                class="btn btn-danger btn-sm ms-2" data-mdb-tooltip-init data-mdb-placement="bottom"
                                data-mdb-trigger="hover" title="Delete Report">
                                <i class="fad fa-trash"></i>
                            </a>
                        </td>
                    </tr>
                <?php }
                if ($currentSurveyor !== null) {
                    echo '</tbody></table></div>';
                }
            } ?>
        </div>
    </div>
</div>
<script>
function removeRep(r) {
    var dest = '<p class="text-center">Are you sure you wish to remove this incomplete report?</p>';
    loadModalContent(dest, "killBox", "modal-xl", 1060, "true", "Remove incomplete report", 'cancelConfirm', () =>
        confirmRemove(r));
}

function confirmRemove(r) {
    $.post('<?= ROOT_URL ?>/includes/master/items.php', {
        mode: 'removeReport',
        id: r,
        tenant: TENANT_URL
    }, function(ret) {
        $("#R" + r).fadeOut();
        showResponse('success', 'Report removed from the system successfully');
        killModal('killBox');
    });
}

document.getElementById('navBox').innerHTML = '<li class="breadcrumb-item active"><?= addslashes(htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8')) ?></li>';
</script>
