<?php
session_start();
require_once('../includes/config.php');

// Check if user is logged in and has admin rights
if (!isset($_SESSION['uid'])) {
    die(json_encode(['success' => false, 'message' => 'Unauthorized access']));
}

// Get database credentials from config
$db_host = $db_host ?? 'localhost';
$db_user = $db_user ?? 'root';
$db_pass = $db_pass ?? '';
$db_name = $db_name ?? 'uzrs-inventorydb';

// Backup source: 'local' or 'cloud'
$backup_source = $_GET['source'] ?? 'local';

// Create backup directory if it doesn't exist
$backup_dir = dirname(__FILE__) . '/../backups';
if (!file_exists($backup_dir)) {
    mkdir($backup_dir, 0755, true);
}

// Check if backup directory is writable
if (!is_writable($backup_dir)) {
    die(json_encode([
        'success' => false, 
        'message' => 'Backup directory is not writable',
        'debug' => 'Directory: ' . $backup_dir
    ]));
}

// Generate backup filename with timestamp and source
$timestamp = date('Y-m-d_H-i-s');
$source_label = ($backup_source == 'cloud') ? 'cloud' : 'local';
$backup_filename = 'backup_' . $db_name . '_' . $source_label . '_' . $timestamp . '.sql';
$backup_filepath = $backup_dir . DIRECTORY_SEPARATOR . $backup_filename;

