<!DOCTYPE html>
<html>
<head>
<!-- FORM CSS CODE -->
<?php include"comman/code_css.php"; ?>
<!-- </copy> -->  
</head>
<body class="hold-transition skin-blue sidebar-mini">

<div class="wrapper">
  <?php include"sidebar.php"; ?>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h1>
        <i class="fa fa-database"></i> <?= $page_title ?>
      </h1>
      <ol class="breadcrumb">
        <li><a href="<?= $base_url ?>dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
        <li class="active"><?= $page_title ?></li>
      </ol>
    </section>

    <!-- Main content -->
    <section class="content">
      <div class="row">
        <!-- ********** ALERT MESSAGE START******* -->
        <?php include"comman/code_flashdata.php"; ?>
        <!-- ********** ALERT MESSAGE END******* -->
      </div>

      <!-- Demo Mode Alert for Database Backup -->
      <?php if(demo_app()){ ?>
      <div class="row">
        <div class="col-md-12">
          <div class="alert alert-warning text-center">
            <i class="fa fa-exclamation-triangle"></i>
            <strong>Demo Mode Active:</strong> Database backup functionality is disabled in demo mode for security reasons. 
            <a href="https://nanzige.com/ncs-billing-book-complete-pos-inventory-management-system/" target="_blank" class="btn btn-sm btn-danger" style="margin-left: 10px;">
              <i class="fa fa-shopping-cart"></i> Buy Now to Enable
            </a>
          </div>
        </div>
      </div>
      <?php } ?>
      
      <div class="row">
        <!-- Create Backup Section -->
        <div class="col-md-6">
          <div class="box box-primary">
            <div class="box-header with-border">
              <h3 class="box-title"><i class="fa fa-plus"></i> Create New Backup</h3>
            </div>
            <div class="box-body">
              <form id="create_backup_form">
                <input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>">
                <div class="form-group">
                  <label for="backup_name">Backup Name (Optional)</label>
                  <input type="text" class="form-control" id="backup_name" name="backup_name" placeholder="Enter backup name or leave empty for auto-generated name" <?php echo demo_app() ? 'disabled' : ''; ?>>
                  <small class="text-muted">If left empty, a name will be generated automatically</small>
                </div>
                <button type="submit" class="btn btn-primary btn-block" <?php echo demo_app() ? 'disabled' : ''; ?>>
                  <i class="fa fa-download"></i> Create Backup
                </button>
              </form>
            </div>
          </div>
        </div>

        <!-- Upload Backup Section -->
        <div class="col-md-6">
          <div class="box box-success">
            <div class="box-header with-border">
              <h3 class="box-title"><i class="fa fa-upload"></i> Upload Backup File</h3>
            </div>
            <div class="box-body">
              <form id="upload_backup_form" enctype="multipart/form-data">
                <input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>">
                <div class="form-group">
                  <label for="backup_file">Select Backup File</label>
                  <input type="file" id="backup_file" name="backup_file" accept=".zip,.sql" class="form-control" <?php echo demo_app() ? 'disabled' : ''; ?>>
                  <small class="text-muted">Supports .zip and .sql files (Max: 200MB)</small>
                  <div id="file_info" class="file-info" style="display: none;">
                    <div class="file-details">
                      <i class="fa fa-file-archive-o"></i>
                      <span class="file-name"></span>
                      <span class="file-size"></span>
                      <button type="button" class="btn btn-sm btn-danger remove-file">
                        <i class="fa fa-times"></i>
                      </button>
                    </div>
                  </div>
                </div>
                <button type="submit" class="btn btn-success btn-block" id="upload_btn" <?php echo demo_app() ? 'disabled' : ''; ?>>
                  <i class="fa fa-upload"></i> Upload & Restore
                </button>
              </form>
            </div>
          </div>
        </div>
      </div>

      <!-- Backup Statistics Row -->
      <div class="row">
        <div class="col-md-12">
          <div class="box box-info">
            <div class="box-header with-border">
              <h3 class="box-title"><i class="fa fa-info-circle"></i> Backup Information</h3>
            </div>
            <div class="box-body">
              <div class="row">
                <div class="col-md-3">
                  <div class="info-box bg-blue">
                    <span class="info-box-icon"><i class="fa fa-database"></i></span>
                    <div class="info-box-content">
                      <span class="info-box-text" style="font-size: 12px;">Total Backups</span>
                      <span class="info-box-number" id="total_backups" style="font-size: 18px;"><?= count($backups) ?></span>
                    </div>
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="info-box bg-green">
                    <span class="info-box-icon"><i class="fa fa-clock-o"></i></span>
                    <div class="info-box-content">
                      <span class="info-box-text" style="font-size: 12px;">Latest Backup</span>
                      <span class="info-box-number" id="latest_backup" style="font-size: 14px;">
                        <?= !empty($backups) ? date('M d, Y', strtotime($backups[0]['date'])) : 'None' ?>
                      </span>
                    </div>
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="info-box bg-yellow">
                    <span class="info-box-icon"><i class="fa fa-hdd-o"></i></span>
                    <div class="info-box-content">
                      <span class="info-box-text" style="font-size: 12px;">Total Size</span>
                      <span class="info-box-number" id="total_size" style="font-size: 14px;">
                        <?php 
                        $total_size = 0;
                        foreach($backups as $backup){
                          $size_str = $backup['size'];
                          $size_num = (float) preg_replace('/[^0-9.]/', '', $size_str);
                          $unit = preg_replace('/[0-9.]/', '', $size_str);
                          switch($unit){
                            case 'KB': $total_size += $size_num * 1024; break;
                            case 'MB': $total_size += $size_num * 1024 * 1024; break;
                            case 'GB': $total_size += $size_num * 1024 * 1024 * 1024; break;
                            default: $total_size += $size_num;
                          }
                        }
                        
                        // Simple format_bytes function for this view
                        $units = array('B', 'KB', 'MB', 'GB', 'TB');
                        $bytes = $total_size;
                        for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
                          $bytes /= 1024;
                        }
                        echo round($bytes, 2) . ' ' . $units[$i];
                        ?>
                      </span>
                    </div>
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="info-box bg-purple">
                    <span class="info-box-icon"><i class="fa fa-shield"></i></span>
                    <div class="info-box-content">
                      <span class="info-box-text" style="font-size: 12px;">Status</span>
                      <span class="info-box-number" style="font-size: 14px;">
                        <?= !empty($backups) ? 'Protected' : 'No Backups' ?>
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Backup List -->
      <div class="row">
        <div class="col-md-12">
          <div class="box box-success">
            <div class="box-header with-border">
              <h3 class="box-title"><i class="fa fa-list"></i> Backup History</h3>
              <div class="box-tools pull-right">
                <button type="button" class="btn btn-box-tool" data-widget="collapse">
                  <i class="fa fa-minus"></i>
                </button>
              </div>
            </div>
            <div class="box-body">
              <?php if(empty($backups)): ?>
                <div class="text-center" style="padding: 40px;">
                  <i class="fa fa-database fa-3x text-muted"></i>
                  <h4 class="text-muted">No backups found</h4>
                  <p class="text-muted">Create your first backup to get started</p>
                </div>
              <?php else: ?>
                <div class="table-responsive">
                  <table class="table table-bordered table-striped" id="backup_table">
                    <thead>
                      <tr>
                        <th>Backup Name</th>
                        <th>Type</th>
                        <th>Size</th>
                        <th>Created Date</th>
                        <th>Actions</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php foreach($backups as $backup): ?>
                        <tr>
                          <td>
                            <?= $backup['name'] ?>
                            <?php if(isset($backup['is_uploaded']) && $backup['is_uploaded']): ?>
                              <span class="label label-info" style="margin-left: 5px;">Uploaded</span>
                            <?php endif; ?>
                          </td>
                          <td>
                            <span class="label label-<?= $backup['type'] == 'zip' ? 'primary' : 'success' ?>">
                              <?= strtoupper($backup['type']) ?>
                            </span>
                          </td>
                          <td><?= $backup['size'] ?></td>
                          <td><?= $backup['date'] ?></td>
                          <td>
                            <div class="btn-group">
                              <button type="button" class="btn btn-sm btn-info download-backup" data-filename="<?= $backup['name'] ?>" <?php echo demo_app() ? 'disabled' : ''; ?>>
                                <i class="fa fa-download"></i> Download
                              </button>
                              <button type="button" class="btn btn-sm btn-warning restore-backup" data-filename="<?= $backup['name'] ?>" <?php echo demo_app() ? 'disabled' : ''; ?>>
                                <i class="fa fa-undo"></i> Restore
                              </button>
                              <button type="button" class="btn btn-sm btn-danger delete-backup" data-filename="<?= $backup['name'] ?>" <?php echo demo_app() ? 'disabled' : ''; ?>>
                                <i class="fa fa-trash"></i> Delete
                              </button>
                            </div>
                          </td>
                        </tr>
                      <?php endforeach; ?>
                    </tbody>
                  </table>
                </div>
              <?php endif; ?>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
