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

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

if ($submitted_pin !== $admin_pin) {
    echo json_encode(array('success' => false, 'message' => 'Invalid PIN'));
    exit();
}

// Security check: only allow .sql files
if (pathinfo($filename, PATHINFO_EXTENSION) != 'sql') {
    echo json_encode(array('success' => false, 'message' => 'Invalid file type'));
    exit();
}

// Get admin details for notification
$admin_id = $_SESSION['admin_id'] ?? $_SESSION['user_id'] ?? 1;
$adminQuery = mysqli_query($conn, "SELECT first_name, email FROM users WHERE id='$admin_id'");
$adminData = mysqli_fetch_assoc($adminQuery);
$admin_name = $adminData['first_name'] ?? 'System Administrator';
$admin_email = $adminData['email'] ?? 'admin@system.com';

// Get file info before deletion
$filepath = '../backups/' . $filename;
$file_exists = file_exists($filepath);
$file_size = $file_exists ? filesize($filepath) : 0;
$formatted_size = formatSize($file_size);
$file_date = $file_exists ? date('F j, Y g:i A', filemtime($filepath)) : 'Unknown';
$backup_age = $file_exists ? round((time() - filemtime($filepath)) / (60 * 60 * 24), 1) : 0;

// Delete file
if ($file_exists) {
    if (unlink($filepath)) {
        // Log activity
        $log_sql = "INSERT INTO admin_activities (admin_id, admin_name, admin_role, action, description, module, created_at) 
                    VALUES ($admin_id, 'System Admin', 'admin', 'Backup Deleted', 'Deleted backup file: $filename', 'System Settings', NOW())";
        mysqli_query($conn, $log_sql);
        
        // NOTIFICATION: Backup Deleted (ADMIN)
        $mail_subject = "Database Backup Deleted";
        $mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Database Backup Deleted</h2>
                            
                            <p class='message'>
                                A database backup file has been deleted from the system by an administrator.
                            </p>

                            <!-- Deletion Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>Deleted File:</strong> " . $filename . "<br>
                                    <strong>File Size:</strong> " . $formatted_size . "<br>
                                    <strong>File Age:</strong> " . $backup_age . " days old<br>
                                    <strong>Original Date:</strong> " . $file_date . "<br>
                                    <strong>Deleted By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                    <strong>Deletion Time:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "<br>
                                    <strong>Action Type:</strong> Manual Deletion<br>
                                    <strong>Status:</strong> <span style='color: #dc3545; font-weight: bold;'>PERMANENTLY DELETED</span>
                                </div>
                            </div>

                            <!-- Impact Analysis -->
                            <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #721c24;'>⚠️ Data Loss Warning</h4>
                                <p style='color: #721c24;'>
                                    <strong>This action is irreversible!</strong><br>
                                    The backup file has been permanently deleted from the server.<br>
                                    Recovery is not possible through normal means.
                                </p>
                            </div>

                            <!-- Available Backups Check -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>📊 Remaining Backups Status</h3>
                                <p style='color: #6c757d;'>
                                    After this deletion:<br>
                                    • Check remaining backups in backup directory<br>
                                    • Ensure minimum backup retention policy is maintained<br>
                                    • Verify backup rotation is functioning properly<br>
                                    • Monitor available storage space
                                </p>
                            </div>

                            <!-- Why Delete Backups? -->
                            <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #856404;'>🗑️ Common Reasons for Backup Deletion</h4>
                                <ul style='color: #856404;'>
                                    <li>Backup exceeded retention period (" . $backup_age . " days)</li>
                                    <li>Storage space optimization</li>
                                    <li>Corrupted or incomplete backup file</li>
                                    <li>Security compliance requirements</li>
                                    <li>Manual cleanup of old backups</li>
                                </ul>
                            </div>

                            <!-- Recovery Options -->
                            <div style='background: #d1ecf1; border: 1px solid #bee5eb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0c5460;'>🔄 If This Was a Mistake</h4>
                                <p style='color: #0c5460;'>
                                    <strong>Immediate Actions:</strong><br>
                                    1. Check if file was recently backed up elsewhere<br>
                                    2. Look for alternative backup copies<br>
                                    3. Check server recycle bin/trash (if enabled)<br>
                                    4. Consider creating a new backup immediately
                                </p>
                            </div>

                            <!-- Admin Actions -->
                            <div style='text-align: center; margin: 30px 0;'>
                                <a href='" . $myUrl . "/admin/backup.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 Remaining Backups
                                </a>
                                <a href='" . $myUrl . "/admin/create-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;'>
                                    Create New Backup
                                </a>
                            </div>

                            <!-- System Information -->
                            <div class='support-section'>
                                <p class='support-text'>System Information:</p>
                                <p style='color: #6c757d; font-size: 12px;'>
                                    <strong>Backup Directory:</strong> ../backups/<br>
                                    <strong>Files Remaining:</strong> " . count(glob('../backups/*.sql')) . " SQL files<br>
                                    <strong>Total Storage:</strong> " . formatSize(array_sum(array_map('filesize', glob('../backups/*.sql')))) . "<br>
                                    <strong>Deletion Method:</strong> Manual via Admin Panel
                                </p>
                            </div>
                        </div>";

        // Send admin notification
        require_once("../proccess/admin_mailer.php");
        
        echo json_encode(array('success' => true, 'message' => 'Backup deleted successfully'));
    } else {
        echo json_encode(array('success' => false, 'message' => 'Failed to delete backup file'));
    }
} else {
    echo json_encode(array('success' => false, 'message' => 'Backup file not found'));
}

function formatSize($bytes) {
    if ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } else {
        return $bytes . ' bytes';
    }
}
?>