if ($backup_source == 'local') {
    // LOCAL BACKUP using mysqldump.exe
    
    // Try multiple possible MySQL paths
    $possible_paths = [
        'C:\\wamp64\\bin\\mysql\\mysql8.0.21\\bin\\mysqldump.exe',
        'C:\\wamp64\\bin\\mysql\\mysql8.0.39\\bin\\mysqldump.exe',
        'C:\\wamp\\bin\\mysql\\mysql8.0.21\\bin\\mysqldump.exe',
        'C:\\xampp\\mysql\\bin\\mysqldump.exe',
    ];
    
    $mysqldump_path = null;
    foreach ($possible_paths as $path) {
        if (file_exists($path)) {
            $mysqldump_path = $path;
            break;
        }
    }
    
    // If not found in common locations, try to find it in PATH
    if (!$mysqldump_path) {
        $which_output = shell_exec('where mysqldump 2>nul');
        if ($which_output) {
            $mysqldump_path = trim(explode("\n", $which_output)[0]);
        }
    }
    
    if (!$mysqldump_path || !file_exists($mysqldump_path)) {
        die(json_encode([
            'success' => false, 
            'message' => 'mysqldump.exe not found', 
            'debug' => 'Checked paths: ' . implode(', ', $possible_paths),
            'suggestion' => 'Please install MySQL or run diagnostics'
        ]));
    }
    
    // Build mysqldump command for local database
    $command = "\"$mysqldump_path\" -h $db_host -u $db_user";
    if (!empty($db_pass)) {
        $command .= " -p$db_pass";
    }
    $command .= " --single-transaction --skip-lock-tables --set-gtid-purged=OFF --databases $db_name";
    
    // Execute command and redirect to file
    $full_command = "cmd /c \"$command > \"$backup_filepath\" 2>&1\"";
    $output = shell_exec($full_command);
    
} else {
    // CLOUD/REMOTE BACKUP using PHP MySQLi
    
    // Check if database connection is available
    if (!isset($con) || !$con || mysqli_connect_errno()) {
        die(json_encode([
            'success' => false,
            'message' => 'Database connection failed',
            'debug' => 'Cannot connect to cloud database'
        ]));
    }
    
    // Start building SQL dump
    $sql_dump = "-- MySQL Dump\n";
    $sql_dump .= "-- Host: $db_host\n";
    $sql_dump .= "-- Database: $db_name\n";
    $sql_dump .= "-- Generated on: " . date('Y-m-d H:i:s') . "\n\n";
    $sql_dump .= "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\n";
    $sql_dump .= "SET AUTOCOMMIT = 0;\n";
    $sql_dump .= "START TRANSACTION;\n";
    $sql_dump .= "SET time_zone = \"+00:00\";\n";
    $sql_dump .= "SET FOREIGN_KEY_CHECKS = 0;\n\n";
    $sql_dump .= "CREATE DATABASE IF NOT EXISTS `$db_name`;\n";
    $sql_dump .= "USE `$db_name`;\n\n";
    
    // Get all tables
    $tables_result = mysqli_query($con, "SHOW TABLES");
    if (!$tables_result) {
        die(json_encode([
            'success' => false,
            'message' => 'Failed to get table list',
            'debug' => mysqli_error($con)
        ]));
    }
    
    while ($table_row = mysqli_fetch_row($tables_result)) {
        $table = $table_row[0];
        
        // Add DROP TABLE statement
        $sql_dump .= "-- --------------------------------------------------------\n";
        $sql_dump .= "-- Table structure for table `$table`\n";
        $sql_dump .= "-- --------------------------------------------------------\n\n";
        $sql_dump .= "DROP TABLE IF EXISTS `$table`;\n";
        
        // Get CREATE TABLE statement
        $create_result = mysqli_query($con, "SHOW CREATE TABLE `$table`");
        if ($create_result) {
            $create_row = mysqli_fetch_row($create_result);
            $sql_dump .= $create_row[1] . ";\n\n";
            mysqli_free_result($create_result);
        }
        
        // Get table data
        $data_result = mysqli_query($con, "SELECT * FROM `$table`");
        if ($data_result && mysqli_num_rows($data_result) > 0) {
            $sql_dump .= "-- Dumping data for table `$table`\n\n";
            
            // Get column names
            $fields = mysqli_fetch_fields($data_result);
            $field_names = array_map(function($field) { return "`{$field->name}`"; }, $fields);
            
            while ($data_row = mysqli_fetch_row($data_result)) {
                $values = array_map(function($value) use ($con) {
                    if ($value === null) return 'NULL';
                    return "'" . mysqli_real_escape_string($con, $value) . "'";
                }, $data_row);
                
                $sql_dump .= "INSERT INTO `$table` (" . implode(', ', $field_names) . ") VALUES (" . implode(', ', $values) . ");\n";
            }
            $sql_dump .= "\n";
            mysqli_free_result($data_result);
        }
    }
    
    mysqli_free_result($tables_result);
    
    // Add footer to SQL dump
    $sql_dump .= "SET FOREIGN_KEY_CHECKS = 1;\n";
    $sql_dump .= "COMMIT;\n";
    
    // Write to file
    if (file_put_contents($backup_filepath, $sql_dump) === false) {
        die(json_encode([
            'success' => false,
            'message' => 'Failed to write backup file',
            'debug' => 'Cannot write to: ' . $backup_filepath
        ]));
    }
}

// Wait a moment for file to be written
sleep(1);

// Check if backup was successful
if (file_exists($backup_filepath)) {
    $filesize = filesize($backup_filepath);
    
    if ($filesize > 100) { // At least 100 bytes
        // Set headers for download
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $backup_filename . '"');
        header('Content-Length: ' . $filesize);
        header('Cache-Control: no-cache, must-revalidate');
        header('Pragma: public');
        
        // Clear any previous output
        if (ob_get_level()) ob_end_clean();
        
        // Output file content
        readfile($backup_filepath);
        
        // Optionally delete file after download
        // unlink($backup_filepath);
        
        exit();
    } else {
        // Read first 500 chars of file to see error
        $content = file_get_contents($backup_filepath);
        
        die(json_encode([
            'success' => false, 
            'message' => 'Backup file is too small (possible error)',
            'debug' => 'Size: ' . $filesize . ' bytes',
            'content' => substr($content, 0, 500)
        ]));
    }
} else {
    die(json_encode([
        'success' => false, 
        'message' => 'Failed to create backup file', 
        'debug' => 'File not created at: ' . $backup_filepath,
        'backup_dir_writable' => is_writable($backup_dir) ? 'yes' : 'no'
    ]));
}
?>
