<?php /* backup/index.php */ ?>

<style>
.bk-hero{background:linear-gradient(135deg,#0f2557,#1a3a8f 60%,#2563eb);
  border-radius:12px;padding:20px 24px;color:#fff;margin-bottom:20px}
.bk-hero h5{font-size:1.2rem;font-weight:800;margin:0}
.bk-card{background:#fff;border-radius:10px;border:1px solid #e2e8f0;overflow:hidden;margin-bottom:14px}
.bk-card-header{padding:10px 16px;background:#f8fafc;border-bottom:1px solid #e2e8f0;
  font-size:.8rem;font-weight:700;color:#1e293b;
  display:flex;align-items:center;justify-content:space-between;gap:8px}
.bk-card-body{padding:16px}
.file-row{display:flex;align-items:center;gap:12px;padding:10px 16px;
  border-bottom:1px solid #f1f5f9;transition:background .12s}
.file-row:last-child{border:none}
.file-row:hover{background:#f8fafc}
.file-icon{width:36px;height:36px;border-radius:8px;background:#e0f2fe;
  display:flex;align-items:center;justify-content:center;flex-shrink:0}
.restore-zone{border:2px dashed #bfdbfe;border-radius:10px;padding:28px;
  text-align:center;background:#eff6ff;cursor:pointer;
  transition:border-color .2s,background .2s}
.restore-zone:hover,.restore-zone.dragover{border-color:#3b82f6;background:#dbeafe}
</style>

<!-- Hero -->
<div class="bk-hero">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
    <div>
      <h5><i class="bi bi-cloud-arrow-up me-2"></i>Database Backup & Restore</h5>
      <div style="opacity:.8;font-size:.82rem;margin-top:4px">
        <i class="bi bi-database me-1"></i><?= DB_NAME ?>
        &nbsp;·&nbsp; <?= $tableCount ?> tables
        &nbsp;·&nbsp; <?= number_format($dbSizeKB / 1024, 2) ?> MB
        &nbsp;·&nbsp; <?= $totalCount ?> backup<?= $totalCount!=1?'s':'' ?>
      </div>
    </div>
    <form method="POST" action="<?= APP_URL ?>/backup/create">
      <?= Auth::csrfField() ?>
      <button class="btn btn-light fw-bold px-4" style="color:#1d4ed8">
        <i class="bi bi-plus-circle me-1"></i>Create Backup Now
      </button>
    </form>
  </div>
</div>

<?= flashMessages() ?>

<div class="row g-3">

  <!-- ── Left: Backup List ─────────────────────────────── -->
  <div class="col-lg-7">

    <!-- DB Stats -->
    <div class="row g-2 mb-3">
      <?php $stats=[
        ['Tables',     $tableCount,                        'bi-table text-primary',    ''],
        ['DB Size',    number_format($dbSizeKB/1024,2).' MB','bi-hdd text-info',       ''],
        ['Backups',    $totalCount,                         'bi-files text-success',   ''],
        ['Total Size', number_format(array_sum(array_column($backups,'size'))/1024/1024,2).' MB','bi-archive text-warning',''],
      ];?>
      <?php foreach($stats as[$lbl,$val,$icon,$cls]):?>
      <div class="col-6 col-md-3">
        <div class="bk-card h-100">
          <div class="bk-card-body text-center py-3">
            <i class="bi <?=$icon?> fs-4 d-block mb-1"></i>
            <div class="fw-bold"><?=$val?></div>
            <small class="text-muted"><?=$lbl?></small>
          </div>
        </div>
      </div>
      <?php endforeach;?>
    </div>

    <!-- Backup files -->
    <div class="bk-card">
      <div class="bk-card-header">
        <span><i class="bi bi-files me-1 text-success"></i>Backup Files</span>
        <?php if($latestDate):?>
        <small class="text-muted fw-normal">
          Latest: <?= date('d M Y H:i', $latestDate) ?>
        </small>
        <?php endif;?>
      </div>

      <?php if(empty($backups)):?>
      <div class="text-center text-muted py-5">
        <i class="bi bi-inbox d-block fs-2 mb-2 opacity-25"></i>
        No backups yet. Click <strong>Create Backup Now</strong> to start.
      </div>
      <?php else:?>
      <?php foreach($backups as $i=>$b):
        $kb   = round($b['size']/1024,1);
        $mb   = round($b['size']/1024/1024,2);
        $disp = $mb >= 1 ? "{$mb} MB" : "{$kb} KB";
        $age  = time()-$b['date'];
        $ageStr = $age<3600 ? round($age/60).'m ago'
                : ($age<86400 ? round($age/3600).'h ago'
                : date('d M Y H:i',$b['date']));
        $isLatest = $i===0;
      ?>
      <div class="file-row">
        <div class="file-icon">
          <i class="bi bi-file-earmark-zip text-primary fs-5"></i>
        </div>
        <div class="flex-grow-1 min-width-0">
          <div class="fw-semibold small text-truncate">
            <?= e($b['name']) ?>
            <?php if($isLatest):?>
            <span class="badge bg-success ms-1" style="font-size:.55rem">Latest</span>
            <?php endif;?>
          </div>
          <div class="text-muted" style="font-size:.72rem">
            <?= $disp ?> &nbsp;·&nbsp; <?= $ageStr ?>
          </div>
        </div>

        <div class="d-flex gap-1 flex-shrink-0">
          <!-- Download -->
          <a href="<?= APP_URL ?>/backup/download/<?= urlencode($b['name']) ?>"
             class="btn btn-sm btn-outline-primary py-1 px-2" title="Download">
            <i class="bi bi-download"></i>
          </a>

          <!-- Restore -->
          <form method="POST"
                action="<?= APP_URL ?>/backup/restore/<?= urlencode($b['name']) ?>"
                onsubmit="return confirmRestore('<?= e($b['name']) ?>')">
            <?= Auth::csrfField() ?>
            <button type="submit"
                    class="btn btn-sm btn-outline-success py-1 px-2" title="Restore this backup">
              <i class="bi bi-arrow-counterclockwise"></i>
            </button>
          </form>

          <!-- Delete -->
          <form method="POST"
                action="<?= APP_URL ?>/backup/delete/<?= urlencode($b['name']) ?>"
                onsubmit="return confirm('Delete backup: <?= e($b['name']) ?>?')">
            <?= Auth::csrfField() ?>
            <button type="submit"
                    class="btn btn-sm btn-outline-danger py-1 px-2" title="Delete">
              <i class="bi bi-trash3"></i>
            </button>
          </form>
        </div>
      </div>
      <?php endforeach;?>
      <?php endif;?>

    </div>
  </div>

  <!-- ── Right: Restore Panel ──────────────────────────── -->
  <div class="col-lg-5">

    <!-- Restore from upload -->
    <div class="bk-card mb-3">
      <div class="bk-card-header">
        <span><i class="bi bi-arrow-counterclockwise me-1 text-success"></i>Restore Database</span>
      </div>
      <div class="bk-card-body">

        <!-- Warning -->
        <div class="d-flex gap-2 mb-3 p-3 rounded"
             style="background:#fef2f2;border:1px solid #fecaca">
          <i class="bi bi-exclamation-triangle-fill text-danger flex-shrink-0 mt-1"></i>
          <div class="small text-danger">
            <strong>Warning:</strong> Restoring will overwrite your current database.
            Create a backup first if needed.
          </div>
        </div>

        <!-- Upload .sql file -->
        <form method="POST" action="<?= APP_URL ?>/backup/upload"
              enctype="multipart/form-data" id="uploadForm">
          <?= Auth::csrfField() ?>

          <div class="restore-zone" id="dropZone"
               onclick="document.getElementById('sqlFile').click()">
            <i class="bi bi-cloud-upload fs-2 text-primary d-block mb-2"></i>
            <div class="fw-semibold">Upload SQL Backup File</div>
            <div class="text-muted small mt-1">
              Drag & drop or click to choose .sql file
            </div>
            <div class="text-muted small mt-1">Max 50 MB</div>
            <div id="fileNameDisplay" class="fw-semibold text-success mt-2"
                 style="display:none"></div>
          </div>

          <input type="file" id="sqlFile" name="sql_file"
                 accept=".sql" style="display:none"
                 onchange="onFileSelect(this)">

          <button type="submit" id="uploadBtn"
                  class="btn btn-success w-100 fw-semibold mt-3" disabled
                  onclick="return confirmRestore('uploaded file')">
            <i class="bi bi-arrow-counterclockwise me-1"></i>Restore from Upload
          </button>
        </form>

        <div class="text-center my-3 text-muted small">— or restore from a saved backup above —</div>

        <!-- Quick create + restore hint -->
        <div class="rounded p-3" style="background:#f0fdf4;border:1px solid #bbf7d0">
          <div class="small fw-semibold text-success mb-1">
            <i class="bi bi-shield-check me-1"></i>Safe Restore Process
          </div>
          <ol class="small text-muted mb-0 ps-3">
            <li>Click <strong>Create Backup Now</strong> to save current state</li>
            <li>Use <i class="bi bi-arrow-counterclockwise text-success"></i> button on any backup to restore</li>
            <li>Or upload a <code>.sql</code> file from your computer</li>
          </ol>
        </div>
      </div>
    </div>

    <!-- Backup location info -->
    <div class="bk-card">
      <div class="bk-card-header">
        <span><i class="bi bi-folder me-1 text-warning"></i>Storage Info</span>
      </div>
      <div class="bk-card-body">
        <table class="table table-sm table-borderless mb-0">
          <tr>
            <td class="text-muted small ps-0">Backup Folder</td>
            <td class="small pe-0">
              <code style="font-size:.72rem;word-break:break-all"><?= e($backupPath) ?></code>
            </td>
          </tr>
          <tr>
            <td class="text-muted small ps-0">Writable</td>
            <td class="ps-0">
              <span class="badge <?= $writable?'bg-success':'bg-danger' ?>">
                <?= $writable ? '✓ Yes' : '✗ No — check folder permissions' ?>
              </span>
            </td>
          </tr>
          <tr>
            <td class="text-muted small ps-0">Total Backups</td>
            <td class="small fw-semibold ps-0"><?= $totalCount ?></td>
          </tr>
          <?php if($latestDate):?>
          <tr>
            <td class="text-muted small ps-0">Last Backup</td>
            <td class="small ps-0"><?= date('d M Y H:i', $latestDate) ?></td>
          </tr>
          <?php endif;?>
        </table>
      </div>
    </div>

  </div>
</div>

<script>
function confirmRestore(name) {
  return confirm(
    '⚠ RESTORE DATABASE FROM:\n\n"' + name + '"\n\n' +
    'This will OVERWRITE your current database.\n' +
    'All current data will be replaced.\n\n' +
    'Are you sure you want to continue?'
  );
}

// File drag & drop
const dropZone = document.getElementById('dropZone');
const sqlFile  = document.getElementById('sqlFile');
const uploadBtn= document.getElementById('uploadBtn');
const fileDisp = document.getElementById('fileNameDisplay');

function onFileSelect(input) {
  const file = input.files[0];
  if (file) {
    fileDisp.textContent = '📄 ' + file.name + ' (' + (file.size/1024).toFixed(1) + ' KB)';
    fileDisp.style.display = 'block';
    uploadBtn.disabled = false;
  }
}

dropZone.addEventListener('dragover', e => {
  e.preventDefault();
  dropZone.classList.add('dragover');
});
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('dragover'));
dropZone.addEventListener('drop', e => {
  e.preventDefault();
  dropZone.classList.remove('dragover');
  const dt = e.dataTransfer;
  if (dt.files.length) {
    sqlFile.files = dt.files;
    onFileSelect(sqlFile);
  }
});
</script>