<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-backups">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4>Backups</h4>
    </div>

    <div class="alert alert-warning small">
      <div><strong>Note:</strong> Only Admin/Super Admin can create backups.</div>
      <div>Database backup uses <code>mysqldump</code>. System backup creates a ZIP of this application, excluding the <code>backups/</code> folder.</div>
    </div>

    <div class="row g-3 mb-3">
      <div class="col-auto">
        <button id="btnDbBackup" class="btn btn-primary"><i class="bi bi-database-down me-2"></i>Create DB Backup</button>
      </div>
      <div class="col-auto">
        <button id="btnSystemBackup" class="btn btn-secondary"><i class="bi bi-hdd-network me-2"></i>Create System Backup (ZIP)</button>
      </div>
    </div>

    <div class="card shadow-sm">
      <div class="card-header">Existing Backups</div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-sm mb-0">
            <thead>
              <tr>
                <th>Name</th>
                <th>Size</th>
                <th>Created</th>
                <th></th>
              </tr>
            </thead>
            <tbody id="backupRows">
              <tr><td colspan="4" class="text-center text-muted">Loading...</td></tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
(function(){
  const csrf = <?php echo json_encode(csrf_token()); ?>;
  function fmtSize(bytes){
    if(bytes < 1024) return bytes+' B';
    const units=['KB','MB','GB','TB']; let i=-1; do { bytes/=1024; i++; } while(bytes>=1024 && i<units.length-1); return bytes.toFixed(2)+' '+units[i];
  }
  function loadList(){
    $.get('api/backup.php', { action:'list' }, function(res){
      const $tb = $('#backupRows'); $tb.empty();
      (res.data||[]).forEach(f=>{
        const tr = $('<tr>');
        tr.append($('<td>').text(f.name));
        tr.append($('<td>').text(fmtSize(f.size)));
        tr.append($('<td>').text(f.mtime));
        const dl = $('<a>').attr('href', f.url).addClass('btn btn-sm btn-outline-primary').text('Download');
        tr.append($('<td>').append(dl));
        $tb.append(tr);
      });
      if(!(res.data||[]).length){ $tb.append('<tr><td colspan="4" class="text-center text-muted">No backups yet</td></tr>'); }
    }).fail(function(xhr){
      const $tb = $('#backupRows'); $tb.html('<tr><td colspan="4" class="text-danger">'+((xhr.responseJSON&&xhr.responseJSON.message)||'Failed to load')+'</td></tr>');
    });
  }
  function run(action){
    const fd = new FormData(); fd.append('csrf', csrf); fd.append('action', action);
    return $.ajax({ url:'api/backup.php', method:'POST', data:fd, processData:false, contentType:false });
  }
  $('#btnDbBackup').on('click', function(){
    const $btn=$(this); $btn.prop('disabled',true).text('Working...');
    run('db_backup').done(function(res){
      loadList(); window.location = res.url; // trigger download
    }).fail(function(xhr){ alert((xhr.responseJSON&&xhr.responseJSON.message)||'Failed to create DB backup'); })
      .always(function(){ $btn.prop('disabled',false).text('Create DB Backup'); });
  });
  $('#btnSystemBackup').on('click', function(){
    const $btn=$(this); $btn.prop('disabled',true).text('Working...');
    run('system_backup').done(function(res){
      loadList(); window.location = res.url;
    }).fail(function(xhr){ alert((xhr.responseJSON&&xhr.responseJSON.message)||'Failed to create System backup'); })
      .always(function(){ $btn.prop('disabled',false).text('Create System Backup (ZIP)'); });
  });
  loadList();
})();
</script>