</div>

<!-- Restore Confirmation Modal -->
<div class="modal fade" id="restore_modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title"><i class="fa fa-exclamation-triangle text-warning"></i> Confirm Restore</h4>
      </div>
      <div class="modal-body">
        <p><strong>Warning:</strong> This action will overwrite your current database with the selected backup. This action cannot be undone!</p>
        <p>Are you sure you want to restore the database from this backup?</p>
        <p><strong>Backup:</strong> <span id="restore_filename"></span></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-warning" id="confirm_restore" <?php echo demo_app() ? 'disabled' : ''; ?>>Yes, Restore Database</button>
      </div>
    </div>
  </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="delete_modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title"><i class="fa fa-exclamation-triangle text-danger"></i> Confirm Delete</h4>
      </div>
      <div class="modal-body">
        <p>Are you sure you want to delete this backup?</p>
        <p><strong>Backup:</strong> <span id="delete_filename"></span></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-danger" id="confirm_delete" <?php echo demo_app() ? 'disabled' : ''; ?>>Yes, Delete Backup</button>
      </div>
    </div>
  </div>
</div>

<!-- Upload Area Styling -->
<style>
  
  .file-info {
    margin-top: 10px;
    padding: 10px;
    background-color: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 4px;
  }
  
  .file-details {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  
  .file-details i {
    color: #28a745;
    font-size: 18px;
  }
  
  .file-name {
    flex: 1;
    font-weight: 500;
    color: #333;
  }
  
  .file-size {
    color: #666;
    font-size: 12px;
  }
  
  .remove-file {
    padding: 2px 6px;
  }
  
  .progress {
    margin-top: 10px;
    height: 20px;
  }
  
  .progress-bar {
    line-height: 20px;
    font-size: 12px;
  }
</style>

<!-- Demo Mode Styling for Database Backup -->
<?php if(demo_app()){ ?>
<style>
  .form-control:disabled {
    background-color: #f5f5f5 !important;
    cursor: not-allowed !important;
    opacity: 0.6 !important;
  }
  
  .btn:disabled {
    cursor: not-allowed !important;
    opacity: 0.6 !important;
  }
  
  .box {
    opacity: 0.8;
  }
  
  .box::before {
    content: "DEMO MODE - READ ONLY";
    position: absolute;
    top: -10px;
    right: 20px;
    background: #f39c12;
    color: white;
    padding: 5px 15px;
    border-radius: 15px;
    font-size: 11px;
    font-weight: bold;
    z-index: 1000;
  }
</style>
<?php } ?>

<!-- FORM JS CODE -->
<?php include"comman/code_js.php"; ?>

<script>
// Define base_url for JavaScript
var base_url = '<?= $base_url ?>';
var csrf_token_name = '<?php echo $this->security->get_csrf_token_name(); ?>';
var csrf_token_value = '<?php echo $this->security->get_csrf_hash(); ?>';

$(document).ready(function() {
  // File upload functionality
  var selectedFile = null;
  
  
  // File input change handler
  $('#backup_file').on('change', function(e) {
    var file = e.target.files[0];
    if(file) {
      handleFileSelection(file);
    }
  });
  
  
  
  // Remove file handler
  $(document).on('click', '.remove-file', function() {
    selectedFile = null;
    $('#backup_file').val('');
    $('#file_info').hide();
  });
  
  // File selection handler
  function handleFileSelection(file) {
    // Validate file type
    var allowedTypes = ['application/zip', 'application/x-zip-compressed', 'application/sql', 'text/sql'];
    var fileExtension = file.name.split('.').pop().toLowerCase();
    
    if(!allowedTypes.includes(file.type) && !['zip', 'sql'].includes(fileExtension)) {
      toastr.error('Please select a valid backup file (.zip or .sql)');
      $('#backup_file').val(''); // Clear the input
      return;
    }
    
    // Validate file size (200MB max)
    var maxSize = 200 * 1024 * 1024; // 200MB in bytes
    if(file.size > maxSize) {
      toastr.error('File size must be less than 200MB');
      $('#backup_file').val(''); // Clear the input
      return;
    }
    
    selectedFile = file;
    
    // Update UI
    $('#file_info .file-name').text(file.name);
    $('#file_info .file-size').text(formatFileSize(file.size));
    $('#file_info').show();
    
    // Show success message
    toastr.success('File selected: ' + file.name);
  }
  
  // Format file size
  function formatFileSize(bytes) {
    if(bytes === 0) return '0 Bytes';
    var k = 1024;
    var sizes = ['Bytes', 'KB', 'MB', 'GB'];
    var i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }
  
  // Upload backup form
  $('#upload_backup_form').on('submit', function(e) {
    e.preventDefault();
    
    // Check if in demo mode
    if($('#upload_btn').prop('disabled')) {
      alert("File upload is disabled in demo mode. Please purchase the full version to enable this feature.");
      return false;
    }
    
    if(!selectedFile) {
      toastr.error('Please select a backup file to upload');
      return false;
    }
    
    var formData = new FormData();
    formData.append('backup_file', selectedFile);
    formData.append(csrf_token_name, csrf_token_value);
    
    $.ajax({
      url: base_url + 'backup/upload_backup',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      beforeSend: function() {
        $('#upload_btn').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Uploading...');
      },
      success: function(response) {
        if(response == 'success') {
          toastr.success('Backup uploaded and restored successfully!');
          setTimeout(function() {
            location.reload();
          }, 1500);
        } else if(response.startsWith('success|')) {
          var parts = response.split('|');
          var message = 'Backup uploaded and restored successfully!';
          if(parts.length > 1) {
            message += ' ' + parts[1];
          }
          toastr.success(message);
          setTimeout(function() {
            location.reload();
          }, 1500);
        } else {
          toastr.error('Failed to upload and restore backup: ' + response);
        }
      },
      error: function(xhr, status, error) {
        var errorMessage = 'An error occurred while uploading backup';
        if(xhr.responseText) {
          errorMessage += ': ' + xhr.responseText;
        } else if(error) {
          errorMessage += ': ' + error;
        }
        
        toastr.error(errorMessage);
      },
      complete: function() {
        $('#upload_btn').prop('disabled', false).html('<i class="fa fa-upload"></i> Upload & Restore');
      }
    });
  });

  // Create backup
  $('#create_backup_form').on('submit', function(e) {
    e.preventDefault();
    
    // Check if in demo mode (form disabled)
    if($('#create_backup_form button').prop('disabled')) {
      alert("Database backup cannot be created in demo mode. Please purchase the full version to enable this feature.");
      return false;
    }
    
    var backup_name = $('#backup_name').val();
    var formData = new FormData(this);
    
    $.ajax({
      url: base_url + 'backup/create_backup',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      beforeSend: function() {
        $('#create_backup_form button').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Creating...');
      },
      success: function(response) {
        if(response == 'success') {
          toastr.success('Backup created successfully!');
          setTimeout(function() {
            location.reload();
          }, 1500);
        } else {
          toastr.error('Failed to create backup: ' + response);
        }
      },
      error: function() {
        toastr.error('An error occurred while creating backup');
      },
      complete: function() {
        $('#create_backup_form button').prop('disabled', false).html('<i class="fa fa-download"></i> Create Backup');
      }
    });
  });
  
  // Download backup
  $('.download-backup').on('click', function() {
    // Check if in demo mode (button disabled)
    if($(this).prop('disabled')) {
      alert("Database backup cannot be downloaded in demo mode. Please purchase the full version to enable this feature.");
      return false;
    }
    
    var filename = $(this).data('filename');
    
    // Create a form to submit the download request
    var form = $('<form>', {
      'method': 'POST',
      'action': base_url + 'backup/download_backup'
    });
    
    form.append($('<input>', {
      'type': 'hidden',
      'name': 'filename',
      'value': filename
    }));
    
    form.append($('<input>', {
      'type': 'hidden',
      'name': csrf_token_name,
      'value': csrf_token_value
    }));
    
    $('body').append(form);
    form.submit();
    form.remove();
  });
  
  // Restore backup
  $('.restore-backup').on('click', function() {
    // Check if in demo mode (button disabled)
    if($(this).prop('disabled')) {
      alert("Database backup cannot be restored in demo mode. Please purchase the full version to enable this feature.");
      return false;
    }
    
    var filename = $(this).data('filename');
    $('#restore_filename').text(filename);
    $('#restore_modal').modal('show');
  });
  
  $('#confirm_restore').on('click', function() {
    // Check if in demo mode (button disabled)
    if($(this).prop('disabled')) {
      alert("Database backup cannot be restored in demo mode. Please purchase the full version to enable this feature.");
      return false;
    }
    
    var filename = $('#restore_filename').text();
    
    $.ajax({
      url: base_url + 'backup/restore_backup',
      type: 'POST',
      data: {
        filename: filename,
        [csrf_token_name]: csrf_token_value
      },
      beforeSend: function() {
        $('#confirm_restore').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Restoring...');
      },
      success: function(response) {
        if(response == 'success') {
          toastr.success('Database restored successfully!');
          setTimeout(function() {
            location.reload();
          }, 1500);
        } else if(response.startsWith('success|')) {
          var parts = response.split('|');
          var message = 'Database restored successfully!';
          if(parts.length > 1) {
            message += ' ' + parts[1];
          }
          toastr.success(message);
          setTimeout(function() {
            location.reload();
          }, 1500);
        } else {
          toastr.error('Failed to restore database: ' + response);
        }
      },
      error: function(xhr, status, error) {
        var errorMessage = 'An error occurred while restoring database';
        if(xhr.responseText) {
          errorMessage += ': ' + xhr.responseText;
        } else if(error) {
          errorMessage += ': ' + error;
        }
        
        toastr.error(errorMessage);
      },
      complete: function() {
        $('#confirm_restore').prop('disabled', false).html('Yes, Restore Database');
        $('#restore_modal').modal('hide');
      }
    });
  });
  
  // Delete backup
  $('.delete-backup').on('click', function() {
    // Check if in demo mode (button disabled)
    if($(this).prop('disabled')) {
      alert("Database backup cannot be deleted in demo mode. Please purchase the full version to enable this feature.");
      return false;
    }
    
    var filename = $(this).data('filename');
    $('#delete_filename').text(filename);
    $('#delete_modal').modal('show');
  });
  
  $('#confirm_delete').on('click', function() {
    // Check if in demo mode (button disabled)
    if($(this).prop('disabled')) {
      alert("Database backup cannot be deleted in demo mode. Please purchase the full version to enable this feature.");
      return false;
    }
    
    var filename = $('#delete_filename').text();
    
    $.ajax({
      url: base_url + 'backup/delete_backup',
      type: 'POST',
      data: {
        filename: filename,
        [csrf_token_name]: csrf_token_value
      },
      beforeSend: function() {
        $('#confirm_delete').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Deleting...');
      },
      success: function(response) {
        if(response == 'success') {
          toastr.success('Backup deleted successfully!');
          setTimeout(function() {
            location.reload();
          }, 1500);
        } else {
          toastr.error('Failed to delete backup: ' + response);
        }
      },
      error: function() {
        toastr.error('An error occurred while deleting backup');
      },
      complete: function() {
        $('#confirm_delete').prop('disabled', false).html('Yes, Delete Backup');
        $('#delete_modal').modal('hide');
      }
    });
  });
});
</script> 