<?php
require_once __DIR__ . '/../../functions/security.php';

$tenant = enrep_tenant_segment($_REQUEST['tenant'] ?? (defined('TENANT_URL') ? TENANT_URL : ''));
if ($tenant !== '' && file_exists('../../../' . $tenant . '/config.php')) {
    require_once('../../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

require_once __DIR__ . '/../asset/asset_functions.php';
require_once __DIR__ . '/inspection_reports_functions.php';

$context = enrep_inspection_report_context($_REQUEST);
$startTs = $context['startTs'];
$endTs = $context['endTs'];
$mode = $context['mode'];
$view = ((string)($_REQUEST['view'] ?? 'clients') === 'items') ? 'items' : 'clients';
$export = trim((string)($_GET['inspection_export'] ?? 'csv'));

if ($startTs === null || $endTs === null || $startTs > $endTs) {
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Invalid date range';
    exit;
}

$title = ($mode === 'done') ? 'Inspections Carried Out' : 'Inspections To Be Done';
$period = $context['start'] . ' - ' . $context['end'];

if ($view === 'items') {
    $rows = enrep_inspection_report_item_rows($context['clientnumber'], $startTs, $endTs, $mode);
    $stmt = $GLOBALS['con']->prepare("SELECT `clientname` FROM `clientdetails` WHERE `clientnumber` = ?");
    $stmt->bind_param("i", $context['clientnumber']);
    $stmt->execute();
    $clientResult = $stmt->get_result();
    $stmt->close();
    $clientName = mysqli_fetch_array($clientResult);
    $title .= ' - ' . ($clientName['clientname'] ?? '');

    if ($export === 'pdf') {
        $html = '<h1>' . enrep_inspection_report_h($title) . '</h1>';
        $html .= '<p>' . enrep_inspection_report_h($period) . '</p>';
        $html .= enrep_inspection_report_render_item_table($rows);
        enrep_inspection_report_export_pdf($html, 'inspection-report-items');
    }

    $csvRows = [];
    foreach ($rows as $row) {
        $csvRows[] = [
            $row['description'],
            $row['plantnumber'],
            $row['serialnumber'],
            getItemLocation($row['itemnumber'], 'name') . ' - ' . getItemLocation($row['itemnumber'], 'postcode'),
            (int)$row['report_date'] > 0 ? date('d-m-Y', (int)$row['report_date']) : '',
        ];
    }
    enrep_inspection_report_export_csv(
        ['Item', 'Plant Number', 'Serial Number', 'Location', 'Date'],
        $csvRows,
        ['Total', count($rows), '', '', ''],
        'inspection-report-items'
    );
}

$rows = enrep_inspection_report_client_rows($startTs, $endTs, $mode);
$totals = enrep_inspection_report_client_totals($rows);

if ($export === 'pdf') {
    $html = '<h1>' . enrep_inspection_report_h($title) . '</h1>';
    $html .= '<p>' . enrep_inspection_report_h($period) . '</p>';
    $html .= enrep_inspection_report_render_client_table($rows, $mode, false);
    enrep_inspection_report_export_pdf($html, 'inspection-report-clients');
}

$csvRows = [];
foreach ($rows as $row) {
    $csvRow = [
        $row['clientname'],
        (int)$row['total_assets'],
        (int)$row['inspections_done'],
    ];
    if ($mode === 'due') {
        $csvRow[] = (int)$row['inspections_due'];
    }
    $csvRows[] = $csvRow;
}

$headers = ['Client', 'Active Assets', 'Inspections Done'];
$footer = ['Total', (int)$totals['total_assets'], (int)$totals['inspections_done']];
if ($mode === 'due') {
    $headers[] = 'Inspections To Do';
    $footer[] = (int)$totals['inspections_due'];
}
enrep_inspection_report_export_csv(
    $headers,
    $csvRows,
    $footer,
    'inspection-report-clients'
);
