<?php
require_once __DIR__ . '/../includes/functions.php';
$admin = require_admin();
$adminTitle = 'Auto Repair';
$report = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    if (isset($_POST['toggle_debug'])) {
        $val = !empty($_POST['debug_mode']) ? '1' : '0';
        q("INSERT INTO mj_settings(setting_key,setting_value) VALUES('debug_mode',?) ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value)", [$val]);
        flash('success', 'Debug mode '.($val==='1'?'enabled':'disabled').'.');
        redirect('auto-repair.php');
    }
    if (isset($_POST['run_repair'])) {
        $report = function_exists('mj428_run_safe_repair') ? mj428_run_safe_repair('admin_auto_repair') : ['error'=>'Auto repair helper not loaded'];
        flash('success', 'Safe repair completed. Tables: '.(int)($report['tables']??0).', Columns: '.(int)($report['columns']??0).', Indexes: '.(int)($report['indexes']??0).'.');
    }
    if (isset($_POST['clear_cache'])) {
        foreach(['mj_page_cache','mj_count_cache','mj_location_cache'] as $t){ try{ if(function_exists('mj428_table_exists') && mj428_table_exists($t)) q('DELETE FROM `'.$t.'`'); }catch(Throwable $e){} }
        flash('success','Cache cleared.'); redirect('auto-repair.php');
    }
}
if (function_exists('mj428_ensure_schema')) { mj428_ensure_schema(); }
$debug = function_exists('mj428_setting_bool') ? mj428_setting_bool('debug_mode', false) : false;
$auto = function_exists('mj428_setting_bool') ? mj428_setting_bool('auto_repair_enabled', true) : true;
$recentErrors = [];
$recentRepairs = [];
try { if (function_exists('mj428_table_exists') && mj428_table_exists('mj_error_logs')) $recentErrors = all_rows('SELECT * FROM mj_error_logs ORDER BY id DESC LIMIT 8'); } catch(Throwable $e) {}
try { if (function_exists('mj428_table_exists') && mj428_table_exists('mj_auto_repair_logs')) $recentRepairs = all_rows('SELECT * FROM mj_auto_repair_logs ORDER BY id DESC LIMIT 8'); } catch(Throwable $e) {}
include __DIR__ . '/_header.php';
?>
<div class="row">
  <div class="col-lg-4">
    <div class="card card-primary card-outline">
      <div class="card-header"><h3 class="card-title"><i class="fas fa-tools mr-2"></i>Safe Auto Repair</h3></div>
      <div class="card-body">
        <p class="text-muted">Repairs missing tables, columns and indexes only. It does not delete data and does not rewrite PHP files.</p>
        <form method="post"><?= csrf_input() ?><button name="run_repair" value="1" class="btn btn-primary btn-block"><i class="fas fa-magic mr-1"></i>Run Safe Repair Now</button></form>
        <hr>
        <form method="post"><?= csrf_input() ?><button name="clear_cache" value="1" class="btn btn-outline-secondary btn-block"><i class="fas fa-broom mr-1"></i>Clear Page / Count / Location Cache</button></form>
      </div>
    </div>
    <div class="card card-warning card-outline">
      <div class="card-header"><h3 class="card-title"><i class="fas fa-bug mr-2"></i>Debug Mode</h3></div>
      <form method="post"><div class="card-body"><?= csrf_input() ?>
        <div class="custom-control custom-switch"><input type="checkbox" class="custom-control-input" id="debugMode" name="debug_mode" value="1" <?= $debug?'checked':'' ?>><label class="custom-control-label" for="debugMode">Show technical errors on screen for admin only</label></div>
        <p class="small text-muted mt-2 mb-0">Customers and normal sellers still see friendly error messages only.</p>
      </div><div class="card-footer"><button name="toggle_debug" value="1" class="btn btn-warning"><i class="fas fa-save mr-1"></i>Save Debug Mode</button></div></form>
    </div>
  </div>
  <div class="col-lg-8">
    <div class="card card-success card-outline"><div class="card-header"><h3 class="card-title"><i class="fas fa-clipboard-check mr-2"></i>Repair Status</h3></div><div class="card-body">
      <div class="row text-center">
        <div class="col-md-4"><div class="p-3 bg-light rounded"><b>Auto Repair</b><div class="h4 mb-0 <?= $auto?'text-success':'text-danger' ?>"><?= $auto?'ON':'OFF' ?></div></div></div>
        <div class="col-md-4"><div class="p-3 bg-light rounded"><b>Debug Mode</b><div class="h4 mb-0 <?= $debug?'text-warning':'text-muted' ?>"><?= $debug?'ON':'OFF' ?></div></div></div>
        <div class="col-md-4"><div class="p-3 bg-light rounded"><b>System Test</b><div><a href="system-test.php" class="btn btn-sm btn-dark mt-2">Open</a></div></div></div>
      </div>
      <?php if($report): ?><pre class="mt-3 bg-dark text-light p-3 rounded"><?= e(json_encode($report, JSON_PRETTY_PRINT)) ?></pre><?php endif; ?>
    </div></div>
    <div class="card"><div class="card-header d-flex justify-content-between"><h3 class="card-title"><i class="fas fa-bug mr-2"></i>Recent Errors</h3><a href="error-logs.php" class="btn btn-sm btn-outline-primary">View All</a></div><div class="card-body p-0"><table class="table table-sm mb-0"><thead><tr><th>ID</th><th>Type</th><th>Message</th><th>When</th></tr></thead><tbody><?php foreach($recentErrors as $e): ?><tr><td><?= e($e['id']) ?></td><td><?= e($e['error_type']) ?></td><td><?= e(mb_substr((string)$e['message'],0,120)) ?></td><td><?= e($e['created_at']) ?></td></tr><?php endforeach; if(!$recentErrors): ?><tr><td colspan="4" class="text-muted text-center p-3">No errors logged.</td></tr><?php endif; ?></tbody></table></div></div>
    <div class="card"><div class="card-header"><h3 class="card-title"><i class="fas fa-history mr-2"></i>Recent Repairs</h3></div><div class="card-body p-0"><table class="table table-sm mb-0"><thead><tr><th>ID</th><th>Type</th><th>Status</th><th>Message</th><th>When</th></tr></thead><tbody><?php foreach($recentRepairs as $r): ?><tr><td><?= e($r['id']) ?></td><td><?= e($r['repair_type']) ?></td><td><?= e($r['status']) ?></td><td><?= e(mb_substr((string)$r['message'],0,120)) ?></td><td><?= e($r['created_at']) ?></td></tr><?php endforeach; if(!$recentRepairs): ?><tr><td colspan="5" class="text-muted text-center p-3">No repairs logged.</td></tr><?php endif; ?></tbody></table></div></div>
  </div>
</div>
<?php include __DIR__ . '/_footer.php'; ?>
