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

class ROS_Admin {

    public function __construct() {
        add_action( 'admin_menu', [ $this, 'add_menus' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue' ] );
        add_action( 'admin_post_ros_save_settings', [ $this, 'save_settings' ] );
        add_action( 'admin_post_ros_save_category', [ $this, 'save_category' ] );
        add_action( 'admin_post_ros_delete_category', [ $this, 'delete_category' ] );
        add_action( 'admin_post_ros_save_dish', [ $this, 'save_dish' ] );
        add_action( 'admin_post_ros_delete_dish', [ $this, 'delete_dish' ] );
        add_action( 'admin_post_ros_save_table', [ $this, 'save_table' ] );
        add_action( 'admin_post_ros_delete_table', [ $this, 'delete_table' ] );
        // Register kitchen role
        add_action( 'init', [ $this, 'register_role' ] );
    }

    public function register_role() {
        if ( ! get_role( 'ros_kitchen' ) ) {
            add_role( 'ros_kitchen', 'Kitchen Staff', [
                'read' => true,
            ] );
        }
    }

    public function enqueue( $hook ) {
        if ( strpos( $hook, 'ros' ) === false ) return;
        wp_enqueue_style( 'ros-admin', ROS_URL . 'public/css/ros-admin.css', [], ROS_VERSION );
        wp_enqueue_media();
    }

    public function add_menus() {
        add_menu_page( 'Restaurant', 'Restaurant', 'manage_options', 'ros-dashboard',
            [ $this, 'page_dashboard' ], 'dashicons-food', 30 );
        add_submenu_page( 'ros-dashboard', 'Settings', 'Settings', 'manage_options', 'ros-settings', [ $this, 'page_settings' ] );
        add_submenu_page( 'ros-dashboard', 'Menu', 'Menu', 'manage_options', 'ros-menu', [ $this, 'page_menu' ] );
        add_submenu_page( 'ros-dashboard', 'Tables', 'Tables', 'manage_options', 'ros-tables', [ $this, 'page_tables' ] );
        add_submenu_page( 'ros-dashboard', 'Orders', 'Orders', 'manage_options', 'ros-orders', [ $this, 'page_orders' ] );
        add_submenu_page( 'ros-dashboard', 'Bonnen Archief', 'Bonnen', 'manage_options', 'ros-receipts', [ $this, 'page_receipts' ] );
        add_submenu_page( 'ros-dashboard', 'Report', 'Report', 'manage_options', 'ros-report', [ $this, 'page_report' ] );
    }

    private function render( $file ) {
        include ROS_PATH . 'templates/admin/' . $file . '.php';
    }

    public function page_dashboard() { $this->render( 'dashboard' ); }
    public function page_settings()  { $this->render( 'settings' ); }
    public function page_menu()      { $this->render( 'menu' ); }
    public function page_tables()    { $this->render( 'tables' ); }
    public function page_orders()    { $this->render( 'orders' ); }
    public function page_receipts()  { $this->render( 'receipts' ); }
    public function page_report()    { $this->render( 'report' ); }

    public function save_settings() {
        check_admin_referer( 'ros_settings' );
        global $wpdb;
        $fields = [ 'restaurant_name', 'restaurant_address', 'restaurant_phone', 'logo_url', 'currency_symbol' ];
        foreach ( $fields as $field ) {
            $value = sanitize_text_field( $_POST[ $field ] ?? '' );
            $wpdb->query( $wpdb->prepare(
                "INSERT INTO {$wpdb->prefix}ros_settings (setting_key, setting_value) VALUES (%s, %s)
                 ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)",
                $field, $value
            ) );
        }
        // Stripe keys — only update if provided (not empty)
        if ( ! empty( $_POST['stripe_pk'] ) ) {
            $wpdb->query( $wpdb->prepare(
                "INSERT INTO {$wpdb->prefix}ros_settings (setting_key, setting_value) VALUES ('stripe_pk', %s)
                 ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)",
                sanitize_text_field( $_POST['stripe_pk'] )
            ) );
        }
        if ( ! empty( $_POST['stripe_sk'] ) ) {
            // Encrypt with WordPress salt
            $wpdb->query( $wpdb->prepare(
                "INSERT INTO {$wpdb->prefix}ros_settings (setting_key, setting_value) VALUES ('stripe_sk', %s)
                 ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)",
                sanitize_text_field( $_POST['stripe_sk'] )
            ) );
        }
        $stripe_enabled = isset( $_POST['stripe_enabled'] ) ? '1' : '0';
        $wpdb->query( $wpdb->prepare(
            "INSERT INTO {$wpdb->prefix}ros_settings (setting_key, setting_value) VALUES ('stripe_enabled', %s)
             ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)",
            $stripe_enabled
        ) );

        wp_redirect( admin_url( 'admin.php?page=ros-settings&saved=1' ) );
        exit;
    }

    public function save_category() {
        check_admin_referer( 'ros_category' );
        global $wpdb;
        $id   = intval( $_POST['cat_id'] ?? 0 );
        $name = sanitize_text_field( $_POST['name'] ?? '' );
        $sort = intval( $_POST['sort_order'] ?? 0 );
        if ( $id ) {
            $wpdb->update( $wpdb->prefix . 'ros_categories', compact( 'name' ) + [ 'sort_order' => $sort ], [ 'id' => $id ] );
        } else {
            $wpdb->insert( $wpdb->prefix . 'ros_categories', [ 'name' => $name, 'sort_order' => $sort ] );
        }
        wp_redirect( admin_url( 'admin.php?page=ros-menu&saved=1' ) );
        exit;
    }

    public function delete_category() {
        check_admin_referer( 'ros_del_cat' );
        global $wpdb;
        $id = intval( $_GET['id'] ?? 0 );
        $wpdb->delete( $wpdb->prefix . 'ros_categories', [ 'id' => $id ] );
        $wpdb->delete( $wpdb->prefix . 'ros_dishes', [ 'category_id' => $id ] );
        wp_redirect( admin_url( 'admin.php?page=ros-menu' ) );
        exit;
    }

    public function save_dish() {
        check_admin_referer( 'ros_dish' );
        global $wpdb;
        $id          = intval( $_POST['dish_id'] ?? 0 );
        $category_id = intval( $_POST['category_id'] ?? 0 );
        $name        = sanitize_text_field( $_POST['name'] ?? '' );
        $description = sanitize_textarea_field( $_POST['description'] ?? '' );
        $price       = floatval( $_POST['price'] ?? 0 );
        $image_url   = esc_url_raw( $_POST['image_url'] ?? '' );
        $available   = isset( $_POST['available'] ) ? 1 : 0;
        $sort        = intval( $_POST['sort_order'] ?? 0 );
        $data        = compact( 'category_id', 'name', 'description', 'price', 'image_url', 'available' ) + [ 'sort_order' => $sort ];
        if ( $id ) {
            $wpdb->update( $wpdb->prefix . 'ros_dishes', $data, [ 'id' => $id ] );
        } else {
            $wpdb->insert( $wpdb->prefix . 'ros_dishes', $data );
        }
        wp_redirect( admin_url( 'admin.php?page=ros-menu&cat=' . $category_id . '&saved=1' ) );
        exit;
    }

    public function delete_dish() {
        check_admin_referer( 'ros_del_dish' );
        global $wpdb;
        $id  = intval( $_GET['id'] ?? 0 );
        $cat = intval( $_GET['cat'] ?? 0 );
        $wpdb->delete( $wpdb->prefix . 'ros_dishes', [ 'id' => $id ] );
        wp_redirect( admin_url( 'admin.php?page=ros-menu&cat=' . $cat ) );
        exit;
    }

    public function save_table() {
        check_admin_referer( 'ros_table' );
        global $wpdb;
        $id    = intval( $_POST['table_id'] ?? 0 );
        $name  = sanitize_text_field( $_POST['name'] ?? '' );
        $seats = intval( $_POST['seats'] ?? 4 );
        $shape = sanitize_text_field( $_POST['shape'] ?? 'rect_4' );
        $sort  = intval( $_POST['sort_order'] ?? 0 );
        $data  = [ 'name' => $name, 'seats' => $seats, 'shape' => $shape, 'sort_order' => $sort ];
        if ( $id ) {
            $wpdb->update( $wpdb->prefix . 'ros_tables', $data, [ 'id' => $id ] );
        } else {
            $wpdb->insert( $wpdb->prefix . 'ros_tables', $data );
        }
        wp_redirect( admin_url( 'admin.php?page=ros-tables&saved=1' ) );
        exit;
    }

    public function delete_table() {
        check_admin_referer( 'ros_del_table' );
        global $wpdb;
        $id = intval( $_GET['id'] ?? 0 );
        $wpdb->delete( $wpdb->prefix . 'ros_tables', [ 'id' => $id ] );
        wp_redirect( admin_url( 'admin.php?page=ros-tables' ) );
        exit;
    }
}
