<?php
/**
 * Database Backup
 * Create and manage database backups
 */

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

requireAdmin();

$pdo = getDB();
$error = '';
$success = '';
$backupDir = '../../backups/';

// Create backup directory if not exists
if (!is_dir($backupDir)) {
    mkdir($backupDir, 0755, true);
}

// Handle backup creation
if (isset($_POST['create_backup'])) {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = "Security token validation failed.";
    } else {
        $backupFile = $backupDir . 'backup_' . date('Y-m-d_H-i-s') . '.sql';
        
        // Get all tables
        $tables = [];
        $stmt = $pdo->query("SHOW TABLES");
        while ($row = $stmt->fetch()) {
            $tables[] = $row[0];
        }
        
        $backupContent = "-- Homoeopathy System Database Backup\n";
        $backupContent .= "-- Generated: " . date('Y-m-d H:i:s') . "\n";
        $backupContent .= "-- Tables: " . implode(', ', $tables) . "\n\n";
        
        foreach ($tables as $table) {
            // Get create table syntax
            $stmt = $pdo->query("SHOW CREATE TABLE `$table`");
            $createTable = $stmt->fetch();
            $backupContent .= "DROP TABLE IF EXISTS `$table`;\n";
            $backupContent .= $createTable['Create Table'] . ";\n\n";
            
            // Get data
            $stmt = $pdo->query("SELECT * FROM `$table`");
            $rows = $stmt->fetchAll();
            
            if (!empty($rows)) {
                $columns = array_keys($rows[0]);
                $backupContent .= "INSERT INTO `$table` (`" . implode('`, `', $columns) . "`) VALUES\n";
                
                $values = [];
                foreach ($rows as $row) {
                    $rowValues = [];
                    foreach ($row as $value) {
                        if ($value === null) {
                            $rowValues[] = "NULL";
                        } else {
                            $rowValues[] = "'" . addslashes($value) . "'";
                        }
                    }
                    $values[] = "(" . implode(', ', $rowValues) . ")";
                }
                $backupContent .= implode(",\n", $values) . ";\n\n";
            }
        }
        
        if (file_put_contents($backupFile, $backupContent)) {
            $success = "Backup created successfully: " . basename($backupFile);
        } else {
            $error = "Failed to create backup";
        }
    }
}

// Handle backup deletion
if (isset($_GET['delete'])) {
    $file = basename($_GET['delete']);
    $filePath = $backupDir . $file;
    
    if (file_exists($filePath) && pathinfo($filePath, PATHINFO_EXTENSION) == 'sql') {
        if (unlink($filePath)) {
            $success = "Backup deleted successfully";
        } else {
            $error = "Failed to delete backup";
        }
    } else {
        $error = "Backup file not found";
    }
}

// Get list of backups
$backups = glob($backupDir . '*.sql');
usort($backups, function($a, $b) {
    return filemtime($b) - filemtime($a);
});

