Path : /home/vishqocm/pcib.in/admin/
File Upload :
Current File : //home/vishqocm/pcib.in/admin/import_theme.php

<?php
// Include database connection
require_once '../config/database.php';

// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Check if user is logged in and is admin
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] !== 'admin' && $_SESSION['role'] !== 'director')) {
    header('Location: login.php');
    exit;
}

// Initialize error and success messages
$error = '';
$success = '';

// Default theme settings
$default_theme = [
    'theme_name' => 'Default Theme',
    'header_bg_color' => '#ffffff',
    'footer_bg_color' => '#f8f9fc',
    'text_color' => '#333333',
    'link_color' => '#4e73df',
    'button_style' => 'rounded',
    'font_family' => "'Poppins', sans-serif",
    'custom_css' => ''
];

// Handle template selection
if (isset($_POST['apply_template']) && isset($_POST['template_file'])) {
    $template_file = $_POST['template_file'];
    $template_path = __DIR__ . '/theme_templates/' . $template_file;
    
    if (file_exists($template_path)) {
        $theme_data = file_get_contents($template_path);
        $theme_settings = json_decode($theme_data, true);
        
        if (!$theme_settings || !is_array($theme_settings)) {
            $error = 'Invalid template file format.';
        } else {
            // Update theme settings in database
            foreach ($theme_settings as $key => $value) {
                // Escape the value
                $value = mysqli_real_escape_string($conn, $value);
                
                // Check if setting exists
                $check_query = "SELECT * FROM theme_settings WHERE setting_key = '$key'";
                $check_result = mysqli_query($conn, $check_query);
                
                if (mysqli_num_rows($check_result) > 0) {
                    // Update existing setting
                    $update_query = "UPDATE theme_settings SET setting_value = '$value' WHERE setting_key = '$key'";
                    mysqli_query($conn, $update_query);
                } else {
                    // Insert new setting
                    $insert_query = "INSERT INTO theme_settings (setting_key, setting_value) VALUES ('$key', '$value')";
                    mysqli_query($conn, $insert_query);
                }
            }
            
            $success = 'Template "' . $theme_settings['theme_name'] . '" applied successfully.';
        }
    } else {
        $error = 'Template file not found.';
    }
}

// Handle reset to default
if (isset($_POST['apply_template']) && isset($_POST['reset_to_default'])) {
    // Update theme settings in database
    foreach ($default_theme as $key => $value) {
        // Escape the value
        $value = mysqli_real_escape_string($conn, $value);
        
        // Check if setting exists
        $check_query = "SELECT * FROM theme_settings WHERE setting_key = '$key'";
        $check_result = mysqli_query($conn, $check_query);
        
        if (mysqli_num_rows($check_result) > 0) {
            // Update existing setting
            $update_query = "UPDATE theme_settings SET setting_value = '$value' WHERE setting_key = '$key'";
            mysqli_query($conn, $update_query);
        } else {
            // Insert new setting
            $insert_query = "INSERT INTO theme_settings (setting_key, setting_value) VALUES ('$key', '$value')";
            mysqli_query($conn, $insert_query);
        }
    }
    
    $success = 'Theme reset to default successfully.';
}

// Handle theme file upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['theme_file'])) {
    // Check if file upload has errors
    if ($_FILES['theme_file']['error'] === UPLOAD_ERR_OK) {
        // Verify file is a JSON file
        $file_info = pathinfo($_FILES['theme_file']['name']);
        if ($file_info['extension'] !== 'json') {
            $error = 'Uploaded file must be a JSON file.';
        } else {
            // Read and parse the uploaded JSON file
            $theme_data = file_get_contents($_FILES['theme_file']['tmp_name']);
            $theme_settings = json_decode($theme_data, true);
            
            // Validate theme settings
            if (!$theme_settings || !is_array($theme_settings)) {
                $error = 'Invalid theme file format.';
            } else {
                // Required theme settings keys
                $required_keys = [
                    'theme_name',
                    'header_bg_color',
                    'footer_bg_color',
                    'text_color',
                    'link_color',
                    'button_style',
                    'font_family'
                ];
                
                // Check if required keys exist
                $missing_keys = [];
                foreach ($required_keys as $key) {
                    if (!isset($theme_settings[$key])) {
                        $missing_keys[] = $key;
                    }
                }
                
                if (!empty($missing_keys)) {
                    $error = 'Theme file is missing required settings: ' . implode(', ', $missing_keys);
                } else {
                    // Update theme settings in database
                    foreach ($theme_settings as $key => $value) {
                        // Check if setting exists
                        $check_query = "SELECT * FROM theme_settings WHERE setting_key = '$key'";
                        $check_result = mysqli_query($conn, $check_query);
                        
                        // Escape the value
                        $value = mysqli_real_escape_string($conn, $value);
                        
                        if (mysqli_num_rows($check_result) > 0) {
                            // Update existing setting
                            $update_query = "UPDATE theme_settings SET setting_value = '$value' WHERE setting_key = '$key'";
                            mysqli_query($conn, $update_query);
                        } else {
                            // Insert new setting
                            $insert_query = "INSERT INTO theme_settings (setting_key, setting_value) VALUES ('$key', '$value')";
                            mysqli_query($conn, $insert_query);
                        }
                    }
                    
                    $success = 'Theme settings imported successfully.';
                }
            }
        }
    } else {
        // Handle upload errors
        switch ($_FILES['theme_file']['error']) {
            case UPLOAD_ERR_INI_SIZE:
            case UPLOAD_ERR_FORM_SIZE:
                $error = 'The uploaded file exceeds the maximum file size.';
                break;
            case UPLOAD_ERR_PARTIAL:
                $error = 'The uploaded file was only partially uploaded.';
                break;
            case UPLOAD_ERR_NO_FILE:
                $error = 'No file was uploaded.';
                break;
            default:
                $error = 'An unknown error occurred during file upload.';
        }
    }
}

// Set session messages and redirect back to themes.php
if (!empty($error)) {
    $_SESSION['theme_import_error'] = $error;
} 
if (!empty($success)) {
    $_SESSION['theme_import_success'] = $success;
}

// Redirect back to the themes page
header('Location: themes.php');
exit;
?>