<script>
document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item">Tools <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb-item active">Database Backups</li>';
</script>

<div id="loadingObject" style="position: fixed; top:40%; width:100%; display:none">
    <h1 class="text-center"><i class="fad fa-database fa-spin fa-3x fa-fw"
            style="--fa-primary-color:#0055A6;--fa-secondary-color:gray;"></i><br>Backing up Data <br><small>Please
            wait</small></h1>
</div>

<div id="start">

    <div class="row">
        <div class="col-12">
            <div class="note note-secondary mb-4"><strong>Backups:</strong> Download a database backup to keep for
                security and retention policy regulations.</div>
        </div>
    </div>
    <div class="col-12 text-center mb-4">
        <div class="btn-group p-3">
            <button class="btn btn-info btn-sm m-0 me-4 p-2" onclick="backup()">Backup Complete Database (SQL)</button>
            <?php
            $tablesToBackup = ['clientdetails', 'itemdetails', 'locations', 'agents', 'brokers', 'invoices', 'reportitems'];
            foreach ($tablesToBackup as $table) {
                echo '<button class="btn btn-secondary btn-sm mb-3 me-4" onclick="csvbackup(\'' . $table . '\')">Backup ' . $table . ' as CSV</button>';
            }
            ?>
        </div>
    </div>

    <div class="container">

        <!-- MANUAL LIST (unchanged API, omits folders) -->
        <ul class="list-group mb-4">
            <li class="list-group-item bg-info text-light">
                <div class="row">
                    <div class="col-6">File</div>
                    <div class="col-3">Date Created</div>
                    <div class="col-3 text-center">Download</div>
                </div>
            </li>
            <?php
            $dir   = 'backups';
            $abs   = $dir;
            $files = is_dir($abs) ? scandir($abs) : [];

            // sort by mtime desc, omit folders
            $files = array_values(array_filter($files, function ($f) use ($abs) {
                if ($f === '.' || $f === '..') return false;
                return is_file($abs . '/' . $f);
            }));
            usort($files, function ($a, $b) use ($abs) {
                return filemtime($abs . '/' . $b) <=> filemtime($abs . '/' . $a);
            });

            foreach ($files as $dl) {
                $fileInfo  = pathinfo($dl);
                $extension = isset($fileInfo['extension']) ? strtolower($fileInfo['extension']) : '';
                $created   = date('d-m-Y H:i:s', filemtime($abs . '/' . $dl));
                echo '
          <li class="list-group-item">
            <div class="row">
              <div class="col-6">' . ($extension === 'csv' ? '<i class="fad fa-file-csv"></i>' : '<i class="fad fa-database"></i>') . ' ' . $dl . '</div>
              <div class="col-3">' . $created . '</div>
              <div class="col-3 text-center">
                <a href="' . $dir . '/' . $dl . '" class="btn btn-outline-info btn-sm" download><i class="fad fa-cloud-download-alt"></i> Download</a>
                <button class="btn btn-outline-danger btn-sm" onclick="deleteBackup(\'' . $dl . '\')"><i class="fad fa-trash"></i> Delete</button>
              </div>
            </div>
          </li>';
            }
            ?>
        </ul>

        <?php
        // AUTO LISTS: Daily / Weekly / Monthly (SQL only)
        function listAuto($label, $relDir)
        {
            $absDir = trim($relDir, '/');
            $webDir = $relDir;

            echo '<ul class="list-group mb-4">';
            echo '<li class="list-group-item bg-info text-light"><div class="row">';
            echo '  <div class="col-6">' . $label . ' Backups</div>';
            echo '  <div class="col-3">Date Created</div>';
            echo '  <div class="col-3 text-center">Actions</div>';
            echo '</div></li>';

            if (!is_dir($absDir)) {
                echo '<li class="list-group-item"><em>Folder not found: ' . htmlspecialchars($relDir) . '</em></li></ul>';
                return;
            }

            $files = glob($absDir . '/*.sql');
            if (!$files) {
                echo '<li class="list-group-item"><em>No backups found</em></li></ul>';
                return;
            }

            usort($files, function ($a, $b) {
                return filemtime($b) <=> filemtime($a);
            });

            foreach ($files as $abs) {
                $base    = basename($abs);
                $created = date('d-m-Y H:i:s', filemtime($abs));
                echo '
            <li class="list-group-item">
              <div class="row align-items-center">
                <div class="col-6"><i class="fad fa-database"></i> ' . $base . '</div>
                <div class="col-3">' . $created . '</div>
                <div class="col-3 text-center">
                  <a href="' . $webDir . '/' . $base . '" class="btn btn-outline-info btn-sm" download>
                    <i class="fad fa-cloud-download-alt"></i> Download
                  </a>
                  
                </div>
              </div>
            </li>';
            }
            echo '</ul>';
        }

        listAuto('Daily',   'backups/db/daily');
        listAuto('Weekly',  'backups/db/weekly');
        listAuto('Monthly', 'backups/db/monthly');
        ?>
    </div>
