<?php
require_once __DIR__ . '/common.php';

$api = enrep_api_require_key();
$clientnumber = enrep_request_int('clientnumber', 0);
$itemnumber = enrep_request_int('itemnumber', 0);
$locnumber = enrep_request_int('locnumber', 0);
$repnumber = enrep_request_string('repnumber', '', 30);
$includeReportData = enrep_request_int('include_report_data', 0) === 1;
$page = enrep_api_page();
$limit = (int)$page['per_page'];
$offset = (int)$page['offset'];
$dateSql = '';
$dateSql .= enrep_api_unix_exact_date_filter('r.`insdate`', 'examination_date');
$dateSql .= enrep_api_unix_exact_date_filter('r.`nextDate`', 'next_examination_due_date');
$dateSql .= enrep_api_unix_exact_date_filter('r.`repdate`', 'report_created_date');
$dateSql .= enrep_api_unix_date_filter('r.`insdate`', 'examination_from', 'examination_to');
$dateSql .= enrep_api_unix_date_filter('r.`nextDate`', 'next_examination_due_from', 'next_examination_due_to');
$dateSql .= enrep_api_unix_date_filter('r.`repdate`', 'report_created_from', 'report_created_to');

$rows = [];
if ($repnumber !== '' && $clientnumber > 0) {
    $stmt = $GLOBALS['con']->prepare("
        SELECT r.`repitem`, r.`repnumber`, r.`master_report_id`, r.`repnumberold`, r.`olddate`, r.`insdate`,
               r.`nextDate`, r.`repdate`, r.`delivery`, r.`clientnumber`, r.`itemnumber`, r.`esname`,
               r.`frequency`, r.`reptype`, r.`result`, r.`report_pdf_options`, r.`reportdata`,
               i.`desc` AS asset_description, i.`plantnumber`, i.`serialnumber`, i.`locnumber`
        FROM `reportitems` r
        INNER JOIN `itemdetails` i ON i.`itemnumber` = r.`itemnumber` AND i.`clientnumber` = r.`clientnumber`
        WHERE r.`clientnumber`=? AND r.`repnumber`=? $dateSql
        LIMIT 1
    ");
    if (!$stmt) {
        enrep_api_fail(500, 'Report lookup unavailable');
    }
    $stmt->bind_param('is', $clientnumber, $repnumber);
} elseif ($repnumber !== '') {
    $stmt = $GLOBALS['con']->prepare("
        SELECT r.`repitem`, r.`repnumber`, r.`master_report_id`, r.`repnumberold`, r.`olddate`, r.`insdate`,
               r.`nextDate`, r.`repdate`, r.`delivery`, r.`clientnumber`, r.`itemnumber`, r.`esname`,
               r.`frequency`, r.`reptype`, r.`result`, r.`report_pdf_options`, r.`reportdata`,
               i.`desc` AS asset_description, i.`plantnumber`, i.`serialnumber`, i.`locnumber`
        FROM `reportitems` r
        INNER JOIN `itemdetails` i ON i.`itemnumber` = r.`itemnumber` AND i.`clientnumber` = r.`clientnumber`
        WHERE r.`repnumber`=? $dateSql
        LIMIT 1
    ");
    if (!$stmt) {
        enrep_api_fail(500, 'Report lookup unavailable');
    }
    $stmt->bind_param('s', $repnumber);
} elseif ($itemnumber > 0 && $clientnumber > 0) {
    $stmt = $GLOBALS['con']->prepare("
        SELECT r.`repitem`, r.`repnumber`, r.`master_report_id`, r.`repnumberold`, r.`olddate`, r.`insdate`,
               r.`nextDate`, r.`repdate`, r.`delivery`, r.`clientnumber`, r.`itemnumber`, r.`esname`,
               r.`frequency`, r.`reptype`, r.`result`, r.`report_pdf_options`, r.`reportdata`,
               i.`desc` AS asset_description, i.`plantnumber`, i.`serialnumber`, i.`locnumber`
        FROM `reportitems` r
        INNER JOIN `itemdetails` i ON i.`itemnumber` = r.`itemnumber` AND i.`clientnumber` = r.`clientnumber`
        WHERE r.`clientnumber`=? AND r.`itemnumber`=? $dateSql
        ORDER BY r.`insdate` DESC, r.`repitem` DESC
        LIMIT ? OFFSET ?
    ");
    if (!$stmt) {
        enrep_api_fail(500, 'Report lookup unavailable');
    }
    $stmt->bind_param('iiii', $clientnumber, $itemnumber, $limit, $offset);
} elseif ($itemnumber > 0) {
    $stmt = $GLOBALS['con']->prepare("
        SELECT r.`repitem`, r.`repnumber`, r.`master_report_id`, r.`repnumberold`, r.`olddate`, r.`insdate`,
               r.`nextDate`, r.`repdate`, r.`delivery`, r.`clientnumber`, r.`itemnumber`, r.`esname`,
               r.`frequency`, r.`reptype`, r.`result`, r.`report_pdf_options`, r.`reportdata`,
               i.`desc` AS asset_description, i.`plantnumber`, i.`serialnumber`, i.`locnumber`
        FROM `reportitems` r
        INNER JOIN `itemdetails` i ON i.`itemnumber` = r.`itemnumber` AND i.`clientnumber` = r.`clientnumber`
        WHERE r.`itemnumber`=? $dateSql
        ORDER BY r.`insdate` DESC, r.`repitem` DESC
        LIMIT ? OFFSET ?
    ");
    if (!$stmt) {
        enrep_api_fail(500, 'Report lookup unavailable');
    }
    $stmt->bind_param('iii', $itemnumber, $limit, $offset);
} elseif ($locnumber > 0 && $clientnumber > 0) {
    $stmt = $GLOBALS['con']->prepare("
        SELECT r.`repitem`, r.`repnumber`, r.`master_report_id`, r.`repnumberold`, r.`olddate`, r.`insdate`,
               r.`nextDate`, r.`repdate`, r.`delivery`, r.`clientnumber`, r.`itemnumber`, r.`esname`,
               r.`frequency`, r.`reptype`, r.`result`, r.`report_pdf_options`, r.`reportdata`,
               i.`desc` AS asset_description, i.`plantnumber`, i.`serialnumber`, i.`locnumber`
        FROM `reportitems` r
        INNER JOIN `itemdetails` i ON i.`itemnumber` = r.`itemnumber` AND i.`clientnumber` = r.`clientnumber`
        WHERE r.`clientnumber`=? AND i.`locnumber`=? $dateSql
        ORDER BY r.`insdate` DESC, r.`repitem` DESC
        LIMIT ? OFFSET ?
    ");
    if (!$stmt) {
        enrep_api_fail(500, 'Report lookup unavailable');
    }
    $stmt->bind_param('iiii', $clientnumber, $locnumber, $limit, $offset);
} elseif ($locnumber > 0) {
    $stmt = $GLOBALS['con']->prepare("
        SELECT r.`repitem`, r.`repnumber`, r.`master_report_id`, r.`repnumberold`, r.`olddate`, r.`insdate`,
               r.`nextDate`, r.`repdate`, r.`delivery`, r.`clientnumber`, r.`itemnumber`, r.`esname`,
               r.`frequency`, r.`reptype`, r.`result`, r.`report_pdf_options`, r.`reportdata`,
               i.`desc` AS asset_description, i.`plantnumber`, i.`serialnumber`, i.`locnumber`
        FROM `reportitems` r
        INNER JOIN `itemdetails` i ON i.`itemnumber` = r.`itemnumber` AND i.`clientnumber` = r.`clientnumber`
        WHERE i.`locnumber`=? $dateSql
        ORDER BY r.`insdate` DESC, r.`repitem` DESC
        LIMIT ? OFFSET ?
    ");
    if (!$stmt) {
        enrep_api_fail(500, 'Report lookup unavailable');
    }
    $stmt->bind_param('iii', $locnumber, $limit, $offset);
} elseif ($clientnumber > 0) {
    $stmt = $GLOBALS['con']->prepare("
        SELECT r.`repitem`, r.`repnumber`, r.`master_report_id`, r.`repnumberold`, r.`olddate`, r.`insdate`,
               r.`nextDate`, r.`repdate`, r.`delivery`, r.`clientnumber`, r.`itemnumber`, r.`esname`,
               r.`frequency`, r.`reptype`, r.`result`, r.`report_pdf_options`, r.`reportdata`,
               i.`desc` AS asset_description, i.`plantnumber`, i.`serialnumber`, i.`locnumber`
        FROM `reportitems` r
        INNER JOIN `itemdetails` i ON i.`itemnumber` = r.`itemnumber` AND i.`clientnumber` = r.`clientnumber`
        WHERE r.`clientnumber`=? $dateSql
        ORDER BY r.`insdate` DESC, r.`repitem` DESC
        LIMIT ? OFFSET ?
    ");
    if (!$stmt) {
        enrep_api_fail(500, 'Report lookup unavailable');
    }
    $stmt->bind_param('iii', $clientnumber, $limit, $offset);
} else {
    $stmt = $GLOBALS['con']->prepare("
        SELECT r.`repitem`, r.`repnumber`, r.`master_report_id`, r.`repnumberold`, r.`olddate`, r.`insdate`,
               r.`nextDate`, r.`repdate`, r.`delivery`, r.`clientnumber`, r.`itemnumber`, r.`esname`,
               r.`frequency`, r.`reptype`, r.`result`, r.`report_pdf_options`, r.`reportdata`,
               i.`desc` AS asset_description, i.`plantnumber`, i.`serialnumber`, i.`locnumber`
        FROM `reportitems` r
        INNER JOIN `itemdetails` i ON i.`itemnumber` = r.`itemnumber` AND i.`clientnumber` = r.`clientnumber`
        WHERE 1=1 $dateSql
        ORDER BY r.`insdate` DESC, r.`repitem` DESC
        LIMIT ? OFFSET ?
    ");
    if (!$stmt) {
        enrep_api_fail(500, 'Report lookup unavailable');
    }
    $stmt->bind_param('ii', $limit, $offset);
}

$stmt->execute();
$result = $stmt->get_result();
$stmt->close();

while ($row = mysqli_fetch_assoc($result)) {
    $item = [
        'repnumber' => enrep_api_nullable_string($row['repnumber'] ?? ''),
        'master_report_id' => enrep_api_nullable_string($row['master_report_id'] ?? ''),
        'previous_report_number' => enrep_api_nullable_string($row['repnumberold'] ?? ''),
        'previous_examination_date' => enrep_api_date($row['olddate'] ?? ''),
        'examination_date' => enrep_api_date($row['insdate'] ?? ''),
        'next_examination_due_date' => enrep_api_date($row['nextDate'] ?? ''),
        'report_created_date' => enrep_api_date($row['repdate'] ?? ''),
        'delivery_status' => (int)($row['delivery'] ?? 0),
        'clientnumber' => (int)$row['clientnumber'],
        'itemnumber' => (int)$row['itemnumber'],
        'locnumber' => (int)($row['locnumber'] ?? 0),
        'asset_description' => enrep_api_nullable_string($row['asset_description'] ?? ''),
        'plant_number' => enrep_api_nullable_string($row['plantnumber'] ?? ''),
        'serial_number' => enrep_api_nullable_string($row['serialnumber'] ?? ''),
        'surveyor_reference' => enrep_api_nullable_string($row['esname'] ?? ''),
        'examination_frequency' => enrep_api_nullable_string($row['frequency'] ?? ''),
        'report_type' => enrep_api_nullable_string($row['reptype'] ?? ''),
        'examination_result' => enrep_api_nullable_string($row['result'] ?? ''),
    ];

    if ($includeReportData) {
        $item['report_data'] = enrep_api_report_data($row['reportdata'] ?? '');
    }

    $rows[] = $item;
}

enrep_api_json([
    'ok' => true,
    'data' => $repnumber !== '' ? ($rows[0] ?? null) : $rows,
    'meta' => $repnumber !== '' ? null : enrep_api_meta($page, count($rows)),
]);
