<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');
require_once('../lib/dbclass.php');




// MySQL connection details
$host     = 'localhost'; // MySQL host
$username = DB_USERNAME;  // MySQL username
$password = DB_PASSWORD;      // MySQL password
$database = DB_NAME; // Database name



// Connect to the database
$conn = new mysqli($host, $username, $password, $database);

if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}

// Set backup file name

$backupFolder = 'DBBackup/'; // Replace with the desired folder path
$files        = glob($backupFolder . '*.sql'); // Get all .sql files in the folder

if (count($files) <= 1) {
    echo 'Nothing to delete. One or no files found.';
    //return;
}

// Sort files by modification time descending
usort($files, function ($a, $b) {
    return filemtime($b) - filemtime($a);
});

$latestFile = $files[0];

// Delete all others
for ($i = 1; $i < count($files); $i++) {
    unlink($files[$i]);
}

// Create the backup file name
$backupFile = $backupFolder . 'backup_' . $database . '_' . date('Y-m-d_H-i-s') . '.sql';

// Open a file to write the backup data
$file = fopen($backupFile, 'w');

// Write the table structure to the backup file
$result = $conn->query('SHOW TABLES');
while ($row = $result->fetch_row()) {
    $table            = $row[0];
    $createTableQuery = $conn->query("SHOW CREATE TABLE $table");
    $createTableRow   = $createTableQuery->fetch_row();
    fwrite($file, $createTableRow[1] . ";\n\n");

    // Write the table data to the backup file
    $tableData = $conn->query("SELECT * FROM $table");
    while ($dataRow = $tableData->fetch_assoc()) {
        $values = array_map(function ($value) {
            return "'" . addslashes($value) . "'";
        }, $dataRow);
        $sql = "INSERT INTO $table VALUES(" . implode(', ', $values) . ");\n";
        fwrite($file, $sql);
    }
    fwrite($file, "\n\n");
}

fclose($file);
$conn->close();

echo "Backup created successfully: $backupFile";




date_default_timezone_set('Asia/Kolkata');

updateQuery('DELETE FROM `tbl_transaction`
WHERE `Received` = 0
  AND DATE(`dateadded`) < (CURDATE() - INTERVAL 7 DAY);
');



updateQuery('delete from tbl_customer where id not in (select `customerid` from tbl_transaction)');

?>

