<?php
namespace App\Services;

class BackupService {
    private $pdo;
    private $backupDir;

    public function __construct(\PDO $pdo) {
        $this->pdo = $pdo;
        $this->backupDir = dirname(__DIR__, 2) . '/storage/backups';
        if (!is_dir($this->backupDir)) @mkdir($this->backupDir, 0755, true);
    }

    public function createBackup(string $type = 'full'): array {
        $filename = 'backup_' . date('Y-m-d_His') . '_' . $type . '.sql';
        $filepath = $this->backupDir . '/' . $filename;
        
        $tables = $this->pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
        $sql = "-- CIX Orbit Academy Backup\n-- Date: " . date('Y-m-d H:i:s') . "\n-- Type: {$type}\n-- Database: " . DB_NAME . "\n\n";
        
        foreach ($tables as $table) {
            $create = $this->pdo->query("SHOW CREATE TABLE `$table`")->fetch();
            $sql .= "DROP TABLE IF EXISTS `{$table}`;\n" . $create[1] . ";\n\n";
            
            $data = $this->pdo->query("SELECT * FROM `$table`")->fetchAll();
            foreach ($data as $row) {
                $values = array_map(function($v) {
                    if ($v === null) return 'NULL';
                    return "'" . addslashes($v) . "'";
                }, $row);
                $sql .= "INSERT INTO `{$table}` VALUES (" . implode(', ', $values) . ");\n";
            }
            $sql .= "\n";
        }
        
        file_put_contents($filepath, $sql);
        $size = filesize($filepath);
        
        $this->pdo->prepare("INSERT INTO backups (file_name, file_path, file_size, backup_type, created_by) VALUES (?, ?, ?, ?, ?)")
            ->execute([$filename, $filepath, $size, $type, current_user()['id'] ?? null]);
        
        return ['success' => true, 'filename' => $filename, 'size' => $size, 'filepath' => $filepath];
    }

    public function getBackupList(): array {
        return $this->pdo->query("SELECT b.*, u.first_name, u.last_name FROM backups b LEFT JOIN users u ON b.created_by = u.id ORDER BY b.created_at DESC")->fetchAll();
    }

    public function deleteBackup(string $filename): bool {
        $filepath = $this->backupDir . '/' . $filename;
        if (file_exists($filepath)) @unlink($filepath);
        $this->pdo->prepare("DELETE FROM backups WHERE file_name = ?")->execute([$filename]);
        return true;
    }

    public function getBackupListLocal(): array {
        $files = [];
        foreach (glob($this->backupDir . '/backup_*.sql') as $file) {
            $files[] = [
                'filename' => basename($file),
                'size' => filesize($file),
                'modified' => date('Y-m-d H:i:s', filemtime($file)),
            ];
        }
        return $files;
    }
}