</div>

<script>
function backup() {
    document.getElementById('loadingObject').style.display = 'block';
    document.getElementById('start').style.display = 'none';

    fetch(ROOT_URL + '/includes/backup/backup_functions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                action: 'dbbackup',
                tenant: TENANT_URL
            })
        })
        .then(r => r.text())
        .then(t => {
            document.getElementById('loadingObject').style.display = 'none';
            if (t.trim() === "s") {
                showResponse('success', 'Your backup has been created successfully');
                location.reload();
            } else {
                showResponse('danger', 'Backup failed');
            }
        })
        .catch(() => {
            document.getElementById('loadingObject').style.display = 'none';
            showResponse('danger', 'Network error');
        });
}

function csvbackup(tableName) {
    document.getElementById('loadingObject').style.display = 'block';
    fetch(ROOT_URL + '/includes/backup/backup_functions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                action: 'csvbackup',
                table: tableName,
                type: 'csv',
                tenant: TENANT_URL
            })
        })
        .then(r => r.text())
        .then(t => {
            document.getElementById('loadingObject').style.display = 'none';
            if (t.trim() === "s") {
                showResponse('success', 'Backup completed successfully');
                location.reload();
            } else {
                showResponse('danger', 'Backup failed');
            }
        })
        .catch(() => {
            document.getElementById('loadingObject').style.display = 'none';
            showResponse('danger', 'Network error');
        });
}

// Manual delete (unchanged API)
function deleteBackup(filename) {
    var dest = '<p>Are you sure you wish do delete this backup?</p>';
    loadModalContent(dest, "deleteBox", "modal-md", 1060, "true", "Delete Backup File", "cancelConfirm",
        () => deleteBackupConfirm(filename)
    );
}

function deleteBackupConfirm(filename) {
    fetch(ROOT_URL + '/includes/backup/backup_functions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                action: 'delete',
                filename: filename,
                tenant: TENANT_URL
            })
        })
        .then(r => r.text())
        .then(t => {
            if (t.trim() === "s") {
                showResponse('success', 'Backup deleted successfully');
                location.reload();
            } else {
                showResponse('danger', 'Backup deletion failed');
            }
        })
        .catch(() => showResponse('danger', 'Network error'));
}

// Auto delete (needs path + filename)
function deleteAutoBackup(pathRel, filename) {
    var dest = '<p>Are you sure you wish to delete this backup?</p>';
    loadModalContent(dest, "deleteBox", "modal-md", 1060, "true", "Delete Backup File", "cancelConfirm",
        () => {
            fetch(ROOT_URL + '/includes/backup/backup_functions.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: new URLSearchParams({
                        action: 'delete',
                        path: pathRel,
                        filename: filename,
                        tenant: TENANT_URL
                    })
                })
                .then(r => r.text())
                .then(t => {
                    if (t.trim() === "s") {
                        showResponse('success', 'Backup deleted successfully');
                        location.reload();
                    } else {
                        showResponse('danger', 'Backup deletion failed');
                    }
                })
                .catch(() => showResponse('danger', 'Network error'));
        }
    );
}
</script>