<?php
session_start();

// Check if this is a download request
$action = isset($_GET['action']) ? $_GET['action'] : '';

if ($action === 'download') {
    // Handle file download
    if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
        http_response_code(403);
        die('Unauthorized');
    }

    $filename = isset($_GET['file']) ? basename($_GET['file']) : '';
    
    if (empty($filename) || strpos($filename, '..') !== false) {
        http_response_code(400);
        die('Invalid filename');
    }

    $backup_dir = __DIR__ . '/../backups';
    $filepath = $backup_dir . '/' . $filename;

    if (!file_exists($filepath)) {
        http_response_code(404);
        die('Backup file not found');
    }

    // Serve the file
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');
    header('Content-Length: ' . filesize($filepath));
    header('Cache-Control: no-cache, no-store, must-revalidate');
    header('Pragma: no-cache');
    header('Expires: 0');
    readfile($filepath);
    exit;
}

// CREATE BACKUP PROCESS
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', '0');
ob_start();

try {
    // Check if user is logged in and is admin
    if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
        throw new Exception('Unauthorized access');
    }

    // Get database credentials
    $db_host = 'localhost';
    $db_user = 'zemaraim';
    $db_password = '8wwxk]-X3Kx]CJ]5';
    $db_name = 'zemaraim_interior';

    // Create connection
    $conn = new mysqli($db_host, $db_user, $db_password, $db_name);

    // Check connection
    if ($conn->connect_error) {
        throw new Exception('Database connection failed: ' . $conn->connect_error);
    }

    $conn->set_charset("utf8");

    // Create backups directory
    $backup_dir = __DIR__ . '/../backups';
    if (!is_dir($backup_dir)) {
        if (!mkdir($backup_dir, 0755, true)) {
            throw new Exception('Failed to create backups directory');
        }
    }

    // Generate backup filename
    $timestamp = date('Y-m-d_H-i-s');
    $backup_filename = 'backup_' . $timestamp . '.sql';
    $backup_filepath = $backup_dir . '/' . $backup_filename;

    // Create backups table if it doesn't exist
    $create_table_sql = "CREATE TABLE IF NOT EXISTS database_backups (
        id INT PRIMARY KEY AUTO_INCREMENT,
        admin_id INT NOT NULL,
        filename VARCHAR(255) NOT NULL,
        filepath VARCHAR(500),
        size BIGINT,
        status ENUM('pending', 'completed', 'failed') DEFAULT 'pending',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_admin_id (admin_id),
        INDEX idx_status (status),
        INDEX idx_created_at (created_at)
    )";

    if (!$conn->query($create_table_sql)) {
        throw new Exception('Failed to create backups table: ' . $conn->error);
    }

    // Get all tables
    $result = $conn->query("SHOW TABLES FROM `" . $db_name . "`");

    if (!$result) {
        throw new Exception('Failed to retrieve tables: ' . $conn->error);
    }

    $tables = array();
    while ($row = $result->fetch_row()) {
        $tables[] = $row[0];
    }

    if (empty($tables)) {
        throw new Exception('No tables found in database');
    }

    // Build backup content
    $backup_content = "-- Database Backup\n";
    $backup_content .= "-- Generated: " . date('Y-m-d H:i:s') . "\n";
    $backup_content .= "-- Database: " . $db_name . "\n\n";
    $backup_content .= "SET FOREIGN_KEY_CHECKS = 0;\n\n";

    foreach ($tables as $table) {
        // Skip backup table to avoid recursion
        if ($table === 'database_backups') {
            continue;
        }

        $backup_content .= "DROP TABLE IF EXISTS `" . $table . "`;\n";

        // Get CREATE TABLE statement
        $create_result = $conn->query("SHOW CREATE TABLE `" . $db_name . "`.`" . $table . "`");
        if ($create_result) {
            $create_row = $create_result->fetch_row();
            $backup_content .= $create_row[1] . ";\n\n";
        }

        // Get table data
        $data_result = $conn->query("SELECT * FROM `" . $db_name . "`.`" . $table . "`");

        if ($data_result && $data_result->num_rows > 0) {
            while ($data_row = $data_result->fetch_assoc()) {
                $values = array();
                foreach ($data_row as $value) {
                    if ($value === null) {
                        $values[] = "NULL";
                    } else {
                        $values[] = "'" . $conn->real_escape_string($value) . "'";
                    }
                }
                $backup_content .= "INSERT INTO `" . $table . "` VALUES (" . implode(", ", $values) . ");\n";
            }
            $backup_content .= "\n";
        }
    }

    $backup_content .= "SET FOREIGN_KEY_CHECKS = 1;\n";

    // Write backup to file
    if (!file_put_contents($backup_filepath, $backup_content)) {
        throw new Exception('Failed to write backup file');
    }

    // Get file size
    $file_size = filesize($backup_filepath);

    // Record backup in database
    $user_id = $_SESSION['user_id'];
    $insert_sql = "INSERT INTO database_backups (admin_id, filename, filepath, size, status, created_at) VALUES (?, ?, ?, ?, 'completed', NOW())";
    $stmt = $conn->prepare($insert_sql);

    if ($stmt) {
        $stmt->bind_param('issi', $user_id, $backup_filename, $backup_filepath, $file_size);
        $stmt->execute();
        $stmt->close();
    }

    $conn->close();

    // Clear output buffer
    ob_end_clean();

    // Return success with download URL
    echo json_encode([
        'success' => true,
        'message' => 'Database backup created successfully',
        'filename' => $backup_filename,
        'timestamp' => $timestamp,
        'download_url' => 'api/backup-database.php?action=download&file=' . urlencode($backup_filename)
    ]);

} catch (Exception $e) {
    ob_end_clean();
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>


