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

$tenant = "alanboswell.enrep.co.uk";

foreach ([
    __DIR__ . '/../../../' . $tenant . '/config.php',
    __DIR__ . '/../../../config.php',
    '/config.php',
] as $configPath) {
    if (!defined('CONFIG_LOADED') && is_file($configPath)) {
        require_once $configPath;
    }
}

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    enrep_fail(400, 'Tenant config not found');
}
enrep_require_admin();

$action = enrep_request_enum('action', ['rebuild', ''], '');
if ($action === 'rebuild') {
    $clientnumber = enrep_request_int('clientnumber');
    $repnumber = enrep_request_int('repnumber');
    $items = enrep_request_int('items');
    $form = enrep_request_int('form');

    if ($clientnumber < 1 || $repnumber < 1 || $items < 1) {
        enrep_fail(400, 'Invalid report');
    }

    $_REQUEST['tenant'] = $tenant;
    $_REQUEST['clientnumber'] = (string)$clientnumber;
    $_REQUEST['repnumber'] = (string)$repnumber;
    $_REQUEST['items'] = (string)$items;
    $_REQUEST['forceGen'] = 'yes';
    if ($form > 0) {
        $_REQUEST['form'] = (string)$form;
    }

    require_once __DIR__ . '/genPDF2.php';
    exit;
}

$limit = enrep_request_int('limit', 0);
$reptypeInput = strtolower(trim((string)($_REQUEST['reptype'] ?? 'all')));
$targetReptype = 0;
if ($reptypeInput !== '' && $reptypeInput !== 'all') {
    if (!preg_match('/^[0-9]+$/', $reptypeInput)) {
        enrep_fail(400, 'Invalid report type');
    }
    $targetReptype = (int)$reptypeInput;
    if ($targetReptype < 1) {
        enrep_fail(400, 'Invalid report type');
    }
}

$where = "TRIM(CAST(`repnumber` AS CHAR)) REGEXP '^[0-9]{10}$'";
if ($targetReptype > 0) {
    $where .= " AND ABS(`reptype`) = " . $targetReptype;
}
$sql = "SELECT
            `repnumber`,
            `itemnumber`,
            `clientnumber`,
            `reptype`,
            MAX(ABS(`insdate`)) AS `latest_insdate`
        FROM `reportitems`
        WHERE {$where}
        GROUP BY `repnumber`, `itemnumber`, `clientnumber`, `reptype`
        ORDER BY ABS(`repnumber`) ASC, ABS(`itemnumber`) ASC";
if ($limit > 0) {
    $sql .= " LIMIT " . $limit;
}

$result = mysqli_query($GLOBALS['con'], $sql) or die(mysqli_error($GLOBALS['con']));
$reports = [];
while ($row = mysqli_fetch_assoc($result)) {
    $reports[] = [
        'repnumber' => (string)$row['repnumber'],
        'items' => (string)$row['itemnumber'],
        'clientnumber' => (string)$row['clientnumber'],
        'form' => (string)$row['reptype'],
        'latest_insdate' => (string)$row['latest_insdate'],
    ];
}

