<?php
/**
 * Admin class for managing announcements in WordPress admin
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class PC_Announcements_274_Admin {
    
    /**
     * Constructor
     */
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        add_action('wp_ajax_pc_announcements_274_action', array($this, 'handle_ajax_requests'));
    }
    
    /**
     * Add admin menu items
     */
    public function add_admin_menu() {
        add_menu_page(
            __('Announcements', 'pc-announcements-274'),
            __('Announcements', 'pc-announcements-274'),
            'manage_options',
            'pc-announcements-274',
            array($this, 'render_announcements_page'),
            'dashicons-megaphone',
            25
        );
        
        add_submenu_page(
            'pc-announcements-274',
            __('All Announcements', 'pc-announcements-274'),
            __('All Announcements', 'pc-announcements-274'),
            'manage_options',
            'pc-announcements-274',
            array($this, 'render_announcements_page')
        );
        
        add_submenu_page(
            'pc-announcements-274',
            __('Add New', 'pc-announcements-274'),
            __('Add New', 'pc-announcements-274'),
            'manage_options',
            'pc-announcements-274-add',
            array($this, 'render_add_announcement_page')
        );
    }
    
    /**
     * Enqueue admin scripts and styles
     */
    public function enqueue_admin_scripts($hook) {
        if (strpos($hook, 'pc-announcements-274') === false) {
            return;
        }
        
        wp_enqueue_style('pc-announcements-274-admin-style', PC_ANNOUNCEMENTS_274_PLUGIN_URL . 'admin/css/admin-style.css', array('wp-admin'), PC_ANNOUNCEMENTS_274_VERSION);
        wp_enqueue_media();
        wp_enqueue_script('pc-announcements-274-admin-script', PC_ANNOUNCEMENTS_274_PLUGIN_URL . 'admin/js/admin-script.js', array('jquery'), PC_ANNOUNCEMENTS_274_VERSION, true);
        wp_localize_script('pc-announcements-274-admin-script', 'pc_announcements_274_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('pc_announcements_274_nonce'),
            'i18n' => array(
                'error_occurred' => __('An error occurred. Please try again.', 'pc-announcements-274'),
                'choose_image' => __('Choose Image', 'pc-announcements-274'),
                'preview' => __('Preview', 'pc-announcements-274'),
                'end_date_warning' => __('End date should be after start date.', 'pc-announcements-274')
            )
        ));
    }
    
    /**
     * Render main announcements page
     */
    public function render_announcements_page() {
        $current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
        $per_page = 20;
        $offset = ($current_page - 1) * $per_page;
        
        global $wpdb;
        $table_name = PC_Announcements_274_Install::get_table_name();
        
        if (empty($table_name)) {
            include PC_ANNOUNCEMENTS_274_PLUGIN_DIR . 'admin/templates/error-page.php';
            return;
        }
        
        // Get total count
        $total = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
        if ($total === null) {
            $total = 0;
        }
        $total_pages = ceil($total / $per_page);
        
        // Get announcements
        $announcements = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table_name ORDER BY created_at DESC LIMIT %d OFFSET %d",
            $per_page, $offset
        ));
        
        if ($announcements === null) {
            $announcements = array();
        }
        
        include PC_ANNOUNCEMENTS_274_PLUGIN_DIR . 'admin/templates/list-page.php';
    }
    
    /**
     * Render add new announcement page
     */
    public function render_add_announcement_page() {
        $announcement_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $announcement = null;
        
        if ($announcement_id > 0) {
            global $wpdb;
            $table_name = PC_Announcements_274_Install::get_table_name();
            
            if (!empty($table_name)) {
                $announcement = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $announcement_id));
            }
        }
        
        include PC_ANNOUNCEMENTS_274_PLUGIN_DIR . 'admin/templates/edit-page.php';
    }
    
    /**
     * Handle AJAX requests
     */
    public function handle_ajax_requests() {
        check_ajax_referer('pc_announcements_274_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions.', 'pc-announcements-274'));
        }
        
        $action = isset($_POST['sub_action']) ? sanitize_text_field($_POST['sub_action']) : '';
        
        switch ($action) {
            case 'save_announcement':
                $this->save_announcement();
                break;
            case 'delete_announcement':
                $this->delete_announcement();
                break;
            default:
                wp_send_json_error(array('message' => __('Invalid action.', 'pc-announcements-274')));
        }
    }
    
    /**
     * Save announcement
     */
    private function save_announcement() {
        global $wpdb;
        $table_name = PC_Announcements_274_Install::get_table_name();
        
        $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
        $title = sanitize_text_field($_POST['title']);
        $message = wp_kses_post($_POST['message']);
        $banner_color = sanitize_hex_color($_POST['banner_color']);
        $link_url = esc_url_raw($_POST['link_url']);
        $image_url = esc_url_raw($_POST['image_url']);
        $start_date = !empty($_POST['start_date']) ? sanitize_text_field($_POST['start_date']) : null;
        $end_date = !empty($_POST['end_date']) ? sanitize_text_field($_POST['end_date']) : null;
        $status = sanitize_text_field($_POST['status']);
        
        if (empty($title)) {
            wp_send_json_error(array('message' => __('Title is required.', 'pc-announcements-274')));
        }
        
        if (empty($banner_color)) {
            $banner_color = '#0d47a1';
        }
        
        $data = array(
            'title' => $title,
            'message' => $message,
            'banner_color' => $banner_color,
            'link_url' => $link_url,
            'image_url' => $image_url,
            'start_date' => $start_date,
            'end_date' => $end_date,
            'status' => $status,
            'updated_at' => current_time('mysql')
        );
        
        $format = array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');
        
        if ($id > 0) {
            $result = $wpdb->update($table_name, $data, array('id' => $id), $format, array('%d'));
        } else {
            $data['created_at'] = current_time('mysql');
            $data['created_by'] = get_current_user_id();
            $format = array('%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');
            
            $result = $wpdb->insert($table_name, $data, $format);
            $id = $wpdb->insert_id;
        }
        
        if ($result === false) {
            wp_send_json_error(array('message' => __('Failed to save announcement.', 'pc-announcements-274')));
        }
        
        wp_send_json_success(array(
            'message' => $id > 0 && isset($_POST['id']) ? __('Announcement updated successfully!', 'pc-announcements-274') : __('Announcement created successfully!', 'pc-announcements-274'),
            'id' => $id
        ));
    }
    
    /**
     * Delete announcement
     */
    private function delete_announcement() {
        global $wpdb;
        $table_name = PC_Announcements_274_Install::get_table_name();
        
        $id = intval($_POST['id']);
        
        if ($id <= 0) {
            wp_send_json_error(array('message' => __('Invalid announcement ID.', 'pc-announcements-274')));
        }
        
        $result = $wpdb->delete($table_name, array('id' => $id), array('%d'));
        
        if ($result === false) {
            wp_send_json_error(array('message' => __('Failed to delete announcement.', 'pc-announcements-274')));
        }
        
        wp_send_json_success(array('message' => __('Announcement deleted successfully!', 'pc-announcements-274')));
    }
}