// Calculate total backup size
$totalSize = 0;
foreach ($backups as $backup) {
    $totalSize += filesize($backup);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Database Backup - Admin Panel</title>
    <link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/vendor/fontawesome/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background: #2c3e50;
        }
        .sidebar .nav-link {
            color: #ecf0f1;
            padding: 12px 20px;
        }
        .sidebar .nav-link:hover {
            background: #34495e;
        }
        .sidebar .nav-link.active {
            background: #3498db;
        }
        .main-content {
            background: #f8f9fa;
            min-height: 100vh;
        }
        .top-navbar {
            background: white;
            padding: 15px 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .backup-item {
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .backup-item:hover {
            box-shadow: 0 2px 6px rgba(0,0,0,0.15);
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-2 p-0 sidebar">
                <div class="text-center py-4">
                    <h4 class="text-white">🏥 Admin</h4>
                </div>
                <nav class="nav flex-column">
                    <a class="nav-link" href="../dashboard.php">Dashboard</a>
                    <a class="nav-link" href="../doctors/index.php">Doctors</a>
                    <a class="nav-link" href="../subscriptions/index.php">Subscriptions</a>
                    <a class="nav-link" href="../rubrics/index.php">Rubrics</a>
                    <a class="nav-link" href="../remedies/index.php">Remedies</a>
                    <a class="nav-link active" href="index.php">Settings</a>
                    <a class="nav-link" href="backup.php">Backup</a>
                    <a class="nav-link" href="system-info.php">System Info</a>
                    <a class="nav-link" href="../profile.php">Profile</a>
                    <hr>
                    <a class="nav-link" href="../../logout.php">Logout</a>
                </nav>
            </div>
            
            <div class="col-md-10 main-content">
                <div class="top-navbar">
                    <h4 class="mb-0"><i class="fas fa-database"></i> Database Backup</h4>
                </div>
                
                <div class="p-4">
                    <?php if ($success): ?>
                        <div class="alert alert-success"><?php echo $success; ?></div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger"><?php echo $error; ?></div>
                    <?php endif; ?>
                    
                    <div class="row">
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-header">Create New Backup</div>
                                <div class="card-body">
                                    <form method="POST">
                                        <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                        <input type="hidden" name="create_backup" value="1">
                                        <p>Create a complete backup of your database including all tables, rubrics, remedies, cases, and settings.</p>
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="fas fa-plus"></i> Create Backup
                                        </button>
                                    </form>
                                </div>
                            </div>
                            
                            <div class="card mt-3">
                                <div class="card-header">Backup Statistics</div>
                                <div class="card-body">
                                    <div><strong>Total Backups:</strong> <?php echo count($backups); ?></div>
                                    <div><strong>Total Size:</strong> <?php echo formatFileSize($totalSize); ?></div>
                                    <div><strong>Backup Directory:</strong> <?php echo $backupDir; ?></div>
                                </div>
                            </div>
                            
                            <div class="card mt-3">
                                <div class="card-header">Schedule Backup (Cron)</div>
                                <div class="card-body">
                                    <p>To schedule automatic daily backups, add this to your crontab:</p>
                                    <code class="d-block bg-light p-2 rounded small">
                                        0 2 * * * php <?php echo dirname(__DIR__, 3); ?>/scripts/backup-database.php
                                    </code>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-8">
                            <div class="card">
                                <div class="card-header">
                                    Available Backups
                                    <span class="float-end text-muted small">Oldest backups are automatically deleted after 30 days</span>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($backups)): ?>
                                        <p class="text-muted text-center">No backups found. Click "Create Backup" to generate one.</p>
                                    <?php else: ?>
                                        <?php foreach ($backups as $backup): ?>
                                            <?php
                                            $filename = basename($backup);
                                            $size = formatFileSize(filesize($backup));
                                            $date = date('d-m-Y H:i:s', filemtime($backup));
                                            $daysOld = floor((time() - filemtime($backup)) / 86400);
                                            ?>
                                            <div class="backup-item">
                                                <div class="row align-items-center">
                                                    <div class="col-md-6">
                                                        <strong><i class="fas fa-archive"></i> <?php echo $filename; ?></strong><br>
                                                        <small class="text-muted">Created: <?php echo $date; ?> (<?php echo $daysOld; ?> days ago)</small>
                                                    </div>
                                                    <div class="col-md-3">
                                                        <span class="badge bg-secondary"><?php echo $size; ?></span>
                                                    </div>
                                                    <div class="col-md-3 text-end">
                                                        <a href="restore.php?file=<?php echo urlencode($filename); ?>" class="btn btn-warning btn-sm">
                                                            <i class="fas fa-undo"></i> Restore
                                                        </a>
                                                        <a href="?delete=<?php echo urlencode($filename); ?>" class="btn btn-danger btn-sm" 
                                                           onclick="return confirm('Delete this backup?')">
                                                            <i class="fas fa-trash"></i>
                                                        </a>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <div class="alert alert-info mt-3">
                                <i class="fas fa-info-circle"></i>
                                <strong>Backup Tips:</strong>
                                <ul class="mb-0 mt-2">
                                    <li>Always download important backups to your local machine</li>
                                    <li>Regular backups are automatically created via cron job</li>
                                    <li>Backups include all data: rubrics, remedies, cases, subscriptions</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>