<?php
if (!defined('ABSPATH')) exit;

class SIMPINBY_Admin_Menu {

    public function __construct() {
        add_action('admin_menu', [$this, 'register_menu']);
        add_action('admin_enqueue_scripts', [$this, 'load_assets']);
    }

    public function register_menu() {
        add_menu_page(
            "Invoice Management",
            "Invoice Management",
            "manage_options",
            "simpinby-dashboard",
            [$this, "dashboard_page"],
            "dashicons-media-spreadsheet"
        );

        add_submenu_page("simpinby-dashboard", "Dashboard", "Dashboard", "manage_options", "simpinby-dashboard", [$this, "dashboard_page"]);
        add_submenu_page("simpinby-dashboard", "Manage Invoices", "Manage Invoices", "manage_options", "simpinby-invoices", [$this, "invoices_page"]);
        add_submenu_page("simpinby-dashboard", "Settings", "Settings", "manage_options", "simpinby-settings", [$this, "settings_page"]);
    }

    public function load_assets($hook) {
        if ( false === strpos( $hook, 'simpinby-' ) ) {
            return;
        }
        wp_enqueue_media();
        wp_enqueue_style("simpinby-admin-css", SIMPINBY_PLUGIN_URL . "admin/assets/admin.css", [], SIMPINBY_VERSION);
        wp_enqueue_script("simpinby-admin-js", SIMPINBY_PLUGIN_URL . "admin/assets/admin.js", ["jquery"], SIMPINBY_VERSION, true);
        $cur = simpinby_get_currency();
        wp_localize_script("simpinby-admin-js", "SIMPINBY_DATA", [
            "currency_symbol" => $cur["symbol"] ?? "₹",
            "ajax_url" => admin_url("admin-ajax.php"),
            "nonce" => wp_create_nonce("simpinby_ajax_nonce"),
        ]);
    }

    public function dashboard_page() {
        include SIMPINBY_PLUGIN_PATH . "admin/pages/dashboard.php";
    }

    public function invoices_page() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Action is used only for page routing.
        $action = isset($_GET['action'])
         // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Action is used only for page routing.
            ? sanitize_text_field( wp_unslash($_GET['action']) )
            : 'list';

        $allowed_actions = ['list', 'create', 'view'];

        if ( ! in_array( $action, $allowed_actions, true ) ) {
            $action = 'list';
        }


        if ($action === 'create') {
            include SIMPINBY_PLUGIN_PATH . "admin/pages/invoice-create.php";
        } elseif ($action === 'view') {
            include SIMPINBY_PLUGIN_PATH . "admin/pages/invoice-view.php";
        } else {
            include SIMPINBY_PLUGIN_PATH . "admin/pages/invoices-list.php";
        }
    }



    public function settings_page() {
        include SIMPINBY_PLUGIN_PATH . "admin/pages/settings.php";
    }
}
