<?php
session_start();
header('Content-Type: application/json');

// ❌ 1) SADECE POST
if($_SERVER['REQUEST_METHOD'] !== 'POST'){
    http_response_code(403);
    echo json_encode(["status"=>"error","message"=>"Forbidden"]);
    exit;
}

// ❌ 2) LOGIN KONTROL
if(!isset($_SESSION['user_id']) || !isset($_SESSION['username'])){
    http_response_code(403);
    echo json_encode(["status"=>"error","message"=>"Yetkisiz"]);
    exit;
}

// ❌ 3) SADECE ADMIN
if($_SESSION['username'] !== 'admin'){
    http_response_code(403);
    echo json_encode(["status"=>"error","message"=>"Yetkin yok"]);
    exit;
}

// ❌ 4) CSRF TOKEN KONTROL
if(
    !isset($_POST['token']) ||
    !isset($_SESSION['csrf_token']) ||
    $_POST['token'] !== $_SESSION['csrf_token']
){
    http_response_code(403);
    echo json_encode(["status"=>"error","message"=>"Token hatalı"]);
    exit;
}

include "db.php";

/* ================= BACKUP ================= */

$dir = dirname(__DIR__) . "/backups"; // WEB ROOT DIŞI
if(!is_dir($dir)){
    mkdir($dir, 0700, true);
}

$file = $dir . "/backup_" . date("Y-m-d_H-i-s") . ".sql";
$handle = fopen($file, "w");

$dbName = $baglan->query("SELECT DATABASE()")->fetch_row()[0];

fwrite($handle, "-- Backup: $dbName\n");
fwrite($handle, "-- Date: ".date("Y-m-d H:i:s")."\n\n");

$res = $baglan->query("SHOW TABLES");
while($row = $res->fetch_row()){
    $table = $row[0];

    $row2 = $baglan->query("SHOW CREATE TABLE `$table`")->fetch_row();
    fwrite($handle, "\nDROP TABLE IF EXISTS `$table`;\n");
    fwrite($handle, $row2[1].";\n\n");

    $data = $baglan->query("SELECT * FROM `$table`");
    while($r = $data->fetch_assoc()){
        $cols = array_keys($r);
        $vals = array_map(function($v) use ($baglan){
            return $v === null ? "NULL" : "'".$baglan->real_escape_string($v)."'";
        }, array_values($r));

        fwrite(
            $handle,
            "INSERT INTO `$table` (`".implode("`,`",$cols)."`) VALUES (".implode(",",$vals).");\n"
        );
    }
}

fclose($handle);
chmod($file, 0600);

if(function_exists('addLog')){
    addLog($baglan, "Yedek Alındı", basename($file));
}

echo json_encode([
    "status"=>"ok",
    "message"=>"Yedek alındı"
]);
