<?php
/**
 * Backup Automation Scheduler
 * 
 * This script checks if it's time to run a backup and executes it.
 * Can be called hourly via cron job for automatic backups at specific times.
 * 
 * Setup cron job (Linux/Mac):
 * # Run every day at 12:00 noon
 * 0 12 * * * /usr/bin/php /path/to/crm-php/api/backup-scheduler.php
 * 
 * # Or run hourly and let the script decide when to backup
 * 0 * * * * /usr/bin/php /path/to/crm-php/api/backup-scheduler.php
 */

// Prevent output buffering issues
ob_start();

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

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

// Backup configuration
define('BACKUP_HOUR', 12); // Run at 12:00 noon
define('BACKUP_INTERVAL_HOURS', 12); // Run backup every 12 hours

try {
    // Check if we should run backup
    $current_hour = (int)date('H');
    $current_time = time();
    
    // Get last backup time from database
    $last_backup_query = "SELECT created_at FROM backup_logs ORDER BY created_at DESC LIMIT 1";
    $result = $conn->query($last_backup_query);
    $last_backup = null;
    
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $last_backup = strtotime($row['created_at']);
    }
    
    // Determine if backup should run
    $should_backup = false;
    
    if ($last_backup === null) {
        // First backup ever
        $should_backup = true;
    } else {
        // Check if enough time has passed since last backup
        $hours_since_backup = ($current_time - $last_backup) / 3600;
        if ($hours_since_backup >= BACKUP_INTERVAL_HOURS) {
            $should_backup = true;
        }
    }
    
    if (!$should_backup) {
        ob_end_clean();
        echo json_encode([
            'status' => 'skipped',
            'message' => 'Backup not needed yet',
            'next_backup_in_hours' => ceil((BACKUP_INTERVAL_HOURS * 3600 - ($current_time - $last_backup)) / 3600)
        ]);
        exit;
    }
    
    // Execute backup
    $backup_dir = __DIR__ . '/../backups';
    if (!is_dir($backup_dir)) {
        mkdir($backup_dir, 0755, true);
    }
    
    $timestamp = date('Y-m-d_H-i-s');
    $backup_file = $backup_dir . '/backup_' . $timestamp . '.sql';
    
    // Build mysqldump command
    $db_host = DB_SERVER;
    $db_user = DB_USER;
    $db_pass = DB_PASSWORD;
    $db_name = DB_NAME;
    
    // Windows vs Unix command formatting
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        // Windows
        $command = sprintf(
            'mysqldump --host=%s --user=%s --password=%s %s > %s 2>&1',
            escapeshellarg($db_host),
            escapeshellarg($db_user),
            escapeshellarg($db_pass),
            escapeshellarg($db_name),
            escapeshellarg($backup_file)
        );
    } else {
        // Unix/Linux/Mac
        $command = sprintf(
            'mysqldump --host=%s --user=%s --password=%s %s > %s 2>&1',
            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');
    }
    
    // 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
    $log_query = "INSERT INTO backup_logs (backup_file, backup_size, backup_type, created_at) 
                  VALUES (?, ?, 'scheduled', NOW())";
    $stmt = $conn->prepare($log_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');
    if ($backups) {
        foreach ($backups as $file) {
            $file_mtime = filemtime($file);
            if ($file_mtime && ($current_time - $file_mtime) > (30 * 24 * 3600)) {
                unlink($file);
            }
        }
    }
    
    ob_end_clean();
    
    // Log success
    echo json_encode([
        'status' => 'success',
        'message' => 'Backup completed successfully',
        'file' => basename($backup_file),
        'size' => round($file_size / 1024 / 1024, 2) . ' MB',
        'timestamp' => $timestamp
    ]);
    
} catch (Exception $e) {
    ob_end_clean();
    
    http_response_code(500);
    echo json_encode([
        'status' => 'error',
        'error' => 'Backup failed: ' . $e->getMessage()
    ]);
}

// Write to log file for debugging
if (!defined('BACKUP_LOG_FILE')) {
    define('BACKUP_LOG_FILE', __DIR__ . '/../backups/backup.log');
}

file_put_contents(
    BACKUP_LOG_FILE,
    date('Y-m-d H:i:s') . ' - ' . (json_decode(ob_get_contents(), true)['status'] ?? 'unknown') . "\n",
    FILE_APPEND
);

?>
