<?php
include 'db.php';
include 'layout.php';

// Include WAMP detector
require_once 'functions/wamp_detector.php';

// Load backup configuration
$configFile = 'backup_config.json';
$config = [];

if (file_exists($configFile)) {
    $config = json_decode(file_get_contents($configFile), true) ?? [];
}

// Get WAMP detection results
$wampStatus = WampDetector::getWampStatus();
$recommendedBackupPath = WampDetector::getRecommendedBackupPath();

// Default configuration with dynamic backup path
$defaultConfig = [
    'frequency' => [
        'enabled' => true,
        'type' => 'daily',
        'custom_schedule' => '0 2 * * *',
        'time' => '02:00'
    ],
    'retention' => [
        'daily_keep' => 30,
        'weekly_keep' => 12,
        'monthly_keep' => 12,
        'auto_cleanup' => true
    ],
    'storage' => [
        'local_enabled' => true,
        'local_path' => $recommendedBackupPath,
        'local_secondary_path' => '',
        'cloud_enabled' => false,
        'cloud_provider' => 'none',
        'cloud_settings' => []
    ],
    'backup_options' => [
        'compression' => true,
        'verification' => true,
        'include_structure' => true,
        'include_data' => true,
        'split_large_files' => false,
        'max_file_size_mb' => 100
    ],
    'notifications' => [
        'email_enabled' => false,
        'email_on_success' => false,
        'email_on_failure' => true,
        'admin_email' => '',
        'smtp_settings' => [
            'host' => '',
            'port' => 587,
            'username' => '',
            'password' => '',
            'encryption' => 'tls'
        ]
    ],
    'monitoring' => [
        'log_level' => 'info',
        'max_log_size_mb' => 10,
        'dashboard_enabled' => true
    ]
];

$config = array_replace_recursive($defaultConfig, $config);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_config'])) {
    $newConfig = [
        'frequency' => [
            'enabled' => isset($_POST['frequency_enabled']),
            'type' => $_POST['backup_frequency'] ?? 'daily',
            'custom_schedule' => $_POST['custom_schedule'] ?? '0 2 * * *',
            'time' => $_POST['backup_time'] ?? '02:00'
        ],
        'retention' => [
            'daily_keep' => (int)($_POST['daily_keep'] ?? 30),
            'weekly_keep' => (int)($_POST['weekly_keep'] ?? 12),
            'monthly_keep' => (int)($_POST['monthly_keep'] ?? 12),
            'auto_cleanup' => isset($_POST['auto_cleanup'])
        ],
        'storage' => [
            'local_enabled' => isset($_POST['local_enabled']),
            'local_path' => $_POST['local_path'] ?? 'D:/wamp/backups/itrpos/',
            'local_secondary_path' => $_POST['secondary_path'] ?? '',
            'cloud_enabled' => isset($_POST['cloud_enabled']),
            'cloud_provider' => $_POST['cloud_provider'] ?? 'none',
            'cloud_settings' => []
        ],
        'backup_options' => [
            'compression' => isset($_POST['compression']),
            'verification' => isset($_POST['verification']),
            'include_structure' => isset($_POST['include_structure']),
            'include_data' => isset($_POST['include_data']),
            'split_large_files' => isset($_POST['split_large_files']),
            'max_file_size_mb' => (int)($_POST['max_file_size_mb'] ?? 100)
        ],
        'notifications' => [
            'email_enabled' => isset($_POST['email_enabled']),
            'email_on_success' => isset($_POST['email_on_success']),
            'email_on_failure' => isset($_POST['email_on_failure']),
            'admin_email' => $_POST['admin_email'] ?? '',
            'smtp_settings' => [
                'host' => $_POST['smtp_host'] ?? '',
                'port' => (int)($_POST['smtp_port'] ?? 587),
                'username' => $_POST['smtp_username'] ?? '',
                'password' => $_POST['smtp_password'] ?? '',
                'encryption' => $_POST['smtp_encryption'] ?? 'tls'
            ]
        ],
        'monitoring' => [
            'log_level' => $_POST['log_level'] ?? 'info',
            'max_log_size_mb' => (int)($_POST['max_log_size_mb'] ?? 10),
            'dashboard_enabled' => isset($_POST['dashboard_enabled'])
        ]
    ];
    
    if (file_put_contents($configFile, json_encode($newConfig, JSON_PRETTY_PRINT))) {
        $config = $newConfig;
        
        // Auto-setup Windows Task Scheduler
        require_once 'handlers/windows_task_manager.php';
        $taskManager = new WindowsTaskManager();
        
        if ($newConfig['frequency']['enabled']) {
            // Create Windows Task Scheduler entry
            $taskResult = $taskManager->createBackupTask();
            if ($taskResult['success']) {
                $success_message = "Backup configuration saved successfully! Windows Task Scheduler has been automatically configured.";
            } else {
                $error_message = "Backup configuration saved, but Windows Task Scheduler setup failed. ";
                if (isset($taskResult['solution'])) {
                    $error_message .= $taskResult['solution'];
                } else {
                    $error_message .= "Please run as administrator or use the manual setup script.";
                }
                $error_message .= " <a href='setup_windows_task_manual.php' target='_blank'>Click here for manual setup instructions</a>";
            }
        } else {
            // Remove Windows Task Scheduler entry
            $taskResult = $taskManager->removeBackupTask();
            $success_message = "Backup configuration saved successfully! Automated backups have been disabled.";
        }
    } else {
        $error_message = "Failed to save configuration. Please check file permissions.";
    }
}

