<?php
// api/backup_db.php
// Script to be called via Cron or manually by Admin

// If run from CLI, we need to manually include config. 
// If run via web, headers checks apply.
if (php_sapi_name() !== 'cli' && session_status() === PHP_SESSION_NONE) {
    session_start();
}

$root = dirname(__DIR__);
require_once $root . '/config/database.php';
require_once $root . '/includes/functions.php';

// Security: If web access, require admin. If CLI, allow.
if (php_sapi_name() !== 'cli') {
    if (!hasRole('admin')) {
        die("Unauthorized Access");
    }
}

// 1. Generate SQL Dump
$dumpFile = $root . '/db/backup_' . date('Y-m-d_H-i-s') . '.sql.gz';
if (!is_dir($root . '/db')) mkdir($root . '/db');

// We use mysqldump if available, or a PHP-based dumper
// Since we are on XAMPP windows, mysqldump is likely in C:\xampp4\mysql\bin\mysqldump.exe
// But path might vary. Let's try to assume it's in path or use a PHP implementation.
// For reliability in this "agent" context without knowing path, a PHP dumper is safer.

function dumpDatabase($pdo, $outFile) {
    $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
    $fp = gzopen($outFile, 'w9');
    
    // Header
    $header = "-- WCS Admin Database Backup\n-- Date: " . date('Y-m-d H:i:s') . "\n\n";
    gzwrite($fp, $header);
    
    gzwrite($fp, "SET FOREIGN_KEY_CHECKS=0;\n\n");

    foreach ($tables as $table) {
        // Structure
        $row = $pdo->query("SHOW CREATE TABLE `$table`")->fetch(PDO::FETCH_NUM);
        gzwrite($fp, "-- Table structure for `$table`\n");
        gzwrite($fp, "DROP TABLE IF EXISTS `$table`;\n");
        gzwrite($fp, $row[1] . ";\n\n");
        
        // Data
        $rows = $pdo->query("SELECT * FROM `$table`");
        while ($r = $rows->fetch(PDO::FETCH_NUM)) {
            $vals = array_map(function($v) use ($pdo) {
                if ($v === null) return "NULL";
                return $pdo->quote($v);
            }, $r);
            gzwrite($fp, "INSERT INTO `$table` VALUES (" . implode(',', $vals) . ");\n");
        }
        gzwrite($fp, "\n");
    }
    
    gzwrite($fp, "SET FOREIGN_KEY_CHECKS=1;\n");
    gzclose($fp);
}

try {
    dumpDatabase($pdo, $dumpFile);
    $msg = "Backup generated successfully at $dumpFile";
} catch (Exception $e) {
    die("Backup failed: " . $e->getMessage());
}

// 2. Send Email
require_once $root . '/includes/email_functions.php';

// Get recipients from settings
// We need to add a setting for this. For now, use a default or check settings table.
$stmt = $pdo->prepare("SELECT value FROM settings_options WHERE category='admin_backup_email'");
$stmt->execute();
$recipients_str = $stmt->fetchColumn();

if (!$recipients_str) {
    // Fallback if not set? Or maybe we just email the one configured in config?
    // Let's assume we want to send to the 'SMTP_FROM_EMAIL' if no specific list is set, or just log warning.
    $recipients_str = defined('SMTP_FROM_EMAIL') ? SMTP_FROM_EMAIL : '';
}

if ($recipients_str) {
    $subject = "Database Backup - " . date('Y-m-d');
    $body = "Attached is the automated database backup for WCS Admin system.";
    
    $result = send_mail($recipients_str, $subject, $body, true, [$dumpFile]);
    
    if ($result === true) {
        echo "Backup sent successfully to $recipients_str";
    } else {
        echo "Backup created but email failed: $result";
    }
} else {
    echo "Backup created but no recipients configured.";
}

?>