$tenantLabel = trim((string)(defined('TENANT_URL') ? TENANT_URL : $tenant), '/');
$targetLabel = $targetReptype > 0 ? (string)$targetReptype : 'all';
$targetDescription = $targetReptype > 0 ? 'report type ' . $targetLabel : 'all report types';
$reportsJson = json_encode($reports, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Force Rebuild Reports</title>
    <style>
        body {
            margin: 0;
            padding: 24px;
            color: #172033;
            background: #f4f6f8;
            font-family: Arial, Helvetica, sans-serif;
        }
        main {
            max-width: 1100px;
            margin: 0 auto;
        }
        h1 {
            margin: 0 0 6px;
            font-size: 26px;
            font-weight: 700;
        }
        p {
            margin: 0 0 16px;
            color: #536073;
        }
        .toolbar,
        .log {
            border: 1px solid #d9e0e8;
            border-radius: 6px;
            background: #fff;
            padding: 16px;
        }
        .toolbar {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 12px;
            margin-bottom: 16px;
        }
        .filter-form {
            display: flex;
            flex-wrap: wrap;
            align-items: flex-end;
            gap: 10px;
        }
        button {
            min-height: 38px;
            border: 0;
            border-radius: 4px;
            padding: 0 14px;
            color: #fff;
            background: #0f5f8f;
            font-weight: 700;
            cursor: pointer;
        }
        button[disabled] {
            cursor: not-allowed;
            opacity: .55;
        }
        label {
            display: inline-flex;
            flex-direction: column;
            gap: 4px;
            color: #536073;
            font-size: 12px;
            font-weight: 700;
            text-transform: uppercase;
        }
        input {
            width: 120px;
            min-height: 38px;
            box-sizing: border-box;
            border: 1px solid #c8d2df;
            border-radius: 4px;
            padding: 0 10px;
            color: #172033;
            background: #fff;
            font: 14px Arial, Helvetica, sans-serif;
        }
        .secondary {
            color: #1f2a3a;
            background: #e5ebf1;
        }
        .meter {
            flex: 1 1 260px;
            height: 12px;
            overflow: hidden;
            border-radius: 999px;
            background: #e5ebf1;
        }
        .bar {
            width: 0;
            height: 100%;
            background: #1b8a5a;
            transition: width .2s ease;
        }
        .status {
            min-width: 190px;
            font-weight: 700;
        }
        .log {
            height: 520px;
            overflow: auto;
            font: 13px/1.45 Consolas, "Courier New", monospace;
            white-space: pre-wrap;
        }
        .ok {
            color: #146c43;
        }
        .fail {
            color: #b42318;
        }
        .muted {
            color: #697586;
        }
    </style>
</head>
<body>
<main>
    <h1>Force Rebuild Reports</h1>
    <p>Tenant: <strong><?= htmlspecialchars($tenantLabel, ENT_QUOTES, 'UTF-8') ?></strong>. Found <strong><?= count($reports) ?></strong> report item PDFs for <strong><?= htmlspecialchars($targetDescription, ENT_QUOTES, 'UTF-8') ?></strong> where the report number is exactly 10 digits.</p>

    <div class="toolbar">
        <form method="get" class="filter-form">
            <label for="reptype">Report type
                <input type="text" id="reptype" name="reptype" value="<?= htmlspecialchars($targetLabel, ENT_QUOTES, 'UTF-8') ?>" placeholder="all or number">
            </label>
            <?php if ($limit > 0): ?>
                <input type="hidden" name="limit" value="<?= (int)$limit ?>">
            <?php endif; ?>
            <button type="submit" class="secondary">Apply</button>
        </form>
        <button type="button" id="startBtn"<?= empty($reports) ? ' disabled' : '' ?>>Start rebuild</button>
        <button type="button" id="pauseBtn" class="secondary" disabled>Pause</button>
        <button type="button" id="clearBtn" class="secondary">Clear log</button>
        <div class="meter" aria-hidden="true"><div class="bar" id="bar"></div></div>
        <div class="status" id="status">0 / <?= count($reports) ?></div>
    </div>

    <div id="log" class="log" aria-live="polite"></div>
</main>

<script>
const reports = <?= $reportsJson ?: '[]' ?>;
let index = 0;
let running = false;
let paused = false;
let okCount = 0;
let failCount = 0;

const startBtn = document.getElementById('startBtn');
const pauseBtn = document.getElementById('pauseBtn');
const clearBtn = document.getElementById('clearBtn');
const statusEl = document.getElementById('status');
const barEl = document.getElementById('bar');
const logEl = document.getElementById('log');

function logLine(text, cls) {
    const div = document.createElement('div');
    div.className = cls || '';
    div.textContent = text;
    logEl.appendChild(div);
    logEl.scrollTop = logEl.scrollHeight;
}

function updateStatus() {
    const total = reports.length;
    const percent = total > 0 ? Math.round((index / total) * 100) : 0;
    statusEl.textContent = `${index} / ${total} rebuilt, ${okCount} ok, ${failCount} failed`;
    barEl.style.width = `${percent}%`;
}

async function rebuildNext() {
    if (!running || paused) {
        return;
    }

    if (index >= reports.length) {
        running = false;
        startBtn.disabled = reports.length === 0;
        pauseBtn.disabled = true;
        pauseBtn.textContent = 'Pause';
        logLine(`Done. ${okCount} rebuilt, ${failCount} failed.`, failCount > 0 ? 'fail' : 'ok');
        return;
    }

    const report = reports[index];
    const current = index + 1;
    const params = new URLSearchParams({
        action: 'rebuild',
        clientnumber: report.clientnumber,
        repnumber: report.repnumber,
        items: report.items,
        form: report.form,
        forceGen: 'yes'
    });

    logLine(`[${current}/${reports.length}] Rebuilding report ${report.repnumber}, item ${report.items}, client ${report.clientnumber}...`, 'muted');

    try {
        const response = await fetch(`force_rebuild_reports.php?${params.toString()}`, {
            credentials: 'same-origin',
            cache: 'no-store'
        });
        const text = await response.text();
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${text.trim().slice(0, 300)}`);
        }
        okCount++;
        logLine(`OK ${report.repnumber}_${report.items}: ${text.trim()}`, 'ok');
    } catch (error) {
        failCount++;
        logLine(`FAILED ${report.repnumber}_${report.items}: ${error.message}`, 'fail');
    }

    index++;
    updateStatus();
    window.setTimeout(rebuildNext, 150);
}

startBtn.addEventListener('click', () => {
    if (index >= reports.length) {
        index = 0;
        okCount = 0;
        failCount = 0;
    }
    running = true;
    paused = false;
    startBtn.disabled = true;
    pauseBtn.disabled = false;
    pauseBtn.textContent = 'Pause';
    updateStatus();
    rebuildNext();
});

pauseBtn.addEventListener('click', () => {
    paused = !paused;
    pauseBtn.textContent = paused ? 'Resume' : 'Pause';
    if (!paused) {
        rebuildNext();
    }
});

clearBtn.addEventListener('click', () => {
    logEl.textContent = '';
});

updateStatus();
logLine(`Ready. ${reports.length} report item PDFs queued for <?= htmlspecialchars($targetDescription, ENT_QUOTES, 'UTF-8') ?>.`, 'muted');
</script>
</body>
</html>
