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

// Check admin access
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    redirectWithMessage(APP_URL . '/admin/dashboard.php', 'Acces refuzat', 'error');
}

// Handle manual backup request
if ($_POST['action'] === 'backup_now') {
    // Trigger backup
    $backup_output = shell_exec('php ' . escapeshellarg(__DIR__ . '/backup-scheduler.php'));
    $backup_result = json_decode($backup_output, true);
}

// Get backup history
$backups_query = "SELECT * FROM backup_logs ORDER BY created_at DESC LIMIT 50";
$backups_result = $conn->query($backups_query);
$backups = [];
while ($backup = $backups_result->fetch_assoc()) {
    $backups[] = $backup;
}

// Get backup files
$backup_dir = __DIR__ . '/../backups';
$backup_files = [];
if (is_dir($backup_dir)) {
    $files = glob($backup_dir . '/backup_*.sql');
    if ($files) {
        usort($files, function($a, $b) {
            return filemtime($b) - filemtime($a);
        });
        
        foreach ($files as $file) {
            $backup_files[] = [
                'path' => $file,
                'name' => basename($file),
                'size' => filesize($file),
                'mtime' => filemtime($file),
                'mtime_formatted' => date('Y-m-d H:i:s', filemtime($file))
            ];
        }
    }
}

$page_title = 'Backup Bază de Date';
require_once __DIR__ . '/../includes/header.php';
?>

