<?php
require 'auth.php';
require 'db.php';
require 'sipp_db.php';
require_login();

// Test connection
$connection_test = testSippConnection();
$available_tables = getSippTables();
$arsip_structure = getArsipTableStructure();
$sipp_db = connectSipp();

function esc($s) { return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }
?>
<!doctype html>
<html lang="id"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test Koneksi SIPP - Sistem Peminjaman Berkas</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
<style>
body{background:#f5f7fb}
.card{box-shadow:0 2px 10px rgba(0,0,0,0.1)}
.table th{background:#f8f9fa}
pre{background:#f8f9fa;padding:10px;border-radius:5px;max-height:300px;overflow-y:auto}
.status-success{color:#28a745;font-weight:bold}
.status-error{color:#dc3545;font-weight:bold}
</style>
</head>
<body>

<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
  <div class="container-fluid">
    <a class="navbar-brand d-flex align-items-center" href="index.php">
      <img src="gambar/Logo_pnwtp.png" alt="Logo PN Watampone" width="70" height="70" class="me-3">
      <span><i class="fa fa-book me-1"></i> Sistem Peminjaman Berkas<br><small>Pengadilan Negeri Watampone</small></span>
    </a>
    <div class="d-flex gap-2">
      <a class="btn btn-outline-light btn-sm" href="index.php">
        <i class="fa fa-home"></i> Beranda
      </a>
      <a class="btn btn-outline-light btn-sm" href="arsip.php">
        <i class="fa fa-archive"></i> Arsip SIPP
      </a>
      <span class="navbar-text text-light">Hi, <?=esc(current_user()['nama_lengkap'] ?? current_user()['username'])?></span>
      <a class="btn btn-outline-light btn-sm" href="logout.php"><i class="fa fa-sign-out-alt"></i> Logout</a>
    </div>
  </div>
</nav>

<div class="container py-4">
  <div class="row">
    <div class="col-12">
      <h2><i class="fa fa-database text-primary"></i> Test Koneksi Database SIPP</h2>
      <p class="text-muted">Halaman ini untuk menguji koneksi dan memeriksa struktur database SIPP</p>
    </div>
  </div>

  <!-- Connection Status -->
  <div class="row mb-4">
    <div class="col-12">
      <div class="card">
        <div class="card-header">
          <h5><i class="fa fa-plug"></i> Status Koneksi</h5>
        </div>
        <div class="card-body">
          <div class="row">
            <div class="col-md-6">
              <strong>Status:</strong> 
              <span class="<?= $connection_test['success'] ? 'status-success' : 'status-error' ?>">
                <?= $connection_test['success'] ? 'BERHASIL' : 'GAGAL' ?>
              </span>
            </div>
            <div class="col-md-6">
              <strong>Pesan:</strong> <?= esc($connection_test['message']) ?>
            </div>
          </div>
          
          <hr>
          
          <h6>Konfigurasi Database:</h6>
          <ul>
            <li><strong>Host:</strong> 192.168.1.240</li>
            <li><strong>Port:</strong> 3306</li>
            <li><strong>Database:</strong> sippbaco</li>
            <li><strong>Username:</strong> pnwtp</li>
            <li><strong>Password:</strong> *** (tersembunyi)</li>
          </ul>
        </div>
      </div>
    </div>
  </div>

  <!-- Available Tables -->
  <?php if($connection_test['success'] && $available_tables): ?>
  <div class="row mb-4">
    <div class="col-12">
      <div class="card">
        <div class="card-header">
          <h5><i class="fa fa-table"></i> Tabel yang Tersedia (<?= count($available_tables) ?> tabel)</h5>
        </div>
        <div class="card-body">
          <div class="row">
            <?php foreach(array_chunk($available_tables, ceil(count($available_tables) / 3)) as $chunk): ?>
            <div class="col-md-4">
              <ul class="list-unstyled">
                <?php foreach($chunk as $table): ?>
                <li>
                  <i class="fa fa-table text-muted"></i> <?= esc($table) ?>
                  <?php if($table === 'arsip'): ?>
                    <span class="badge bg-success">Target</span>
                  <?php endif; ?>
                </li>
                <?php endforeach; ?>
              </ul>
            </div>
            <?php endforeach; ?>
          </div>
        </div>
      </div>
    </div>
  </div>
  <?php endif; ?>

  <!-- Arsip Table Structure -->
  <?php if($connection_test['success'] && $arsip_structure): ?>
  <div class="row mb-4">
    <div class="col-12">
      <div class="card">
        <div class="card-header">
          <h5><i class="fa fa-archive"></i> Struktur Tabel Arsip</h5>
        </div>
        <div class="card-body">
          <div class="table-responsive">
            <table class="table table-striped table-sm">
              <thead>
                <tr>
                  <th>Kolom</th>
                  <th>Tipe Data</th>
                  <th>Null</th>
                  <th>Key</th>
                  <th>Default</th>
                  <th>Extra</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach($arsip_structure as $column): ?>
                <tr>
                  <td><strong><?= esc($column['Field']) ?></strong></td>
                  <td><?= esc($column['Type']) ?></td>
                  <td><?= $column['Null'] === 'YES' ? 'Ya' : 'Tidak' ?></td>
                  <td><?= esc($column['Key']) ?></td>
                  <td><?= esc($column['Default']) ?></td>
                  <td><?= esc($column['Extra']) ?></td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
  <?php endif; ?>

  <!-- Sample Data -->
  <?php if($connection_test['success'] && $sipp_db): ?>
  <div class="row mb-4">
    <div class="col-12">
      <div class="card">
        <div class="card-header">
          <h5><i class="fa fa-eye"></i> Sample Data Arsip (5 record terbaru)</h5>
        </div>
        <div class="card-body">
          <?php
          try {
            $stmt = $sipp_db->query("SELECT * FROM arsip ORDER BY id DESC LIMIT 5");
            $sample_data = $stmt->fetchAll();
            
            if(!empty($sample_data)):
          ?>
            <div class="table-responsive">
              <table class="table table-striped table-sm">
                <thead>
                  <tr>
                    <?php foreach(array_keys($sample_data[0]) as $column): ?>
                    <th><?= esc($column) ?></th>
                    <?php endforeach; ?>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach($sample_data as $row): ?>
                  <tr>
                    <?php foreach($row as $value): ?>
                    <td><?= esc(substr($value, 0, 50)) ?><?= strlen($value) > 50 ? '...' : '' ?></td>
                    <?php endforeach; ?>
                  </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          <?php else: ?>
            <p class="text-muted"><em>Tidak ada data di tabel arsip</em></p>
          <?php endif; ?>
          
          <?php
          } catch(PDOException $e) {
            echo '<div class="alert alert-warning">Error mengambil sample data: ' . esc($e->getMessage()) . '</div>';
          }
          ?>
        </div>
      </div>
    </div>
  </div>
  <?php endif; ?>

  <!-- Raw Configuration -->
  <div class="row">
    <div class="col-12">
      <div class="card">
        <div class="card-header">
          <h5><i class="fa fa-code"></i> Debug Information</h5>
        </div>
        <div class="card-body">
          <h6>PHP PDO MySQL Extension:</h6>
          <p><?= extension_loaded('pdo_mysql') ? '<span class="status-success">TERSEDIA</span>' : '<span class="status-error">TIDAK TERSEDIA</span>' ?></p>
          
          <h6>Error Log:</h6>
          <pre><?php
          if($connection_test['success']) {
            echo "Tidak ada error koneksi.\n";
          } else {
            echo "Error: " . $connection_test['message'] . "\n";
          }
          ?></pre>
          
          <h6>Global SIPP Config:</h6>
          <pre><?php
          global $sipp_config;
          $safe_config = $sipp_config ?? [];
          $safe_config['password'] = '***'; // Hide password
          print_r($safe_config);
          ?></pre>
        </div>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body></html>
