<?php
session_start();
include('../includes/config.php');
include('../includes/functions.php');

// Check PIN
$admin_pin = "1234";
$submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';

if ($submitted_pin !== $admin_pin) {
    header('Location: ../system_settings.php?error=Invalid PIN');
    exit();
}

$action = isset($_POST['action']) ? $_POST['action'] : '';

if ($action == 'save_backup_settings') {
    $auto_backup = isset($_POST['auto_backup']) ? 1 : 0;
    $backup_frequency = mysqli_real_escape_string($conn, $_POST['backup_frequency']);
    $keep_backups_days = intval($_POST['keep_backups_days']);
    
    $settings = array(
        'auto_backup' => $auto_backup,
        'backup_frequency' => $backup_frequency,
        'keep_backups_days' => $keep_backups_days
    );
    
    // Get admin details for notification
    $admin_id = $_SESSION['user_id'] ?? 0;
    $adminQuery = mysqli_query($conn, "SELECT first_name, email FROM users WHERE id='$admin_id'");
    $adminData = mysqli_fetch_assoc($adminQuery);
    $admin_name = $adminData['first_name'] ?? 'Administrator';
    $admin_email = $adminData['email'] ?? 'admin@system.com';
    
    foreach ($settings as $key => $value) {
        saveSetting($conn, $key, $value);
    }
    
    // NOTIFICATION: System Settings Updated (ADMIN)
    $mail_subject = "System Backup Settings Updated";
    $mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>System Settings Updated</h2>
                        
                        <p class='message'>
                            The system backup settings have been modified successfully.
                        </p>

                        <!-- Settings Update Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Updated By:</strong> " . $admin_name . " (Admin ID: " . $admin_id . ")<br>
                                <strong>Update Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Action:</strong> Backup Settings Configuration<br>
                                <strong>Auto Backup:</strong> " . ($auto_backup == 1 ? '<span style="color: #28a745;">Enabled</span>' : '<span style="color: #dc3545;">Disabled</span>') . "<br>
                                <strong>Backup Frequency:</strong> " . $backup_frequency . "<br>
                                <strong>Keep Backups:</strong> " . $keep_backups_days . " days<br>
                                <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "
                            </div>
                        </div>

                        <!-- System Impact -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>System Impact</h3>
                            <p style='color: #6c757d;'>
                                With these new settings:<br>
                                • Backups will " . ($auto_backup == 1 ? 'run automatically ' . $backup_frequency : 'require manual triggering') . "<br>
                                • Old backups will be automatically deleted after " . $keep_backups_days . " days<br>
                                • Next scheduled backup: " . ($auto_backup == 1 ? date('F j, Y', strtotime('+1 ' . $backup_frequency)) : 'Manual only') . "<br>
                                • Storage will be optimized with " . $keep_backups_days . "-day retention
                            </p>
                        </div>

                        <!-- Security Notes -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>🔒 Security Notes</h4>
                            <ul style='color: #856404;'>
                                <li>Regular backups protect against data loss</li>
                                <li>" . $keep_backups_days . "-day retention balances storage and recovery needs</li>
                                <li>Auto-backup ensures consistent data protection</li>
                                <li>Monitor backup storage space regularly</li>
                            </ul>
                        </div>

                        <!-- Admin Actions -->
                        <div style='text-align: center; margin: 30px 0;'>
                            <a href='" . $myUrl . "/admin/system_settings.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                View Settings
                            </a>
                            <a href='" . $myUrl . "/admin/backup.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                Manage Backups
                            </a>
                        </div>

                        <!-- Technical Details -->
                        <div class='support-section'>
                            <p class='support-text'>System Information:</p>
                            <p style='color: #6c757d; font-size: 12px;'>
                                <strong>Server Time:</strong> " . date('Y-m-d H:i:s') . "<br>
                                <strong>Admin Session:</strong> Active<br>
                                <strong>Settings Updated:</strong> Backup Configuration
                            </p>
                        </div>
                    </div>";

    // Send admin notification
    require_once("../proccess/admin_mailer.php");
    
    logAdminActivity('Backup Settings Updated', 'Updated backup system settings', 'System Settings');
    header('Location: ../system_settings.php?success=Backup settings updated successfully!');
    exit();
}

function saveSetting($conn, $key, $value) {
    $check = "SELECT id FROM system_settings WHERE setting_key = '$key'";
    $result = mysqli_query($conn, $check);
    
    if (mysqli_num_rows($result) > 0) {
        $sql = "UPDATE system_settings SET setting_value = '$value', updated_at = NOW() WHERE setting_key = '$key'";
    } else {
        $sql = "INSERT INTO system_settings (setting_key, setting_value, created_at, updated_at) 
                VALUES ('$key', '$value', NOW(), NOW())";
    }
    
    return mysqli_query($conn, $sql);
}
?>