<?php
session_start();
require_once 'db.php';

// Check if user is logged in and is an Admin
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'Admin') {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$action = $_GET['action'] ?? '';

if ($action === 'download') {
    try {
        // Clear buffer to avoid unwanted output
        if (ob_get_level()) ob_end_clean();

        $tables = [];
        $result = $pdo->query("SHOW TABLES");
        while ($row = $result->fetch(PDO::FETCH_NUM)) {
            $tables[] = $row[0];
        }

        $return = "-- JUSTSALE POS Database Backup\n";
        $return .= "-- Generated: " . date('Y-m-d H:i:s') . "\n";
        $return .= "-- Version: " . SYSTEM_VERSION . "\n\n";
        $return .= "SET FOREIGN_KEY_CHECKS=0;\n\n";

        foreach ($tables as $table) {
            // Create table structure
            $stmt = $pdo->query("SHOW CREATE TABLE `$table` ");
            $row2 = $stmt->fetch(PDO::FETCH_NUM);
            $return .= "\n\n" . $row2[1] . ";\n\n";

            // Get data
            $stmt = $pdo->query("SELECT * FROM `$table` ");
            $num_fields = $stmt->columnCount();

            while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
                $return .= "INSERT INTO `$table` VALUES(";
                for ($j = 0; $j < $num_fields; $j++) {
                    if (isset($row[$j])) {
                        // Secure against SQL injection by escaping correctly
                        $value = $row[$j];
                        $value = str_replace("\n", "\\n", addslashes($value));
                        $return .= '"' . $value . '"';
                    } else {
                        $return .= 'NULL';
                    }
                    if ($j < ($num_fields - 1)) {
                        $return .= ',';
                    }
                }
                $return .= ");\n";
            }
            $return .= "\n\n\n";
        }

        $return .= "SET FOREIGN_KEY_CHECKS=1;";

        // Set headers for download
        $filename = 'justsale_backup_' . date('Y-m-d_H-i-s') . '.sql';
        header('Content-Type: application/sql');
        header('Content-Disposition: attachment; filename=' . $filename);
        header('Content-Length: ' . strlen($return));
        
        echo $return;
        exit;

    } catch (Exception $e) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Backup failed: ' . $e->getMessage()]);
        exit;
    }
} else {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
}
