<?php

/**

 * Fichier  : backup_cron.php

 * Auteur   : KREMER Régis

 * Version  : 2.2.0

 * Date     : 2026-02-21

 * Description : Script cron de sauvegarde automatique quotidienne

 *

 * Changelog :

 *   v2.1.0 (2026-02-21) — Version initiale auditée et sécurisée

 *   v2.1.1 (2026-02-21) — Corrections sécurité (CSRF, MIME, session, migrateSuppliers)

 *   v2.2.0 (2026-02-21) — Permissions magasins, bons de commande, rapport d'écart,

 *                      import CSV, historique prix, bon de livraison multi-lignes

 */

// ================================================================

// STOCKMASTER PRO V2.1 — backup_cron.php

// Automatic backup script (run via cron)

// Usage: 0 2 * * * php /path/to/backup_cron.php

// ================================================================



require_once __DIR__.'/config.php';



$backupDir = BACKUPS_DIR;

if (!is_dir($backupDir)) {

    mkdir($backupDir, 0775, true);

}



$date = date('Y-m-d_H-i-s');

$filename = "backup_{$date}.json";



// Collect all data

$entities = [

    'products', 'stock', 'movements', 'warehouses', 'suppliers', 

    'categories', 'alerts', 'inventories', 'users', 'settings', 

    'purchase_prices'

];



$data = [];

foreach($entities as $entity) {

    $data[$entity] = loadData($entity);

}



// Add metadata

$data['_backup_meta'] = [

    'version' => APP_VER,

    'date' => date('c'),

    'entities' => $entities,

    'total_products' => count($data['products'] ?? []),

    'total_movements' => count($data['movements'] ?? []),

];



// Write backup file

$backupPath = $backupDir . '/' . $filename;

file_put_contents(

    $backupPath,

    json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)

);



echo "✓ Backup created: {$filename}\n";

echo "  Path: {$backupPath}\n";

echo "  Size: " . number_format(filesize($backupPath) / 1024, 2) . " KB\n";



// Cleanup: keep only last 30 backups

$backups = glob($backupDir . '/backup_*.json');

usort($backups, fn($a,$b) => filemtime($b) - filemtime($a));



$deleted = 0;

foreach (array_slice($backups, 30) as $old) {

    if(@unlink($old)) {

        $deleted++;

    }

}



if($deleted > 0) {

    echo "✓ Cleaned up {$deleted} old backup(s)\n";

}



echo "✓ Total backups: " . min(count($backups), 30) . "\n";

?>