// Get backup status
function getBackupStatus() {
    // Use the recommended backup path from WAMP detection
    $backupDir = WampDetector::getRecommendedBackupPath();
    $status = [
        'last_backup' => 'Never',
        'next_backup' => 'Not scheduled',
        'total_backups' => 0,
        'total_size' => 0,
        'service_status' => 'Unknown'
    ];
    
    if (is_dir($backupDir)) {
        $files = glob($backupDir . 'itrpos_backup_*.sql*');
        $status['total_backups'] = count($files);
        
        if ($files) {
            // Get most recent backup
            $latestFile = '';
            $latestTime = 0;
            foreach ($files as $file) {
                $time = filemtime($file);
                if ($time > $latestTime) {
                    $latestTime = $time;
                    $latestFile = $file;
                }
            }
            
            if ($latestFile) {
                $status['last_backup'] = date('Y-m-d H:i:s', $latestTime);
            }
            
            // Calculate total size
            foreach ($files as $file) {
                $status['total_size'] += filesize($file);
            }
        }
    }
    
    return $status;
}

$backupStatus = getBackupStatus();
?>

<div class="page-wrapper">
    <div class="content">
        <div class="page-header">
            <div class="add-item d-flex">
                <div class="page-title">
                    <h4>💾 Database Backup Management</h4>
                    <h6>Configure automated backup settings and monitor backup status</h6>
                </div>
            </div>
            <ul class="table-top-head">
                                 <li>
                     <a href="#status-overview" class="btn btn-secondary">
                         <i data-feather="bar-chart-2" class="feather-16"></i> Status Overview
                     </a>
                 </li>
                <li>
                    <a href="backup_restore.php" class="btn btn-info">
                        <i data-feather="download" class="feather-16"></i> Restore
                    </a>
                </li>
                <li>
                    <a href="#" id="run-backup-now" class="btn btn-primary">
                        <i data-feather="save" class="feather-16"></i> Run Backup Now
                    </a>
                </li>
            </ul>
        </div>

        <?php if (isset($success_message)): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i data-feather="check-circle" class="feather-16"></i> <?php echo $success_message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <?php if (isset($error_message)): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i data-feather="alert-circle" class="feather-16"></i> <?php echo $error_message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

                 <!-- Backup Status Overview -->
         <div class="row mb-4" id="status-overview">
            <div class="col-lg-3 col-sm-6 col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="dash-counts">
                            <h4><?php echo $backupStatus['total_backups']; ?></h4>
                            <h5>Total Backups</h5>
                        </div>
                        <div class="dash-imgs">
                            <i data-feather="archive" class="feather-24"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-sm-6 col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="dash-counts">
                            <h4><?php echo $backupStatus['last_backup']; ?></h4>
                            <h5>Last Backup</h5>
                        </div>
                        <div class="dash-imgs">
                            <i data-feather="clock" class="feather-24"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-sm-6 col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="dash-counts">
                            <h4><?php echo number_format($backupStatus['total_size'] / (1024*1024), 1) . ' MB'; ?></h4>
                            <h5>Storage Used</h5>
                        </div>
                        <div class="dash-imgs">
                            <i data-feather="hard-drive" class="feather-24"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-sm-6 col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="dash-counts">
                            <h4 id="scheduler-status"><?php echo $config['frequency']['enabled'] ? 'Active' : 'Disabled'; ?></h4>
                            <h5>Backup Service</h5>
                        </div>
                        <div class="dash-imgs">
                            <i data-feather="<?php echo $config['frequency']['enabled'] ? 'check-circle' : 'x-circle'; ?>" 
                               class="feather-24 <?php echo $config['frequency']['enabled'] ? 'text-success' : 'text-danger'; ?>" id="scheduler-icon"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Scheduler Status -->
        <div class="row mb-4">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">⏰ Automated Backup Scheduler Status</h5>
                        <button type="button" id="refresh-scheduler-status" class="btn btn-sm btn-outline-primary">
                            <i data-feather="refresh-cw" class="feather-16"></i> Refresh Status
                        </button>
                    </div>
                    <div class="card-body">
                        <div id="scheduler-status-content">
                            <div class="row">
                                <div class="col-lg-3 col-sm-6 col-12">
                                    <div class="status-item">
                                        <label>Windows Task Scheduler:</label>
                                        <span class="badge bg-warning" id="windows-task-status">
                                            <?php 
                                            if (file_exists('backup_last_run.json')) {
                                                echo 'Configured';
                                            } else {
                                                echo 'Not Configured';
                                            }
                                            ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="col-lg-3 col-sm-6 col-12">
                                    <div class="status-item">
                                        <label>Next Backup:</label>
                                        <span class="badge bg-info" id="next-backup-time">
                                            <?php 
                                            if (file_exists('backup_last_run.json')) {
                                                $lastRun = json_decode(file_get_contents('backup_last_run.json'), true);
                                                $frequency = $config['frequency']['type'] ?? '6hourly';
                                                $lastTime = $lastRun[$frequency] ?? 0;
                                                if ($lastTime > 0) {
                                                    $interval = 6 * 60 * 60; // 6 hours default
                                                    switch ($frequency) {
                                                        case '15min': $interval = 15 * 60; break;
                                                        case '30min': $interval = 30 * 60; break;
                                                        case 'hourly': $interval = 60 * 60; break;
                                                        case '6hourly': $interval = 6 * 60 * 60; break;
                                                        case '12hourly': $interval = 12 * 60 * 60; break;
                                                        case 'daily': $interval = 24 * 60 * 60; break;
                                                        case 'weekly': $interval = 7 * 24 * 60 * 60; break;
                                                    }
                                                    $nextTime = $lastTime + $interval;
                                                    echo date('Y-m-d H:i:s', $nextTime);
                                                } else {
                                                    echo 'Unknown';
                                                }
                                            } else {
                                                echo 'Not Configured';
                                            }
                                            ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="col-lg-3 col-sm-6 col-12">
                                    <div class="status-item">
                                        <label>Time Until Next:</label>
                                        <span class="badge bg-secondary" id="time-until-next">Loading...</span>
                                    </div>
                                </div>
                                <div class="col-lg-3 col-sm-6 col-12">
                                    <div class="status-item">
                                        <label>Frequency:</label>
                                        <span class="badge bg-primary" id="backup-frequency"><?php echo ucfirst($config['frequency']['type'] ?? 'unknown'); ?></span>
                                    </div>
                                </div>
                            </div>
                            <div class="alert alert-info mt-3" id="scheduler-info">
                                <i data-feather="info" class="feather-16"></i>
                                <strong>Setup Required:</strong> To enable automated backups, you need to set up a cron job or Windows Task Scheduler. 
                                <a href="BACKUP_CRON_SETUP.md" target="_blank" class="alert-link">View setup instructions</a>
                                <br><small>Current configuration: <?php echo ucfirst($config['frequency']['type'] ?? 'unknown'); ?> backups <?php echo $config['frequency']['enabled'] ? 'enabled' : 'disabled'; ?></small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- WAMP Detection Status -->
        <div class="row mb-4">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">🔍 WAMP Installation Status</h5>
                        <button type="button" id="re-detect-wamp" class="btn btn-sm btn-outline-primary">
                            <i data-feather="refresh-cw" class="feather-16"></i> Re-detect WAMP
                        </button>
                    </div>
                    <div class="card-body">
                        <div id="wamp-status-content">
                            <div class="row">
                                <div class="col-lg-3 col-sm-6 col-12">
                                    <div class="status-item">
                                        <label>WAMP Detected:</label>
                                        <span class="badge <?php echo $wampStatus['detected'] ? 'bg-success' : 'bg-danger'; ?>">
                                            <?php echo $wampStatus['detected'] ? 'Yes' : 'No'; ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="col-lg-3 col-sm-6 col-12">
                                    <div class="status-item">
                                        <label>WAMP Type:</label>
                                        <span class="badge bg-info"><?php echo ucfirst($wampStatus['wamp_type'] ?? 'Unknown'); ?></span>
                                    </div>
                                </div>
                                <div class="col-lg-3 col-sm-6 col-12">
                                    <div class="status-item">
                                        <label>MySQL Version:</label>
                                        <span class="badge bg-secondary"><?php echo $wampStatus['mysql_version'] ?? 'Unknown'; ?></span>
                                    </div>
                                </div>
                                <div class="col-lg-3 col-sm-6 col-12">
                                    <div class="status-item">
                                        <label>mysqldump Available:</label>
                                        <span class="badge <?php echo $wampStatus['mysqldump_available'] ? 'bg-success' : 'bg-danger'; ?>">
                                            <?php echo $wampStatus['mysqldump_available'] ? 'Yes' : 'No'; ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <?php if ($wampStatus['detected']): ?>
                            <div class="row mt-3">
                                <div class="col-lg-6">
                                    <div class="status-item">
                                        <label>WAMP Root:</label>
                                        <code><?php echo htmlspecialchars($wampStatus['wamp_root']); ?></code>
                                    </div>
                                </div>
                                <div class="col-lg-6">
                                    <div class="status-item">
                                        <label>Recommended Backup Path:</label>
                                        <code><?php echo htmlspecialchars($recommendedBackupPath); ?></code>
                                    </div>
                                </div>
                            </div>
                            <?php else: ?>
                            <div class="alert alert-warning mt-3">
                                <i data-feather="alert-triangle" class="feather-16"></i>
                                <strong>WAMP not detected!</strong> Please ensure WAMP is properly installed and try re-detecting.
                                <br><small>Supported locations: C:/wamp/, D:/wamp/, E:/wamp/, etc. (including wamp64 variants)</small>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Configuration Form -->
        <form method="POST" action="">
            <div class="row">
                <!-- Backup Frequency Configuration -->
                <div class="col-lg-6 col-12">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="card-title">🕒 Backup Frequency</h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-lg-12 col-sm-12">
                                    <div class="form-group">
                                        <label class="form-label">
                                            <input type="checkbox" name="frequency_enabled" <?php echo $config['frequency']['enabled'] ? 'checked' : ''; ?>>
                                            Enable Automated Backups
                                        </label>
                                    </div>
                                </div>
                                <div class="col-lg-8 col-sm-12">
                                    <div class="form-group">
                                        <label>Backup Frequency</label>
                                        <select class="form-control" name="backup_frequency" id="backup_frequency">
                                            <option value="15min" <?php echo $config['frequency']['type'] == '15min' ? 'selected' : ''; ?>>Every 15 minutes</option>
                                            <option value="30min" <?php echo $config['frequency']['type'] == '30min' ? 'selected' : ''; ?>>Every 30 minutes</option>
                                            <option value="hourly" <?php echo $config['frequency']['type'] == 'hourly' ? 'selected' : ''; ?>>Every hour</option>
                                            <option value="6hourly" <?php echo $config['frequency']['type'] == '6hourly' ? 'selected' : ''; ?>>Every 6 hours</option>
                                            <option value="12hourly" <?php echo $config['frequency']['type'] == '12hourly' ? 'selected' : ''; ?>>Every 12 hours</option>
                                            <option value="daily" <?php echo $config['frequency']['type'] == 'daily' ? 'selected' : ''; ?>>Daily</option>
                                            <option value="weekly" <?php echo $config['frequency']['type'] == 'weekly' ? 'selected' : ''; ?>>Weekly</option>
                                            <option value="custom" <?php echo $config['frequency']['type'] == 'custom' ? 'selected' : ''; ?>>Custom Schedule</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-lg-4 col-sm-12">
                                    <div class="form-group" id="backup_time_group">
                                        <label>Time</label>
                                        <input type="time" class="form-control" name="backup_time" value="<?php echo $config['frequency']['time']; ?>">
                                    </div>
                                </div>
                                <div class="col-lg-12 col-sm-12" id="custom_schedule_group" style="display: none;">
                                    <div class="form-group">
                                        <label>Custom Schedule (Cron Format)</label>
                                        <input type="text" class="form-control" name="custom_schedule" 
                                               value="<?php echo htmlspecialchars($config['frequency']['custom_schedule']); ?>"
                                               placeholder="0 2 * * * (2 AM daily)">
                                        <small class="text-muted">Format: minute hour day month weekday</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Retention Policy -->
                <div class="col-lg-6 col-12">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="card-title">📅 Retention Policy</h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-lg-4 col-sm-12">
                                    <div class="form-group">
                                        <label>Daily Backups</label>
                                        <input type="number" class="form-control" name="daily_keep" 
                                               value="<?php echo $config['retention']['daily_keep']; ?>" 
                                               min="1" max="365">
                                        <small class="text-muted">Keep for days</small>
                                    </div>
                                </div>
                                <div class="col-lg-4 col-sm-12">
                                    <div class="form-group">
                                        <label>Weekly Backups</label>
                                        <input type="number" class="form-control" name="weekly_keep" 
                                               value="<?php echo $config['retention']['weekly_keep']; ?>" 
                                               min="1" max="52">
                                        <small class="text-muted">Keep for weeks</small>
                                    </div>
                                </div>
                                <div class="col-lg-4 col-sm-12">
                                    <div class="form-group">
                                        <label>Monthly Backups</label>
                                        <input type="number" class="form-control" name="monthly_keep" 
                                               value="<?php echo $config['retention']['monthly_keep']; ?>" 
                                               min="1" max="60">
                                        <small class="text-muted">Keep for months</small>
                                    </div>
                                </div>
                                <div class="col-lg-12 col-sm-12">
                                    <div class="form-group">
                                        <label class="form-label">
                                            <input type="checkbox" name="auto_cleanup" <?php echo $config['retention']['auto_cleanup'] ? 'checked' : ''; ?>>
                                            Automatically delete old backups based on retention policy
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Storage Configuration -->
                <div class="col-lg-12 col-12">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="card-title">💾 Storage Configuration</h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-lg-6 col-sm-12">
                                    <h6>Local Storage</h6>
                                    <div class="form-group">
                                        <label class="form-label">
                                            <input type="checkbox" name="local_enabled" <?php echo $config['storage']['local_enabled'] ? 'checked' : ''; ?>>
                                            Enable Local Storage
                                        </label>
                                    </div>
                                    <div class="form-group">
                                        <label>Primary Backup Directory</label>
                                        <input type="text" class="form-control" name="local_path" 
                                               value="<?php echo htmlspecialchars($config['storage']['local_path']); ?>">
                                    </div>
                                    <div class="form-group">
                                        <label>Secondary Backup Directory (Optional)</label>
                                        <input type="text" class="form-control" name="secondary_path" 
                                               value="<?php echo htmlspecialchars($config['storage']['local_secondary_path']); ?>">
                                        <small class="text-muted">For redundancy - backups will be copied here too</small>
                                    </div>
                                </div>
                                <div class="col-lg-6 col-sm-12">
                                    <h6>Cloud Storage (Optional)</h6>
                                    <div class="form-group">
                                        <label class="form-label">
                                            <input type="checkbox" name="cloud_enabled" <?php echo $config['storage']['cloud_enabled'] ? 'checked' : ''; ?>>
                                            Enable Cloud Storage
                                        </label>
                                    </div>
                                    <div class="form-group">
                                        <label>Cloud Provider</label>
                                        <select class="form-control" name="cloud_provider">
                                            <option value="none" <?php echo $config['storage']['cloud_provider'] == 'none' ? 'selected' : ''; ?>>None</option>
                                            <option value="gdrive" <?php echo $config['storage']['cloud_provider'] == 'gdrive' ? 'selected' : ''; ?>>Google Drive</option>
                                            <option value="dropbox" <?php echo $config['storage']['cloud_provider'] == 'dropbox' ? 'selected' : ''; ?>>Dropbox</option>
                                            <option value="ftp" <?php echo $config['storage']['cloud_provider'] == 'ftp' ? 'selected' : ''; ?>>FTP Server</option>
                                            <option value="aws_s3" <?php echo $config['storage']['cloud_provider'] == 'aws_s3' ? 'selected' : ''; ?>>AWS S3</option>
                                        </select>
                                    </div>
                                    <div class="alert alert-info">
                                        <small><i data-feather="info" class="feather-16"></i> Cloud storage configuration will be available after selecting a provider and saving settings.</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Backup Options -->
                <div class="col-lg-6 col-12">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="card-title">⚙️ Backup Options</h5>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label class="form-label">
                                    <input type="checkbox" name="compression" <?php echo $config['backup_options']['compression'] ? 'checked' : ''; ?>>
                                    Compress backups (saves storage space)
                                </label>
                            </div>
                            <div class="form-group">
                                <label class="form-label">
                                    <input type="checkbox" name="verification" <?php echo $config['backup_options']['verification'] ? 'checked' : ''; ?>>
                                    Verify backup integrity after creation
                                </label>
                            </div>
                            <div class="form-group">
                                <label class="form-label">
                                    <input type="checkbox" name="include_structure" <?php echo $config['backup_options']['include_structure'] ? 'checked' : ''; ?>>
                                    Include table structure
                                </label>
                            </div>
                            <div class="form-group">
                                <label class="form-label">
                                    <input type="checkbox" name="include_data" <?php echo $config['backup_options']['include_data'] ? 'checked' : ''; ?>>
                                    Include table data
                                </label>
                            </div>
                            <div class="form-group">
                                <label class="form-label">
                                    <input type="checkbox" name="split_large_files" <?php echo $config['backup_options']['split_large_files'] ? 'checked' : ''; ?>>
                                    Split large backup files
                                </label>
                            </div>
                            <div class="form-group">
                                <label>Maximum file size (MB)</label>
                                <input type="number" class="form-control" name="max_file_size_mb" 
                                       value="<?php echo $config['backup_options']['max_file_size_mb']; ?>" 
                                       min="1" max="1000">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Email Notifications -->
                <div class="col-lg-6 col-12">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="card-title">📧 Email Notifications</h5>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label class="form-label">
                                    <input type="checkbox" name="email_enabled" id="email_enabled" <?php echo $config['notifications']['email_enabled'] ? 'checked' : ''; ?>>
                                    Enable Email Notifications
                                </label>
                            </div>
                            <div id="email_settings" style="<?php echo $config['notifications']['email_enabled'] ? '' : 'display: none;'; ?>">
                                <div class="form-group">
                                    <label>Admin Email</label>
                                    <input type="email" class="form-control" name="admin_email" 
                                           value="<?php echo htmlspecialchars($config['notifications']['admin_email']); ?>">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">
                                        <input type="checkbox" name="email_on_success" <?php echo $config['notifications']['email_on_success'] ? 'checked' : ''; ?>>
                                        Email on successful backup
                                    </label>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">
                                        <input type="checkbox" name="email_on_failure" <?php echo $config['notifications']['email_on_failure'] ? 'checked' : ''; ?>>
                                        Email on backup failure
                                    </label>
                                </div>
                                <div class="row">
                                    <div class="col-lg-6">
                                        <div class="form-group">
                                            <label>SMTP Host</label>
                                            <input type="text" class="form-control" name="smtp_host" 
                                                   value="<?php echo htmlspecialchars($config['notifications']['smtp_settings']['host']); ?>">
                                        </div>
                                    </div>
                                    <div class="col-lg-6">
                                        <div class="form-group">
                                            <label>SMTP Port</label>
                                            <input type="number" class="form-control" name="smtp_port" 
                                                   value="<?php echo $config['notifications']['smtp_settings']['port']; ?>">
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-lg-6">
                                        <div class="form-group">
                                            <label>SMTP Username</label>
                                            <input type="text" class="form-control" name="smtp_username" 
                                                   value="<?php echo htmlspecialchars($config['notifications']['smtp_settings']['username']); ?>">
                                        </div>
                                    </div>
                                    <div class="col-lg-6">
                                        <div class="form-group">
                                            <label>SMTP Password</label>
                                            <input type="password" class="form-control" name="smtp_password" 
                                                   value="<?php echo htmlspecialchars($config['notifications']['smtp_settings']['password']); ?>">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Save Button -->
            <div class="row">
                <div class="col-lg-12">
                    <div class="btn-path text-center">
                        <button type="submit" name="save_config" class="btn btn-primary me-3">
                            <i data-feather="save" class="feather-16"></i> Save Configuration
                        </button>
                                                 <a href="#status-overview" class="btn btn-secondary">
                             <i data-feather="x" class="feather-16"></i> Back to Top
                         </a>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- SweetAlert2 for better user notifications -->
