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

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

if ($submitted_pin !== $admin_pin) {
    echo json_encode(array('success' => false, 'message' => 'Invalid PIN'));
    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';

// Create backup directory if it doesn't exist
$backup_dir = '../backups/';
if (!file_exists($backup_dir)) {
    mkdir($backup_dir, 0755, true);
}

// Generate filename
$filename = 'backup_' . date('Y-m-d_H-i-s') . '.sql';
$filepath = $backup_dir . $filename;

// Get all tables
$tables = array();
$result = mysqli_query($conn, 'SHOW TABLES');
$total_tables = 0;
while ($row = mysqli_fetch_row($result)) {
    $tables[] = $row[0];
    $total_tables++;
}

// Start backup file
$output = "-- Database Backup\n";
$output .= "-- Generated: " . date('Y-m-d H:i:s') . "\n";
$output .= "-- Host: " . $_SERVER['HTTP_HOST'] . "\n";
$output .= "-- Generated by: " . $admin_name . " (ID: " . $admin_id . ")\n";
$output .= "\nSET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\n";
$output .= "START TRANSACTION;\n";
$output .= "SET time_zone = \"+00:00\";\n\n";

// Count total records
$total_records = 0;
foreach ($tables as $table) {
    $count_result = mysqli_query($conn, "SELECT COUNT(*) as count FROM `$table`");
    $count_row = mysqli_fetch_assoc($count_result);
    $total_records += $count_row['count'];
}

// Loop through tables
foreach ($tables as $table) {
    // Drop table if exists
    $output .= "DROP TABLE IF EXISTS `$table`;\n";
    
    // Get table structure
    $result = mysqli_query($conn, "SHOW CREATE TABLE `$table`");
    $row = mysqli_fetch_row($result);
    $output .= "\n" . $row[1] . ";\n\n";
    
    // Get table data
    $result = mysqli_query($conn, "SELECT * FROM `$table`");
    $num_fields = mysqli_num_fields($result);
    
    if (mysqli_num_rows($result) > 0) {
        $output .= "INSERT INTO `$table` VALUES\n";
        
        $row_count = 0;
        while ($row = mysqli_fetch_row($result)) {
            $output .= "(";
            for ($j = 0; $j < $num_fields; $j++) {
                $row[$j] = addslashes($row[$j]);
                $row[$j] = str_replace("\n", "\\n", $row[$j]);
                
                if (isset($row[$j])) {
                    $output .= '"' . $row[$j] . '"';
                } else {
                    $output .= '""';
                }
                
                if ($j < ($num_fields - 1)) {
                    $output .= ',';
                }
            }
            
            $row_count++;
            if ($row_count < mysqli_num_rows($result)) {
                $output .= "),\n";
            } else {
                $output .= ");\n\n";
            }
        }
    }
}

$output .= "\nCOMMIT;\n";

// Write to file
if (file_put_contents($filepath, $output)) {
    $file_size = filesize($filepath);
    $formatted_size = formatSize($file_size);
    
    // Update last backup setting
    $update_sql = "INSERT INTO system_settings (setting_key, setting_value, created_at, updated_at) 
                   VALUES ('last_backup', '" . date('Y-m-d H:i:s') . "', NOW(), NOW())
                   ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = NOW()";
    mysqli_query($conn, $update_sql);
    
    // Log activity
    $admin_id = $_SESSION['admin_id'] ?: 1;
    $log_sql = "INSERT INTO admin_activities (admin_id, admin_name, admin_role, action, description, module, created_at) 
                VALUES ($admin_id, 'System Admin', 'admin', 'Database Backup', 'Created database backup: $filename', 'System Settings', NOW())";
    mysqli_query($conn, $log_sql);
    
    // NOTIFICATION: Database Backup Created (ADMIN)
    $mail_subject = "Database Backup Created Successfully";
    $mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>Database Backup Created</h2>
                        
                        <p class='message'>
                            A manual database backup has been successfully created by an administrator.
                        </p>

                        <!-- Backup Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Backup File:</strong> " . $filename . "<br>
                                <strong>File Size:</strong> " . $formatted_size . "<br>
                                <strong>Location:</strong> " . $backup_dir . "<br>
                                <strong>Created By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                <strong>Creation Time:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Database Statistics:</strong><br>
                                &nbsp;&nbsp;• Tables: " . $total_tables . "<br>
                                &nbsp;&nbsp;• Total Records: " . number_format($total_records) . "<br>
                                &nbsp;&nbsp;• Backup Duration: " . round(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], 2) . " seconds<br>
                                <strong>Status:</strong> <span style='color: #28a745; font-weight: bold;'>COMPLETED</span>
                            </div>
                        </div>

                        <!-- Backup Integrity Check -->
                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #0056b3;'>✅ Backup Integrity Verified</h4>
                            <p style='color: #0056b3;'>
                                <strong>Verification:</strong> All " . $total_tables . " tables backed up successfully<br>
                                <strong>File Status:</strong> File created and writeable<br>
                                <strong>Size Validation:</strong> " . $formatted_size . " (non-zero file)<br>
                                <strong>Structure:</strong> SQL format with proper encoding
                            </p>
                        </div>

                        <!-- Recovery Instructions -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>📋 Recovery Instructions</h3>
                            <p style='color: #6c757d;'>To restore from this backup:</p>
                            <ol style='color: #6c757d;'>
                                <li>Download the backup file from: " . $backup_dir . $filename . "</li>
                                <li>Use phpMyAdmin or MySQL command line</li>
                                <li>Import the SQL file to your database</li>
                                <li>Verify data integrity after restore</li>
                            </ol>
                        </div>

                        <!-- Security Notes -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>🔒 Security Recommendations</h4>
                            <ul style='color: #856404;'>
                                <li>Store backup files in a secure location</li>
                                <li>Encrypt sensitive backup files</li>
                                <li>Regularly test backup restoration</li>
                                <li>Keep multiple backup versions</li>
                                <li>Monitor backup storage space</li>
                            </ul>
                        </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 All Backups
                            </a>
                            <a href='" . $myUrl . "/admin/download-backup.php?file=" . urlencode($filename) . "' 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;'>
                                Download Backup
                            </a>
                        </div>

                        <!-- System Information -->
                        <div class='support-section'>
                            <p class='support-text'>System Information:</p>
                            <p style='color: #6c757d; font-size: 12px;'>
                                <strong>Server:</strong> " . $_SERVER['SERVER_NAME'] . "<br>
                                <strong>Database:</strong> " . mysqli_get_host_info($conn) . "<br>
                                <strong>PHP Version:</strong> " . PHP_VERSION . "<br>
                                <strong>Backup Method:</strong> Manual SQL Export
                            </p>
                        </div>
                    </div>";

    // Send admin notification
    require_once("../proccess/admin_mailer.php");
    
    echo json_encode(array(
        'success' => true,
        'filename' => $filename,
        'size' => $formatted_size
    ));
} else {
    echo json_encode(array('success' => false, 'message' => 'Failed to create backup file'));
}

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';
    }
}
?>