<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/zone.php';
require_login();

if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); }
$pdo = db();
$user = current_user() ?? [];
$userId = isset($user['id']) && (int)$user['id'] > 0 ? (int)$user['id'] : null;
$role = strtoupper((string)($user['role'] ?? current_user_role() ?? ''));
$zoneId = current_user_zone_id();
$isSuperAdmin = $role === 'SUPERADMIN';

function ot_e($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function ot_num(string $s): ?float {
    $s = trim(str_replace(',', '.', $s));
    return is_numeric($s) ? (float)$s : null;
}
function ot_norm(string $s): string {
    $s = str_replace(["\xC2\xA0", "\r"], [' ', "\n"], $s);
    $s = preg_replace('/[ \t]+/u', ' ', $s) ?? $s;
    return trim($s);
}
function ot_values_after_label(array $lines, array $labels, string $unit=''): ?float {
    foreach ($lines as $i => $line) {
        $n = mb_strtolower(trim($line), 'UTF-8');
        foreach ($labels as $label) {
            if ($n === mb_strtolower($label, 'UTF-8') || $n === mb_strtolower($label.' '.$unit, 'UTF-8')) {
                for ($j=$i+1; $j<min(count($lines), $i+8); $j++) {
                    $candidate = trim($lines[$j]);
                    if (preg_match('/^-?\d+(?:[.,]\d+)?(?:\s*(?:km|dB|nm|m|dB\/km))?$/iu', $candidate, $m)) {
                        if (preg_match('/-?\d+(?:[.,]\d+)?/', $candidate, $numm)) return ot_num($numm[0]);
                    }
                }
            }
        }
    }
    return null;
}
function ot_extract_values(array $lines, array $labels): array {
    foreach ($lines as $i=>$line) {
        $n = mb_strtolower(trim($line), 'UTF-8');
        foreach ($labels as $label) {
            if ($n === mb_strtolower($label, 'UTF-8')) {
                $vals = [];
                for ($j=$i+1; $j<count($lines); $j++) {
                    $v=trim($lines[$j]);
                    if ($v === '' || preg_match('/^[A-Za-z][A-Za-z \\/()_-]*$/u', $v)) break;
                    if (preg_match('/^-?\d+(?:[.,]\d+)?$/u', $v)) $vals[]=(float)str_replace(',','.',$v);
                    if (count($vals)>300) break;
                }
                if ($vals) return $vals;
            }
        }
    }
    return [];
}
function ot_ocr_pdf(string $tmp, string $key): array {
    if (!function_exists('curl_init')) return ['error'=>'PHP cURL tidak tersedia pada hosting.'];
    $ch = curl_init('https://api.ocr.space/parse/image');
    $post = [
        'apikey'=>$key, 'language'=>'eng', 'isOverlayRequired'=>'false',
        'detectOrientation'=>'true', 'scale'=>'true', 'OCREngine'=>'2',
        'file'=>new CURLFile($tmp,'application/pdf','otdr.pdf')
    ];
    curl_setopt_array($ch, [
        CURLOPT_POST=>true, CURLOPT_POSTFIELDS=>$post, CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_CONNECTTIMEOUT=>20, CURLOPT_TIMEOUT=>120
    ]);
    $response=curl_exec($ch); $err=curl_error($ch); $http=(int)curl_getinfo($ch,CURLINFO_HTTP_CODE); curl_close($ch);
    if (!is_string($response)) return ['error'=>'Sambungan OCR gagal: '.$err];
    $data=json_decode($response,true);
    if ($http<200 || $http>=300 || !is_array($data)) return ['error'=>'OCR service tidak memberi respons yang sah (HTTP '.$http.').'];
    if (!empty($data['IsErroredOnProcessing'])) return ['error'=>'OCR gagal: '.implode('; ',(array)($data['ErrorMessage']??['Tidak diketahui']))];
    $text='';
    foreach (($data['ParsedResults']??[]) as $page) $text.="\n".(string)($page['ParsedText']??'');
    if (trim($text)==='') return ['error'=>'OCR tidak dapat membaca teks daripada PDF ini.'];
    return ['text'=>$text];
}

$routes=[];
try {
    if ($isSuperAdmin) {
        $routes=$pdo->query("SELECT id,route_name FROM routes WHERE status='ACTIVE' ORDER BY route_name")->fetchAll(PDO::FETCH_ASSOC);
    } elseif ($zoneId !== null && (int)$zoneId>0) {
        $st=$pdo->prepare("SELECT id,route_name FROM routes WHERE zone_id=? AND status='ACTIVE' ORDER BY route_name");
        $st->execute([(int)$zoneId]); $routes=$st->fetchAll(PDO::FETCH_ASSOC);
    }
} catch(Throwable $e) { $routes=[]; }

$configPath=__DIR__.'/../config/ocr_config.php';
$ocrCfg=is_file($configPath)?require $configPath:[];
$apiKey=trim((string)($ocrCfg['api_key']??''));
$error=''; $success=''; $preview=null; $selectedRoute=(int)($_POST['route_id']??$_GET['route_id']??0);
$selectedCore=(int)($_POST['core_id']??0); $cores=[];
if ($selectedRoute>0) {
    $allowedRoute=false;
    foreach($routes as $r) if((int)$r['id']===$selectedRoute) $allowedRoute=true;
    if($allowedRoute) {
        $st=$pdo->prepare("SELECT id,core_no FROM fiber_cores WHERE route_id=? ORDER BY core_no");
        $st->execute([$selectedRoute]); $cores=$st->fetchAll(PDO::FETCH_ASSOC);
    }
}

$action=(string)($_POST['action']??'');
if ($_SERVER['REQUEST_METHOD']==='POST' && $action==='save') {
    $token=(string)($_POST['preview_token']??'');
    $savedPreview=$_SESSION['otdr_preview'][$token]??null;
    $length=ot_num((string)($_POST['fiber_length_km']??''));
    $totalLoss=ot_num((string)($_POST['total_loss_db']??''));
    if (!$savedPreview || !preg_match('/^[a-f0-9]{32}$/',$token)) {
        $error='Preview sudah tamat atau tidak sah. Jalankan OCR & Preview semula.';
    } elseif ($length===null || $length<=0 || $length>1000 || $totalLoss===null || $totalLoss<0 || $totalLoss>1000) {
        $error='Total Length dan Total Loss mesti nombor yang sah. Betulkan nilai berdasarkan PDF asal.';
    } elseif (empty($savedPreview['events']) || count($savedPreview['events'])>300) {
        $error='Tiada event sah untuk disimpan.';
    } else {
        $events=$savedPreview['events'];
        $lastDistance=(float)$events[count($events)-1]['distance'];
        if (abs($lastDistance-$length)>0.15) {
            $error='Tidak boleh simpan: Total Length mesti hampir sama dengan jarak event terakhir. Semak nilai pada PDF.';
        } else {
            $routeId=(int)$savedPreview['route_id']; $coreId=(int)$savedPreview['core_id'];
            $routeAllowed=false;
            foreach($routes as $r) if((int)$r['id']===$routeId) $routeAllowed=true;
            $coreCheck=$pdo->prepare("SELECT fc.id,fc.route_id,fc.core_no FROM fiber_cores fc WHERE fc.id=? AND fc.route_id=?");
            $coreCheck->execute([$coreId,$routeId]); $coreRow=$coreCheck->fetch(PDO::FETCH_ASSOC);
            if (!$routeAllowed || !$coreRow) {
                $error='Route/Core tidak lagi sah atau akses Zone tidak dibenarkan.';
            } else {
                $hash=(string)$savedPreview['file_hash'];
                $marker='[OTDR_IMPORT_SHA256:'.$hash.']';
                try {
                    $dupe=$pdo->prepare("SELECT ct.id FROM core_tests ct JOIN test_sessions ts ON ts.id=ct.session_id WHERE ct.core_id=? AND ts.route_id=? AND ts.session_remark LIKE ? LIMIT 1");
                    $dupe->execute([$coreId,$routeId,'%'.$marker.'%']);
                    if ($dupe->fetchColumn()) {
                        $error='PDF yang sama sudah pernah diimport untuk core ini. Tiada rekod baharu dibuat.';
                    } else {
                        $pdo->beginTransaction();
                        $testDate=(string)($savedPreview['test_date']??date('Y-m-d'));
                        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/',$testDate)) $testDate=date('Y-m-d');
                        $wave=$savedPreview['wavelength'] ? (int)$savedPreview['wavelength'] : null;
                        $sessionRemark='OTDR PDF import: '.(string)$savedPreview['name'].'; Wavelength: '.($wave!==null?$wave.' nm':'not detected').'; '.$marker;
                        $insSession=$pdo->prepare("INSERT INTO test_sessions (route_id,taken_by,test_date,direction,equipment,session_remark) VALUES (?,?,?,?,?,?)");
                        $insSession->execute([$routeId,$userId,$testDate,'PDF report','FC3200 / OTDR PDF',$sessionRemark]);
                        $sessionId=(int)$pdo->lastInsertId();
                        $testRemark='Imported from PDF '.$savedPreview['name'].'; wavelength='.($wave!==null?$wave.' nm':'unknown').'; sha256='.$hash;
                        $insTest=$pdo->prepare("INSERT INTO core_tests (session_id,core_id,fiber_length_km,total_loss_db,pm_1310_dbm,pm_1550_dbm,remark) VALUES (?,?,?,?,?,?,?)");
                        $insTest->execute([$sessionId,$coreId,$length,$totalLoss,null,null,$testRemark]);
                        $testId=(int)$pdo->lastInsertId();
                        $threshold=1.0;
                        try { $q=$pdo->prepare("SELECT setting_value FROM settings WHERE setting_key='high_loss_threshold_db' LIMIT 1"); $q->execute(); $v=$q->fetchColumn(); if(is_numeric($v)) $threshold=(float)$v; } catch(Throwable $ignore) {}
                        $insEvent=$pdo->prepare("INSERT INTO core_events (core_test_id,event_no,distance_km,loss_db,event_type,status,joint_name,remark) VALUES (?,?,?,?,?,?,?,?)");
                        foreach($events as $ev) {
                            $evLoss=(float)$ev['loss'];
                            $type=$evLoss >= $threshold ? 'HIGH_LOSS' : 'NORMAL';
                            $status=$evLoss >= $threshold ? 'HIGH_LOSS' : 'NORMAL';
                            $reflection=$ev['reflection']===null?'not read':number_format((float)$ev['reflection'],2,'.','').' dB';
                            $sum=number_format((float)$ev['sum'],3,'.','').' dB';
                            $remark='Imported from OTDR PDF; Reflection='.$reflection.'; Sum Loss='.$sum.'; Wavelength='.($wave!==null?$wave.' nm':'unknown');
                            $insEvent->execute([$testId,(int)$ev['no'],(float)$ev['distance'],$evLoss,$type,$status,null,$remark]);
                        }
                        $pdo->commit();
                        unset($_SESSION['otdr_preview'][$token]);
                        $success='Berjaya disimpan: Core '.(int)$coreRow['core_no'].', Total Length '.number_format($length,3).' km, Total Loss '.number_format($totalLoss,3).' dB, '.count($events).' event. Status continuity/core tidak diubah.';
                        $preview=null;
                    }
                } catch(Throwable $e) {
                    if ($pdo->inTransaction()) $pdo->rollBack();
                    error_log('FibreCore OTDR PDF save error: '.$e->getMessage());
                    $error='Simpanan gagal dan transaksi dibatalkan. Semak struktur database/log hosting; tiada rekod separa dikekalkan.';
                }
            }
        }
    }
} elseif ($_SERVER['REQUEST_METHOD']==='POST' && $action!=='save') {
    if ($apiKey==='' || $apiKey==='PASTE_YOUR_OCR_SPACE_API_KEY_HERE') $error='API key OCR belum ditetapkan dalam config/ocr_config.php.';
    elseif (!$selectedRoute || !$selectedCore) $error='Pilih Route dan Core dahulu.';
    else {
        $coreAllowed=false;
        foreach($cores as $c) if((int)$c['id']===$selectedCore) $coreAllowed=true;
        if(!$coreAllowed) $error='Core tidak sepadan dengan route yang dipilih.';
        elseif (!isset($_FILES['otdr_file']) || ($_FILES['otdr_file']['error']??UPLOAD_ERR_NO_FILE)!==UPLOAD_ERR_OK) $error='Pilih satu fail PDF yang sah.';
        elseif (strtolower(pathinfo((string)$_FILES['otdr_file']['name'],PATHINFO_EXTENSION))!=='pdf') $error='Hanya fail PDF disokong.';
        elseif ((int)$_FILES['otdr_file']['size']>10*1024*1024) $error='Saiz PDF maksimum 10 MB.';
        else {
            $finfo=new finfo(FILEINFO_MIME_TYPE); $mime=$finfo->file($_FILES['otdr_file']['tmp_name']);
            if ($mime!=='application/pdf' && $mime!=='application/octet-stream') $error='Fail ini tidak dikenali sebagai PDF.';
            else {
                $hash=hash_file('sha256',$_FILES['otdr_file']['tmp_name']);
                $ocr=ot_ocr_pdf($_FILES['otdr_file']['tmp_name'],$apiKey);
                if(isset($ocr['error'])) $error=$ocr['error'];
                else {
                    $raw=ot_norm($ocr['text']);
                    $lines=array_values(array_filter(array_map('trim',explode("\n",$raw)),static fn($v)=>$v!==''));
                    $length=ot_values_after_label($lines,['Total length','Total Length'],'km');
                    $loss=ot_values_after_label($lines,['Total loss','Total Loss'],'dB');
                    $wave=null; $testDate=null;
                    foreach($lines as $i=>$line) {
                        if(preg_match('/^wave\s*length$/iu',trim($line)) && isset($lines[$i+1]) && preg_match('/(\d{3,4})\s*nm/iu',$lines[$i+1],$m)) $wave=(int)$m[1];
                        if(preg_match('/^(\d{3,4})\s*nm$/iu',trim($line),$m)) $wave=(int)$m[1];
                        if($testDate===null && preg_match('/\b(\d{2})\/(\d{2})\/(\d{4})\s+(\d{1,2}):(\d{2})\b/',$line,$m)) {
                            $d=(int)$m[1];$mo=(int)$m[2];$y=(int)$m[3]; if(checkdate($mo,$d,$y)) $testDate=sprintf('%04d-%02d-%02d',$y,$mo,$d);
                        }
                    }
                    $dist=ot_extract_values($lines,['Distance','Distance (km)']);
                    $losses=ot_extract_values($lines,['Loss','Loss (dB)']);
                    $sums=ot_extract_values($lines,['Sum loss','Sum loss (dB)']);
                    $refs=ot_extract_values($lines,['Reflection','Reflection (dB)']);
                    $count=min(count($dist),count($losses),count($sums));
                    $events=[];
                    for($i=0;$i<$count;$i++) $events[]=['no'=>$i+1,'distance'=>(float)$dist[$i],'loss'=>(float)$losses[$i],'sum'=>(float)$sums[$i],'reflection'=>isset($refs[$i])?(float)$refs[$i]:null];
                    $warnings=[];
                    if($length===null) $warnings[]='Total Length tidak dikenal pasti automatik; masukkan nilai yang tertera pada PDF.';
                    if($loss===null) $warnings[]='Total Loss tidak dikenal pasti automatik; masukkan nilai yang tertera pada PDF.';
                    if($wave===null) $warnings[]='Wavelength tidak dikenal pasti.';
                    if(!$count) $warnings[]='Kolum event belum dapat dipadankan.';
                    if(count($dist)!==count($losses)||count($dist)!==count($sums)) $warnings[]='Bilangan nilai Distance, Loss dan Sum Loss tidak sepadan.';
                    if($count && $length!==null && abs((float)$length-(float)$dist[$count-1])>0.15) $warnings[]='Total Length automatik tidak sepadan dengan jarak event terakhir.';
                    $token=bin2hex(random_bytes(16));
                    $_SESSION['otdr_preview'][$token]=[
                        'name'=>basename((string)$_FILES['otdr_file']['name']),'file_hash'=>$hash,
                        'route_id'=>$selectedRoute,'core_id'=>$selectedCore,'length'=>$length,'total_loss'=>$loss,
                        'wavelength'=>$wave,'events'=>$events,'raw'=>$raw,'warnings'=>$warnings,'test_date'=>$testDate
                    ];
                    $preview=$_SESSION['otdr_preview'][$token];
                    $preview['token']=$token;
                }
            }
        }
    }
}

$pageTitle='Import OTDR PDF'; $currentPage='import_otdr_pdf.php';
require_once __DIR__.'/_header.php';
?>
<div class="content-wrapper"><section class="content-header"><div class="container-fluid"><h1>Import OTDR PDF</h1><p class="text-muted">Satu PDF untuk satu core. Semak dan betulkan ringkasan jika OCR tersalah sebelum simpan.</p></div></section>
<section class="content"><div class="container-fluid">
<?php if($error!==''): ?><div class="alert alert-danger"><?=ot_e($error)?></div><?php endif; ?>
<?php if($success!==''): ?><div class="alert alert-success"><?=ot_e($success)?> <a class="alert-link" href="route_detail.php?id=<?= (int)$selectedRoute ?>">Buka Route Detail</a></div><?php endif; ?>
<div class="alert alert-warning"><strong>Privasi:</strong> PDF dihantar kepada OCR.space untuk diproses. Pastikan dibenarkan oleh organisasi. Import tidak mengubah status FREE/USED/FAULTY atau continuity THROUGH.</div>
<div class="card card-primary"><div class="card-header"><h3 class="card-title">Pilih Route, Core dan PDF</h3></div>
<form method="post" enctype="multipart/form-data"><input type="hidden" name="action" value="preview"><div class="card-body">
<div class="form-group"><label>Route</label><select class="form-control" name="route_id" required onchange="this.form.querySelector('[name=core_id]').value='';this.form.submit()"><option value="">-- Pilih Route --</option><?php foreach($routes as $r): ?><option value="<?= (int)$r['id']?>" <?=$selectedRoute===(int)$r['id']?'selected':''?>><?=ot_e($r['route_name'])?></option><?php endforeach;?></select></div>
<div class="form-group"><label>Core</label><select class="form-control" name="core_id" required><option value="">-- Pilih Core --</option><?php foreach($cores as $c): ?><option value="<?= (int)$c['id']?>" <?=$selectedCore===(int)$c['id']?'selected':''?>>Core <?= (int)$c['core_no']?></option><?php endforeach;?></select></div>
<div class="form-group"><label>Fail PDF OTDR (satu core sahaja)</label><input type="file" name="otdr_file" class="form-control-file" accept=".pdf,application/pdf" required><small class="text-muted">Maksimum 10 MB.</small></div>
</div><div class="card-footer"><button class="btn btn-primary" type="submit">OCR &amp; Preview</button></div></form></div>
<?php if($preview): ?>
<div class="card card-info"><div class="card-header"><h3 class="card-title">Preview — belum disimpan</h3></div><div class="card-body">
<p><strong>Fail:</strong> <?=ot_e($preview['name'])?></p>
<p><strong>Route:</strong> <?php foreach($routes as $r) if((int)$r['id']===(int)$preview['route_id']) echo ot_e($r['route_name']); ?> · <strong>Core:</strong> <?php foreach($cores as $c) if((int)$c['id']===(int)$preview['core_id']) echo (int)$c['core_no']; ?></p>
<div class="alert alert-info">Semak nilai Total Length dan Total Loss dengan PDF asal. Jika OCR menunjukkan nilai salah (contohnya 0.400), betulkan pada kotak di bawah sebelum simpan. Jarak event terakhir mesti hampir sama dengan Total Length.</div>
<form method="post"><input type="hidden" name="action" value="save"><input type="hidden" name="preview_token" value="<?=ot_e($preview['token']??'')?>"><input type="hidden" name="route_id" value="<?=(int)$preview['route_id']?>"><input type="hidden" name="core_id" value="<?=(int)$preview['core_id']?>">
<div class="row">
<div class="col-md-3 form-group"><label>Total Length (km)</label><input class="form-control" type="number" step="0.001" min="0.001" max="1000" name="fiber_length_km" value="<?= $preview['length']===null?'':ot_e(number_format((float)$preview['length'],3,'.','')) ?>" required></div>
<div class="col-md-3 form-group"><label>Total Loss (dB)</label><input class="form-control" type="number" step="0.001" min="0" max="1000" name="total_loss_db" value="<?= $preview['total_loss']===null?'':ot_e(number_format((float)$preview['total_loss'],3,'.','')) ?>" required></div>
<div class="col-md-3 form-group"><label>Wavelength</label><input class="form-control" value="<?= $preview['wavelength']===null?'Tidak dikesan':(int)$preview['wavelength'].' nm' ?>" readonly></div>
<div class="col-md-3 form-group"><label>Event dibaca</label><input class="form-control" value="<?=count($preview['events'])?>" readonly></div>
</div>
<?php if(!empty($preview['warnings'])): ?><div class="alert alert-warning"><strong>Semak OCR:</strong><ul><?php foreach($preview['warnings'] as $w): ?><li><?=ot_e($w)?></li><?php endforeach;?></ul></div><?php endif;?>
<div class="table-responsive"><table class="table table-sm table-striped table-bordered"><thead><tr><th>Event</th><th>Distance (km)</th><th>Loss (dB)</th><th>Reflection (dB)</th><th>Sum Loss (dB)</th></tr></thead><tbody><?php foreach($preview['events'] as $ev): ?><tr><td><?=(int)$ev['no']?></td><td><?=ot_e(number_format((float)$ev['distance'],3,'.',''))?></td><td><?=ot_e(number_format((float)$ev['loss'],3,'.',''))?></td><td><?=$ev['reflection']===null?'—':ot_e(number_format((float)$ev['reflection'],2,'.',''))?></td><td><?=ot_e(number_format((float)$ev['sum'],3,'.',''))?></td></tr><?php endforeach;?></tbody></table></div>
<?php if(count($preview['events'])>0): ?><button class="btn btn-success" type="submit" onclick="return confirm('Simpan bacaan OTDR dan semua event untuk core yang dipilih? Status continuity tidak akan diubah.')"><i class="fas fa-save"></i> Simpan OTDR &amp; Semua Event</button><?php else: ?><div class="alert alert-danger">Tiada event dibaca; tidak boleh simpan.</div><?php endif;?>
</form>
<details class="mt-3"><summary>Tek OCR mentah</summary><pre style="max-height:350px;overflow:auto;white-space:pre-wrap"><?=ot_e($preview['raw'])?></pre></details>
</div></div>
<?php endif;?>
</div></section></div>
<?php require_once __DIR__.'/_footer.php'; ?>
