<?php if(defined('TENANT_URL') && !empty(TENANT_URL)) {
    $_REQUEST['tenant'] = TENANT_URL;
}


if(file_exists('../../../'.$_REQUEST['tenant'].'/config.php')){require_once('../../../'.$_REQUEST['tenant'].'/config.php');}
if(file_exists('/config.php')){require_once('/config.php'); }

ini_set('memory_limit', '512M');
if (isset($_POST['action']) && $_POST['action'] === 'delete') {
    $filename = basename($_POST['filename'] ?? '');
    if ($filename === '') { echo 'e'; exit; }

    // default to manual folder if no path supplied
    $relPath = trim($_POST['path'] ?? 'backups', '/');

    // EXACT same base as your working code
    $filePath = '../../..' . TENANT_URL . '/' . $relPath . '/' . $filename;

    if (is_file($filePath) && unlink($filePath)) {
        echo 's';
    } else {
        echo 'e';
    }
    exit;
}


function dbbackup($host,$user,$pass,$name,$tables=false, $backup_name=false)
{ 
set_time_limit(3000); 
$mysqli = new mysqli($host,$user,$pass,$name); 
$mysqli->select_db($name); 
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES'); 
while($row = $queryTables->fetch_row()) 
{ 
    $target_tables[] = $row[0]; 
}   
if($tables !== false) 
{
    $target_tables = array_intersect( $target_tables, $tables); 
} 
$content = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8 */;\r\n--\r\n-- Database: `".$name."`\r\n--\r\n\r\n\r\n";
foreach($target_tables as $table)
{
    if (empty($table))
    {
        continue;
    } 
    $result = $mysqli->query('SELECT * FROM `'.$table.'`');     $fields_amount=$result->field_count;  $rows_num=$mysqli->affected_rows;     $res = $mysqli->query('SHOW CREATE TABLE '.$table); $TableMLine=$res->fetch_row(); 
    $content .= "\n\n".$TableMLine[1].";\n\n";   $TableMLine[1]=str_ireplace('CREATE TABLE `','CREATE TABLE IF NOT EXISTS `',$TableMLine[1]);
    for ($i = 0, $st_counter = 0; $i < $fields_amount;   $i++, $st_counter=0) 
    {
        while($row = $result->fetch_row())  
        {
            if ($st_counter%100 == 0 || $st_counter == 0 )  
            {
                $content .= "\nINSERT INTO ".$table." VALUES";
            }
            $content .= "\n(";    
            for($j=0; $j<$fields_amount; $j++)
            {
                $row[$j] = str_replace("\n","\\n", addslashes($row[$j]) ); 
                if (isset($row[$j]))
                {
                    $content .= '"'.$row[$j].'"' ;
                } 
                else
                {
                    $content .= '""';
                }
                if ($j<($fields_amount-1))
                {
                    $content.= ',';
                }  
            }
            $content .=")";
            if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) 
            {
                $content .= ";";
            }
            else
            {
                $content .= ",";
            }
            $st_counter=$st_counter+1;
        }
    } $content .="\n\n\n";
}
$content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
ob_get_clean(); 
$filename = '../../..'.TENANT_URL.'/backups/database-backup_' . date("d-m-Y_H-i-s") . '.sql';
$file = $filename;
file_put_contents($file, $content);
echo "s";
}

function csvbackup($host, $user, $pass, $name, $tableName = null)
{
    set_time_limit(3000);
    $mysqli = new mysqli($host, $user, $pass, $name);
    $mysqli->select_db($name);
    $mysqli->query("SET NAMES 'utf8'");

    // CSV backup for specific table
    $csvFilename = '../../..' . TENANT_URL . '/backups/' . $tableName . '_' . date("d-m-Y") . '.csv';
    $output = fopen($csvFilename, 'w');
    $result = $mysqli->query("SELECT * FROM $tableName");

    // Write CSV header
    $header = [];
    while ($fieldInfo = $result->fetch_field()) {
        $header[] = $fieldInfo->name;
    }
    fputcsv($output, $header);

    // Write table data to CSV
    while ($row = $result->fetch_assoc()) {
        foreach ($row as $column => &$value) {
            // Check for columns containing "date" in the name
            if (strpos($column, 'date') !== false) {
                if (empty($value)) {
                    // If the value is blank, set to "Not Known"
                    $value = "Not Known";
                } elseif (is_numeric($value)) {
                    // If value is numeric, assume it's a UNIX timestamp and format it
                    $value = date('d-m-Y', $value);
                }
            }
            if (strpos($column, 'Date') !== false) {
                if (empty($value)) {
                    // If the value is blank, set to "Not Known"
                    $value = "Not Known";
                } elseif (is_numeric($value)) {
                    // If value is numeric, assume it's a UNIX timestamp and format it
                    $value = date('d-m-Y', $value);
                }
            }
            // Special handling for the "delivery" column
            elseif ($column === 'delivery') {
                if (empty($value) || $value == 0) {
                    // If blank or 0, set to "undelivered"
                    $value = "undelivered";
                } elseif (is_numeric($value)) {
                    // Convert the UNIX timestamp to date format if numeric
                    $value = date('d-m-Y', $value);
                }
            }
        }
        fputcsv($output, $row);
    }

    fclose($output);
    $mysqli->close();

    echo "s";
}




if ($_POST['action'] == 'csvbackup') {
    $tableName = isset($_POST['table']) ? $_POST['table'] : null; // Table name for CSV backup (null for complete SQL backup)
    csvbackup("localhost", $dbUsr, $dbpass, $dbSrc."$dbTenant", $tableName);
}

if ($_POST['action'] == 'dbbackup') {
    dbbackup("localhost", $dbUsr, $dbpass,$dbSrc."$dbTenant") ;
}
?>