<?php
/**
 * Admin functionality for BW Gallery
 */

if (!defined('ABSPATH')) {
    exit;
}

class BW_Gallery_Admin {
    
    private $db;
    
    public function __construct() {
        $this->db = new BW_Gallery_DB();
    }
    
    public function init() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
        add_action('wp_ajax_bwg_save_gallery', array($this, 'ajax_save_gallery'));
        add_action('wp_ajax_bwg_delete_gallery', array($this, 'ajax_delete_gallery'));
        add_action('wp_ajax_bwg_get_gallery', array($this, 'ajax_get_gallery'));
    }
    
    public function add_admin_menu() {
        add_menu_page(
            __('BW Gallery', 'bw-gallery'),
            __('BW Gallery', 'bw-gallery'),
            'manage_options',
            'bw-gallery',
            array($this, 'render_admin_page'),
            'dashicons-format-gallery',
            25
        );
        
        add_submenu_page(
            'bw-gallery',
            __('All Galleries', 'bw-gallery'),
            __('All Galleries', 'bw-gallery'),
            'manage_options',
            'bw-gallery',
            array($this, 'render_admin_page')
        );
        
        add_submenu_page(
            'bw-gallery',
            __('Add New Gallery', 'bw-gallery'),
            __('Add New', 'bw-gallery'),
            'manage_options',
            'bw-gallery-new',
            array($this, 'render_new_gallery_page')
        );
        
        add_submenu_page(
            'bw-gallery',
            __('Settings', 'bw-gallery'),
            __('Settings', 'bw-gallery'),
            'manage_options',
            'bw-gallery-settings',
            array($this, 'render_settings_page')
        );
    }
    
    public function enqueue_admin_assets($hook) {
        if (strpos($hook, 'bw-gallery') === false) {
            return;
        }
        
        wp_enqueue_media();
        wp_enqueue_style('bwg-admin', BWG_PLUGIN_URL . 'assets/css/admin.css', array(), BWG_VERSION);
        wp_enqueue_script('bwg-admin', BWG_PLUGIN_URL . 'assets/js/admin.js', array('jquery', 'jquery-ui-sortable'), BWG_VERSION, true);
        
        wp_localize_script('bwg-admin', 'bwg_admin', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('bwg_admin_nonce'),
            'strings' => array(
                'select_images' => __('Select Images', 'bw-gallery'),
                'use_images' => __('Use Selected Images', 'bw-gallery'),
                'confirm_delete' => __('Are you sure you want to delete this gallery?', 'bw-gallery'),
                'saving' => __('Saving...', 'bw-gallery'),
                'saved' => __('Saved!', 'bw-gallery'),
                'error' => __('An error occurred. Please try again.', 'bw-gallery')
            )
        ));
    }
    
    public function render_admin_page() {
        $galleries = $this->db->get_galleries();
        include BWG_PLUGIN_DIR . 'templates/admin/galleries-list.php';
    }
    
    public function render_new_gallery_page() {
        $gallery_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $gallery = null;
        
        if ($gallery_id) {
            $gallery = $this->db->get_gallery($gallery_id);
        }
        
        include BWG_PLUGIN_DIR . 'templates/admin/gallery-edit.php';
    }
    
    public function render_settings_page() {
        if (isset($_POST['submit'])) {
            $this->save_settings();
        }
        
        $settings = get_option('bwg_settings', array());
        include BWG_PLUGIN_DIR . 'templates/admin/settings.php';
    }
    
    private function save_settings() {
        if (!isset($_POST['bwg_settings_nonce']) || !wp_verify_nonce($_POST['bwg_settings_nonce'], 'bwg_save_settings')) {
            return;
        }
        
        $settings = array(
            'thumbnail_size' => sanitize_text_field($_POST['thumbnail_size']),
            'lightbox_enabled' => isset($_POST['lightbox_enabled']),
            'columns' => intval($_POST['columns']),
            'gap' => intval($_POST['gap'])
        );
        
        update_option('bwg_settings', $settings);
        
        add_settings_error('bwg_settings', 'settings_updated', __('Settings saved.', 'bw-gallery'), 'updated');
    }
    
    public function ajax_save_gallery() {
        check_ajax_referer('bwg_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('Insufficient permissions', 'bw-gallery'));
        }
        
        // Rate limiting
        if (!BW_Gallery_Helper::check_rate_limit('save_gallery', 20, 60)) {
            wp_send_json_error(array(
                'message' => __('Too many requests. Please wait a moment and try again.', 'bw-gallery')
            ));
        }
        
        $gallery_id = isset($_POST['gallery_id']) ? intval($_POST['gallery_id']) : 0;
        $gallery_data = array(
            'name' => sanitize_text_field($_POST['name']),
            'description' => sanitize_textarea_field($_POST['description']),
            'settings' => array(
                'enable_tabs' => isset($_POST['enable_tabs']),
                'lightbox' => isset($_POST['lightbox']),
                'columns' => intval($_POST['columns']),
                'gap' => intval($_POST['gap'])
            )
        );
        
        // Validate data
        $errors = BW_Gallery_Helper::validate_gallery_data($gallery_data);
        if (!empty($errors)) {
            wp_send_json_error(array(
                'message' => __('Validation failed.', 'bw-gallery'),
                'errors' => $errors
            ));
        }
        
        if ($gallery_id) {
            $this->db->update_gallery($gallery_id, $gallery_data);
            BW_Gallery_Helper::clear_gallery_cache($gallery_id);
        } else {
            $gallery_id = $this->db->insert_gallery($gallery_data);
        }
        
        // Update images
        if (isset($_POST['images']) && is_array($_POST['images'])) {
            $this->db->update_gallery_images($gallery_id, $_POST['images']);
        }
        
        // Log the action
        BW_Gallery_Helper::log("Gallery saved: ID $gallery_id by user " . get_current_user_id());
        
        wp_send_json_success(array(
            'gallery_id' => $gallery_id,
            'message' => __('Gallery saved successfully!', 'bw-gallery')
        ));
    }
    
    public function ajax_delete_gallery() {
        check_ajax_referer('bwg_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('Insufficient permissions', 'bw-gallery'));
        }
        
        $gallery_id = intval($_POST['gallery_id']);
        $this->db->delete_gallery($gallery_id);
        
        wp_send_json_success(array(
            'message' => __('Gallery deleted successfully!', 'bw-gallery')
        ));
    }
    
    public function ajax_get_gallery() {
        check_ajax_referer('bwg_admin_nonce', 'nonce');
        
        $gallery_id = intval($_POST['gallery_id']);
        $gallery = $this->db->get_gallery($gallery_id);
        $images = $this->db->get_gallery_images($gallery_id);
        
        wp_send_json_success(array(
            'gallery' => $gallery,
            'images' => $images
        ));
    }
}