<div style="max-width:1000px">
    <!-- ACTION SECTION -->
    <div class="card" style="margin-bottom:16px">
        <div class="card-body">
            <div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap">
                <form method="POST" style="display:flex;align-items:center;gap:10px">
                    <input type="hidden" name="action" value="backup_now">
                    <button type="submit" class="btn btn-primary" style="display:flex;align-items:center;gap:6px">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="23 6 13.5 15.5 2 4">
                            </polyline><polyline points="13.5 15.5 23 6 23 19 2 19 15.5 5.5"></polyline>
                        </svg>
                        Backup Acum
                    </button>
                </form>
                
                <?php if (isset($backup_result)): ?>
                    <div style="padding:8px 12px;border-radius:8px;background:<?php echo $backup_result['status'] === 'success' ? 'var(--green)' : 'var(--red)'; ?>20;color:<?php echo $backup_result['status'] === 'success' ? 'var(--green)' : 'var(--red)'; ?>;font-size:13px">
                        <?php echo htmlspecialchars($backup_result['message'] ?? $backup_result['error'] ?? 'Unknown'); ?>
                    </div>
                <?php endif; ?>
                
                <div style="flex:1"></div>
                
                <div style="font-size:12px;color:var(--text3);text-align:right">
                    <div>Sistem backup: <strong>Activ</strong></div>
                    <div style="margin-top:2px">Interval: <strong>Fiecare 12 ore</strong></div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- STATISTICS -->
    <div class="form-grid c3" style="margin-bottom:16px">
        <div class="card">
            <div class="card-body">
                <div style="font-size:12px;color:var(--text3);font-weight:600">Total Backups</div>
                <div style="font-size:28px;font-weight:700;color:var(--accent);margin-top:6px"><?php echo count($backup_files); ?></div>
            </div>
        </div>
        
        <div class="card">
            <div class="card-body">
                <div style="font-size:12px;color:var(--text3);font-weight:600">Mărime Totală</div>
                <?php 
                    $total_size = array_sum(array_map(function($f) { return $f['size']; }, $backup_files));
                    $size_mb = $total_size / 1024 / 1024;
                ?>
                <div style="font-size:28px;font-weight:700;color:var(--blue);margin-top:6px"><?php echo number_format($size_mb, 2); ?> MB</div>
            </div>
        </div>
        
        <div class="card">
            <div class="card-body">
                <div style="font-size:12px;color:var(--text3);font-weight:600">Cel Mai Nou Backup</div>
                <div style="font-size:13px;color:var(--text);margin-top:6px">
                    <?php echo count($backup_files) > 0 ? $backup_files[0]['mtime_formatted'] : 'Niciun backup'; ?>
                </div>
            </div>
        </div>
    </div>
    
    <!-- BACKUP FILES LIST -->
    <div class="card">
        <div class="card-header">
            <div class="card-title">Fișiere Backup (Ultimi 50)</div>
        </div>
        <div class="card-body" style="padding:0">
            <?php if (count($backup_files) > 0): ?>
                <div style="overflow-x:auto">
                    <table style="width:100%;border-collapse:collapse">
                        <thead>
                            <tr style="background:var(--bg3);border-bottom:1px solid var(--border)">
                                <th style="padding:12px 16px;text-align:left;font-size:12px;color:var(--text3);font-weight:600;text-transform:uppercase">Fișier</th>
                                <th style="padding:12px 16px;text-align:right;font-size:12px;color:var(--text3);font-weight:600;text-transform:uppercase">Mărime</th>
                                <th style="padding:12px 16px;text-align:center;font-size:12px;color:var(--text3);font-weight:600;text-transform:uppercase">Data Creării</th>
                                <th style="padding:12px 16px;text-align:center;font-size:12px;color:var(--text3);font-weight:600;text-transform:uppercase">Acțiuni</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($backup_files as $idx => $file): ?>
                                <tr style="border-bottom:1px solid var(--border)<?php echo $idx === 0 ? ';background:var(--bg3)' : ''; ?>">
                                    <td style="padding:12px 16px;font-size:13px;font-family:monospace;word-break:break-all">
                                        <code style="background:var(--bg4);padding:4px 8px;border-radius:6px"><?php echo $file['name']; ?></code>
                                    </td>
                                    <td style="padding:12px 16px;font-size:13px;text-align:right;font-weight:600">
                                        <?php echo number_format($file['size'] / 1024 / 1024, 2); ?> MB
                                    </td>
                                    <td style="padding:12px 16px;font-size:13px;text-align:center;color:var(--text2)">
                                        <?php echo $file['mtime_formatted']; ?>
                                        <?php if ($idx === 0): ?>
                                            <span style="display:inline-block;background:var(--green);color:white;padding:2px 8px;border-radius:4px;font-size:11px;margin-left:6px">NEWEST</span>
                                        <?php endif; ?>
                                    </td>
                                    <td style="padding:12px 16px;text-align:center">
                                        <a href="<?php echo APP_URL; ?>/admin/download-backup.php?file=<?php echo urlencode($file['name']); ?>" class="btn btn-sm" style="display:inline-flex;align-items:center;gap:4px;padding:6px 10px;background:var(--bg4);border:1px solid var(--border);border-radius:6px;color:var(--accent);text-decoration:none;font-size:12px;cursor:pointer">
                                            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                                                <polyline points="7 10 12 15 17 10"></polyline>
                                                <line x1="12" y1="15" x2="12" y2="3"></line>
                                            </svg>
                                            Download
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div style="padding:40px;text-align:center;color:var(--text3)">
                    <div style="font-size:14px;margin-bottom:8px">Niciun backup disponibil</div>
                    <div style="font-size:12px">Creați un backup manual pentru a vedea fișierele</div>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- SETUP INSTRUCTIONS -->
    <div class="card" style="margin-top:16px">
        <div class="card-header">
            <div class="card-title">🔧 Configurație Backup Automat (Cron)</div>
        </div>
        <div class="card-body">
            <div style="background:var(--bg4);border:1px solid var(--border);border-radius:10px;padding:14px;margin-bottom:12px">
                <div style="font-size:12px;color:var(--text3);margin-bottom:8px;text-transform:uppercase;font-weight:600">Pentru Linux/Mac (crontab):</div>
                <div style="background:var(--bg3);border-left:3px solid var(--accent);padding:10px;border-radius:6px;font-family:monospace;font-size:12px;word-break:break-all;color:var(--text2)">
                    0 12 * * * /usr/bin/php /path/to/crm-php/api/backup-scheduler.php
                </div>
                <div style="font-size:11px;color:var(--text3);margin-top:6px">
                    Aceasta rulează backupul la 12:00 (prânz) zilnic
                </div>
            </div>
            
            <div style="background:var(--bg4);border:1px solid var(--border);border-radius:10px;padding:14px">
                <div style="font-size:12px;color:var(--text3);margin-bottom:8px;text-transform:uppercase;font-weight:600">Pentru Windows (Task Scheduler):</div>
                <ol style="margin:0;padding-left:20px;color:var(--text2);font-size:12px">
                    <li>Deschideți <strong>Task Scheduler</strong></li>
                    <li>Creați o nouă task programată</li>
                    <li>Setați declanșatorul pentru 12:00 zilnic</li>
                    <li>SetAcțiunea: <code>C:\xampp\php\php.exe -f C:\xampp\htdocs\Efim\crm-php\api\backup-scheduler.php</code></li>
                </ol>
            </div>
            
            <div style="background:var(--green)20;border:1px solid var(--green);border-radius:10px;padding:12px;margin-top:12px;color:var(--green);font-size:12px">
                ✓ Backupurile se șterg automat după 30 de zile
            </div>
        </div>
    </div>
</div>

<?php
require_once __DIR__ . '/../includes/footer.php';
?>
