<?php
/**
 * Database Backup Script
 * Automated backup triggered via cron or periodic check
 */

header('Content-Type: application/json');

// Prevent timeout for large databases
set_time_limit(300);
ini_set('memory_limit', '512M');

require_once __DIR__ . '/../includes/config.php';

// Security: Check if called from cron or admin panel
$is_cron = (PHP_SAPI === 'cli');
$is_admin = !empty($_SESSION['user_id']) && $_SESSION['role'] === 'admin';

if (!$is_cron && !$is_admin) {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

// Create backups directory if not exists
$backup_dir = __DIR__ . '/../backups';
if (!is_dir($backup_dir)) {
    mkdir($backup_dir, 0755, true);
}

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

try {
    // Build mysqldump command
    $db_host = DB_SERVER;
    $db_user = DB_USER;
    $db_pass = DB_PASSWORD;
    $db_name = DB_NAME;
    
    // Build command with proper escaping for Windows
    $command = sprintf(
        'mysqldump --host=%s --user=%s --password=%s %s > %s',
        escapeshellarg($db_host),
        escapeshellarg($db_user),
        escapeshellarg($db_pass),
        escapeshellarg($db_name),
        escapeshellarg($backup_file)
    );
    
    // Execute backup
    $output = [];
    $return_var = 0;
    exec($command, $output, $return_var);
    
    if ($return_var !== 0) {
        throw new Exception('mysqldump failed with code ' . $return_var);
    }
    
    // Check if file was created
    if (!file_exists($backup_file)) {
        throw new Exception('Backup file was not created');
    }
    
    $file_size = filesize($backup_file);
    
    // Log backup in database
    $query = "INSERT INTO backup_logs (backup_file, backup_size, backup_type, created_at) 
              VALUES (?, ?, 'automated', NOW())";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('si', $backup_file, $file_size);
    $stmt->execute();
    
    // Clean old backups (keep last 30 days)
    $old_date = date('Y-m-d', strtotime('-30 days'));
    $backups = glob($backup_dir . '/backup_*.sql');
    foreach ($backups as $file) {
        $file_date = basename($file, '.sql');
        $file_date = str_replace('backup_', '', $file_date);
        $file_date = str_replace('_', '-', substr($file_date, 0, 10));
        
        if ($file_date < $old_date && file_exists($file)) {
            unlink($file);
        }
    }
    
    // Return success
    echo json_encode([
        'success' => true,
        'message' => 'Backup created successfully',
        'file' => basename($backup_file),
        'size' => $file_size,
        'timestamp' => $timestamp
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Backup failed: ' . $e->getMessage()
    ]);
}
?>