<script src="assets/plugins/sweetalert/sweetalert2.all.min.js"></script>

<style>
.status-item {
    margin-bottom: 15px;
}
.status-item label {
    display: block;
    font-weight: 600;
    color: #555;
    margin-bottom: 5px;
    font-size: 0.9rem;
}
.status-item .badge {
    font-size: 0.85rem;
    padding: 5px 10px;
}
.status-item code {
    background: #f8f9fa;
    padding: 3px 6px;
    border-radius: 3px;
    font-size: 0.85rem;
    color: #e83e8c;
}
.spin {
    animation: spin 1s linear infinite;
}
@keyframes spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Handle backup frequency change
    const frequencySelect = document.getElementById('backup_frequency');
    const timeGroup = document.getElementById('backup_time_group');
    const customGroup = document.getElementById('custom_schedule_group');
    
    function toggleScheduleInputs() {
        const value = frequencySelect.value;
        if (value === 'custom') {
            timeGroup.style.display = 'none';
            customGroup.style.display = 'block';
        } else {
            timeGroup.style.display = value === 'daily' || value === 'weekly' ? 'block' : 'none';
            customGroup.style.display = 'none';
        }
    }
    
    frequencySelect.addEventListener('change', toggleScheduleInputs);
    toggleScheduleInputs(); // Initial call
    
    // Handle email settings toggle
    const emailEnabled = document.getElementById('email_enabled');
    const emailSettings = document.getElementById('email_settings');
    
    emailEnabled.addEventListener('change', function() {
        emailSettings.style.display = this.checked ? 'block' : 'none';
    });
    
    // Handle WAMP re-detection
    document.getElementById('re-detect-wamp').addEventListener('click', function(e) {
        e.preventDefault();
        
        const button = this;
        const originalText = button.innerHTML;
        
        // Show loading state
        button.innerHTML = '<i data-feather="loader" class="feather-16 spin"></i> Detecting...';
        button.disabled = true;
        
        // Make AJAX request
        fetch('ajax/detect_wamp.php?action=detect', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Update the status content
                updateWampStatus(data);
                
                // Show success message
                Swal.fire({
                    title: 'WAMP Detection Complete',
                    text: data.wamp_status.detected ? 
                        'WAMP installation detected successfully!' : 
                        'WAMP detection completed. Please check the status below.',
                    icon: data.wamp_status.detected ? 'success' : 'warning',
                    confirmButtonText: 'OK'
                });
            } else {
                Swal.fire({
                    title: 'Detection Failed',
                    text: data.message || 'Failed to detect WAMP installation.',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
            }
        })
        .catch(error => {
            console.error('Error:', error);
            Swal.fire({
                title: 'Network Error',
                text: 'Failed to communicate with server. Please try again.',
                icon: 'error',
                confirmButtonText: 'OK'
            });
        })
        .finally(() => {
            // Restore button state
            button.innerHTML = originalText;
            button.disabled = false;
        });
    });
    
    // Function to update WAMP status display
    function updateWampStatus(data) {
        const statusContent = document.getElementById('wamp-status-content');
        
        let html = `
            <div class="row">
                <div class="col-lg-3 col-sm-6 col-12">
                    <div class="status-item">
                        <label>WAMP Detected:</label>
                        <span class="badge ${data.wamp_status.detected ? 'bg-success' : 'bg-danger'}">
                            ${data.wamp_status.detected ? 'Yes' : 'No'}
                        </span>
                    </div>
                </div>
                <div class="col-lg-3 col-sm-6 col-12">
                    <div class="status-item">
                        <label>WAMP Type:</label>
                        <span class="badge bg-info">${data.wamp_status.wamp_type ? data.wamp_status.wamp_type.charAt(0).toUpperCase() + data.wamp_status.wamp_type.slice(1) : 'Unknown'}</span>
                    </div>
                </div>
                <div class="col-lg-3 col-sm-6 col-12">
                    <div class="status-item">
                        <label>MySQL Version:</label>
                        <span class="badge bg-secondary">${data.wamp_status.mysql_version || 'Unknown'}</span>
                    </div>
                </div>
                <div class="col-lg-3 col-sm-6 col-12">
                    <div class="status-item">
                        <label>mysqldump Available:</label>
                        <span class="badge ${data.wamp_status.mysqldump_available ? 'bg-success' : 'bg-danger'}">
                            ${data.wamp_status.mysqldump_available ? 'Yes' : 'No'}
                        </span>
                    </div>
                </div>
            </div>`;
        
        if (data.wamp_status.detected) {
            html += `
                <div class="row mt-3">
                    <div class="col-lg-6">
                        <div class="status-item">
                            <label>WAMP Root:</label>
                            <code>${data.wamp_status.wamp_root}</code>
                        </div>
                    </div>
                    <div class="col-lg-6">
                        <div class="status-item">
                            <label>Recommended Backup Path:</label>
                            <code>${data.recommended_backup_path}</code>
                        </div>
                    </div>
                </div>`;
        } else {
            html += `
                <div class="alert alert-warning mt-3">
                    <i data-feather="alert-triangle" class="feather-16"></i>
                    <strong>WAMP not detected!</strong> Please ensure WAMP is properly installed and try re-detecting.
                    <br><small>Supported locations: C:/wamp/, D:/wamp/, E:/wamp/, etc. (including wamp64 variants)</small>
                </div>`;
        }
        
        statusContent.innerHTML = html;
        
        // Re-initialize feather icons
        if (typeof feather !== 'undefined') {
            feather.replace();
        }
    }
    
    // Load scheduler status on page load
    loadSchedulerStatus();
    
    // Handle refresh scheduler status
    document.getElementById('refresh-scheduler-status').addEventListener('click', function(e) {
        e.preventDefault();
        loadSchedulerStatus();
    });
    
    // Function to load scheduler status
    function loadSchedulerStatus() {
        const refreshBtn = document.getElementById('refresh-scheduler-status');
        const originalText = refreshBtn.innerHTML;
        
        // Show loading state
        refreshBtn.innerHTML = '<i data-feather="loader" class="feather-16 spin"></i> Loading...';
        refreshBtn.disabled = true;
        
        fetch('ajax/backup_status_simple.php', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                updateSchedulerStatus(data);
            } else {
                console.error('Failed to load scheduler status:', data.error);
                updateSchedulerStatusError();
            }
        })
        .catch(error => {
            console.error('Error loading scheduler status:', error);
            updateSchedulerStatusError();
        })
        .finally(() => {
            // Restore button state
            refreshBtn.innerHTML = originalText;
            refreshBtn.disabled = false;
        });
    }
    
    // Function to update scheduler status display
    function updateSchedulerStatus(data) {
        // Update Windows Task Scheduler status
        const windowsTaskStatus = document.getElementById('windows-task-status');
        if (windowsTaskStatus) {
            const taskStatusText = data.windows_task.running ? 'Active' : 'Not Configured';
            const taskStatusClass = data.windows_task.running ? 'bg-success' : 'bg-warning';
            windowsTaskStatus.textContent = taskStatusText;
            windowsTaskStatus.className = `badge ${taskStatusClass}`;
        }
        
        // Update scheduler working status (fallback for old structure)
        const workingStatus = document.getElementById('scheduler-working-status');
        if (workingStatus) {
            const workingStatusText = data.scheduler.working ? 'Active' : 'Not Configured';
            const workingStatusClass = data.scheduler.working ? 'bg-success' : 'bg-warning';
            workingStatus.textContent = workingStatusText;
            workingStatus.className = `badge ${workingStatusClass}`;
        }
        
        // Update next backup time
        const nextBackupTime = document.getElementById('next-backup-time');
        if (nextBackupTime) {
            nextBackupTime.textContent = data.backups.next_backup;
        }
        
        // Update time until next
        const timeUntilNext = document.getElementById('time-until-next');
        if (timeUntilNext) {
            timeUntilNext.textContent = data.backups.time_until_next;
        }
        
        // Update frequency
        const backupFrequency = document.getElementById('backup-frequency');
        if (backupFrequency) {
            backupFrequency.textContent = data.scheduler.frequency;
        }
        
        // Update main scheduler status
        const mainStatus = document.getElementById('scheduler-status');
        const mainIcon = document.getElementById('scheduler-icon');
        
        if (data.scheduler.enabled && data.scheduler.working) {
            mainStatus.textContent = 'Active';
            mainIcon.className = 'feather-24 text-success';
            mainIcon.setAttribute('data-feather', 'check-circle');
        } else if (data.scheduler.enabled && !data.scheduler.working) {
            mainStatus.textContent = 'Configured';
            mainIcon.className = 'feather-24 text-warning';
            mainIcon.setAttribute('data-feather', 'clock');
        } else {
            mainStatus.textContent = 'Disabled';
            mainIcon.className = 'feather-24 text-danger';
            mainIcon.setAttribute('data-feather', 'x-circle');
        }
        
        // Update scheduler info alert
        const schedulerInfo = document.getElementById('scheduler-info');
        if (data.scheduler.enabled && data.windows_task.running) {
            schedulerInfo.className = 'alert alert-success mt-3';
            schedulerInfo.innerHTML = '<i data-feather="check-circle" class="feather-16"></i> <strong>Automated backups are active!</strong> Windows Task Scheduler is running and your backups will be created automatically according to your schedule.';
        } else if (data.scheduler.enabled && !data.windows_task.running) {
            schedulerInfo.className = 'alert alert-warning mt-3';
            schedulerInfo.innerHTML = '<i data-feather="alert-triangle" class="feather-16"></i> <strong>Windows Task Scheduler not configured.</strong> Please save your backup configuration to automatically set up the scheduler.';
        } else {
            schedulerInfo.className = 'alert alert-info mt-3';
            schedulerInfo.innerHTML = '<i data-feather="info" class="feather-16"></i> <strong>Automated backups are disabled.</strong> Enable them in the configuration below and the system will automatically set up Windows Task Scheduler.';
        }
        
        // Re-initialize feather icons
        if (typeof feather !== 'undefined') {
            feather.replace();
        }
    }
    
    // Function to handle scheduler status error
    function updateSchedulerStatusError() {
        // Update Windows Task Scheduler status
        const windowsTaskStatus = document.getElementById('windows-task-status');
        if (windowsTaskStatus) {
            windowsTaskStatus.textContent = 'Error';
            windowsTaskStatus.className = 'badge bg-danger';
        }
        
        // Update scheduler working status (fallback)
        const workingStatus = document.getElementById('scheduler-working-status');
        if (workingStatus) {
            workingStatus.textContent = 'Error';
            workingStatus.className = 'badge bg-danger';
        }
        
        const nextBackupTime = document.getElementById('next-backup-time');
        if (nextBackupTime) {
            nextBackupTime.textContent = 'Unknown';
        }
        
        const timeUntilNext = document.getElementById('time-until-next');
        if (timeUntilNext) {
            timeUntilNext.textContent = 'Unknown';
        }
        
        const backupFrequency = document.getElementById('backup-frequency');
        if (backupFrequency) {
            backupFrequency.textContent = 'Unknown';
        }
    }
    
    // Handle run backup now
    document.getElementById('run-backup-now').addEventListener('click', function(e) {
        e.preventDefault();
        
        // Show confirmation with SweetAlert
        Swal.fire({
            title: 'Run Backup Now?',
            text: 'This will create a manual backup of your database. This may take a few minutes.',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, Run Backup',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                // Show loading
                Swal.fire({
                    title: 'Creating Backup...',
                    text: 'Please wait while we create your database backup.',
                    icon: 'info',
                    allowOutsideClick: false,
                    allowEscapeKey: false,
                    showConfirmButton: false,
                    willOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                // Make AJAX request
                fetch('ajax/run_backup_now.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        Swal.fire({
                            title: data.title,
                            text: data.message,
                            icon: 'success',
                            confirmButtonText: 'OK'
                        }).then(() => {
                            // Reload page to refresh backup list and scheduler status
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            title: data.title,
                            text: data.message,
                            icon: 'error',
                            confirmButtonText: 'OK'
                        });
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    Swal.fire({
                        title: 'Network Error',
                        text: 'Failed to communicate with server. Please try again.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                });
            }
        });
    });
    
    // Refresh scheduler status after form submission
    const configForm = document.querySelector('form[method="POST"]');
    if (configForm) {
        configForm.addEventListener('submit', function() {
            // Add a small delay to allow the form to process
            setTimeout(() => {
                loadSchedulerStatus();
            }, 1000);
        });
    }
});
</script>


