<?php
// backup.php - Modernized backup script (Aug 2025)
require_once '../includes/constants.php';
require_once 'dbinfo.php';

$mysqli = new mysqli($host, $user, $pass, $dbname);
if ($mysqli->connect_errno) {
    die("Database connection failed: " . $mysqli->connect_error);
}

function get_def($mysqli, $table) {
    $def = "DROP TABLE IF EXISTS `$table`;\n";
    $def .= "CREATE TABLE `$table` (\n";

    $fieldsResult = $mysqli->query("SHOW FIELDS FROM `$table`");
    if (!$fieldsResult) {
        die("Table $table not found.");
    }

    while ($row = $fieldsResult->fetch_assoc()) {
        $def .= "  `{$row['Field']}` {$row['Type']}";
        if ($row['Default'] !== null) {
            $def .= " DEFAULT '" . $mysqli->real_escape_string($row['Default']) . "'";
        }
        if ($row['Null'] !== "YES") {
            $def .= " NOT NULL";
        }
        if ($row['Extra']) {
            $def .= " {$row['Extra']}";
        }
        $def .= ",\n";
    }

    $def = rtrim($def, ",\n") . "\n";

    $index = [];
    $keysResult = $mysqli->query("SHOW KEYS FROM `$table`");
    while ($row = $keysResult->fetch_assoc()) {
        $kname = $row['Key_name'];
        if ($kname !== "PRIMARY" && $row['Non_unique'] == 0) {
            $kname = "UNIQUE|$kname";
        }
        $index[$kname][] = $row['Column_name'];
    }

    foreach ($index as $k => $cols) {
        $def .= ",\n";
        if ($k === "PRIMARY") {
            $def .= "  PRIMARY KEY (`" . implode("`, `", $cols) . "`)";
        } elseif (strpos($k, "UNIQUE|") === 0) {
            $def .= "  UNIQUE `" . substr($k, 7) . "` (`" . implode("`, `", $cols) . "`)";
        } else {
            $def .= "  KEY `$k` (`" . implode("`, `", $cols) . "`)";
        }
    }

    $def .= "\n);\n";
    return $def;
}

function get_content($mysqli, $table) {
    $content = "";
    $mysqli->query("LOCK TABLES `$table` WRITE");
    $result = $mysqli->query("SELECT * FROM `$table`");
    
    while ($row = $result->fetch_row()) {
        $values = array_map(function ($val) use ($mysqli) {
            if (!isset($val)) return "NULL";
            if ($val === "") return "''";
            return "'" . $mysqli->real_escape_string($val) . "'";
        }, $row);
        $content .= "INSERT INTO `$table` VALUES (" . implode(",", $values) . ");\n";
    }

    $mysqli->query("UNLOCK TABLES");
    return $content;
}

// Get POST input safely
$tables = $_POST['tables'] ?? [];
$numtables = count($tables);
$structonly = $_POST['structonly'] ?? '';
$title = $_POST['title'] ?? 'Affiliate Backup';

// OS Path
$path = __DIR__ . (stripos(PHP_OS, 'WIN') === 0 ? "\\dump\\" : "/dump/");
if (!is_dir($path)) {
    mkdir($path, 0766, true);
}

$filename = "backup-" . date("d-m-Y") . ".sql";
$filepath = $path . $filename;

if (file_exists($path . "backup.gz")) {
    unlink($path . "backup.gz");
}

$newfile = "# Backup File\n";
$newfile .= "# Created: " . date("Y-m-d H:i:s") . "\n";
$newfile .= "# Database: $dbname\n\n";

foreach ($tables as $table) {
    $table = $mysqli->real_escape_string($table);
    $newfile .= get_def($mysqli, $table) . "\n\n";

    if (strtolower($structonly) !== "yes") {
        $newfile .= get_content($mysqli, $table) . "\n\n";
    }
}

file_put_contents($filepath, $newfile);
chmod($filepath, 0666);
?>

<!DOCTYPE HTML>
<html>
<head>
    <title>Affiliate Network Pro - Admin Panel</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <link rel="stylesheet" type="text/css" href="admin.css">
    <link rel="stylesheet" type="text/css" href="includes/admin.css">
</head>
<body bgcolor="#f4f4f4" link="#000000" alink="#000000" vlink="#000000">
    <table width="914" border="0" align="center" cellpadding="0" cellspacing="0" height="530">
        <tr>
            <td height="114" bgcolor="#FFFFFF">
                <table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                        <td width="341"><img src="images/logo.jpg" width="341" height="112" alt=""></td>
                        <td height="112" align="right" valign="middle"></td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td height="22" bgcolor="#FFFFFF">
                <table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                        <td align="right" width="4"><img src="images/topbar-left.jpg" width="4" height="22"></td>
                        <td class="top-bar-tile">&nbsp;</td>
                        <td align="left" width="4"><img src="images/topbar-right.jpg" width="4" height="22"></td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td bgcolor="#FFFFFF">
                <table width="80%" border="0" cellspacing="0" class="tablebdr" align="center">
                    <tr>
                        <td height="26" valign="top" class="tdhead"><b>Partners Backup ::</b></td>
                    </tr>
                    <tr><td>&nbsp;</td></tr>
                    <tr>
                        <td height="100" valign="top" align="center">
                            <strong>Your Backup request was processed Successfully.</strong>
                            <br>
                            <font size="2">Use Restore Option to Restore the Backup data</font>
                        </td>
                    </tr>
                    <tr>
                        <td height="27" align="right" valign="top" class="tdbackbold">
                            <small><a href="backupstart.php">Go Back to Main Screen &raquo;</a></small>
                        </td>
                    </tr>
                    <tr>
                        <td height="15" valign="top" bgcolor="#FFFFFF">
                            <div align="right"><font color="#9999CC" face="Arial, Helvetica, sans-serif" style="font-size:6Pt"></font></div>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td align="center" class="footer-bg"><?php include "footer.php"; ?></td>
        </tr>
    </table>
</body>
</html>
