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

class EMPR_Settings {

    public static function get( $key, $default = '' ) {
        return get_option( 'empr_' . $key, $default );
    }

    public static function set( $key, $value ) {
        return update_option( 'empr_' . $key, $value );
    }

    public static function departments() {
        $raw    = self::get( 'departments', '' );
        $result = array_values( array_filter( array_map( 'trim', explode( "\n", $raw ) ) ) );
        return $result ?: array( 'General Department' );
    }

    public static function locations() {
        $raw    = self::get( 'locations', '' );
        $result = array();

        if ( ! empty( $raw ) ) {
            $decoded = json_decode( $raw, true );
            if ( is_array( $decoded ) ) {
                $result = $decoded; // may be an empty array — fallback applied below
            } else {
                // Backward-compat: plain newline-separated strings (pre-1.6.0)
                $palette = array( '#2563EB', '#16A34A', '#DC2626', '#D97706', '#7C3AED', '#0891B2', '#BE185D', '#374151' );
                foreach ( array_values( array_filter( array_map( 'trim', explode( "\n", $raw ) ) ) ) as $i => $name ) {
                    $result[] = array( 'name' => $name, 'color' => $palette[ $i % count( $palette ) ] );
                }
            }
        }

        return $result ?: array( array( 'name' => 'Main Location', 'color' => '#2563EB' ) );
    }

    public static function company_name() {
        return self::get( 'company_name', get_bloginfo( 'name' ) );
    }

    public static function primary_color() {
        return self::get( 'primary_color', '#2563EB' );
    }

    /**
     * Returns the configured weekly hour limits per job type.
     * Casual returns null (no fixed limit).
     */
    public static function job_type_hours() {
        return array(
            'fulltime' => (int) self::get( 'hours_fulltime', 38 ),
            'parttime' => (int) self::get( 'hours_parttime', 24 ),
            'casual'   => null,
        );
    }

    /**
     * Returns the role__in array for roster staff queries,
     * including 'administrator' when the "include all admins" setting is on.
     */
    public static function roster_role_in() {
        $roles = array( 'emr_employee', 'emr_supervisor', 'emr_manager' );
        if ( self::get( 'admin_include_all', '0' ) === '1' ) {
            $roles[] = 'administrator';
        }
        return $roles;
    }

    /**
     * Returns IDs of all WordPress administrators who have personally opted in
     * to the roster via empr_admin_include_self user meta.
     * Returns an empty array when "include all" is active — those admins are
     * already pulled in via roster_role_in().
     */
    public static function admin_opted_in_ids() {
        if ( self::get( 'admin_include_all', '0' ) === '1' ) return array();
        $users = get_users( array(
            'role'       => 'administrator',
            'meta_key'   => 'empr_admin_include_self',
            'meta_value' => '1',
            'fields'     => 'ID',
            'number'     => -1,
        ) );
        return array_map( 'intval', (array) $users );
    }

    /**
     * Drop-in replacement for get_users() for roster staff lists.
     * Handles both admin-inclusion modes transparently.
     *
     * @param array $args  Same args as get_users(); do NOT pass role__in.
     */
    public static function get_roster_users( $args = array() ) {
        if ( ! isset( $args['meta_query'] ) ) {
            $args['meta_query'] = array(
                'relation' => 'OR',
                array( 'key' => 'empr_deactivated', 'compare' => 'NOT EXISTS' ),
                array( 'key' => 'empr_deactivated', 'value'   => '1', 'compare' => '!=' ),
            );
        }
        $args['role__in'] = self::roster_role_in();
        $users            = get_users( $args );
        $opted_ids        = self::admin_opted_in_ids();
        if ( empty( $opted_ids ) ) return $users;

        // Find which opted-in admins are not already in the result.
        $fields = isset( $args['fields'] ) ? $args['fields'] : null;
        if ( is_array( $fields ) ) {
            $existing_ids = array_map( 'intval', array_column( (array) $users, 'ID' ) );
        } elseif ( is_string( $fields ) && strtolower( $fields ) === 'id' ) {
            $existing_ids = array_map( 'intval', (array) $users );
        } else {
            $existing_ids = array_map( function ( $u ) { return (int) $u->ID; }, (array) $users );
        }

        $missing_ids = array_values( array_diff( $opted_ids, $existing_ids ) );
        if ( empty( $missing_ids ) ) return $users;

        $extra_args = array( 'include' => $missing_ids );
        if ( isset( $args['fields'] ) ) $extra_args['fields'] = $args['fields'];
        return array_merge( $users, get_users( $extra_args ) );
    }

    public static function for_js() {
        $settings = array(
            'companyName'            => self::company_name(),
            'primaryColor'           => self::primary_color(),
            'departments'            => self::departments(),
            'locations'              => self::locations(),
            'weekStart'              => (int) self::get( 'week_start', 1 ),
            'allowSelfClock'         => ( self::get( 'allow_self_clock', '1' ) === '1' ),
            'jobTypeHours'           => self::job_type_hours(),
            'adminIncludeSelf'       => ( get_user_meta( get_current_user_id(), 'empr_admin_include_self', true ) === '1'
                                          || self::get( 'admin_include_all', '0' ) === '1' ),
            'adminIncludeAll'        => ( self::get( 'admin_include_all',  '0' ) === '1' ),
            'taxRate'                => (float) self::get( 'tax_rate', 0 ),
            'dailyBudget'            => (float) self::get( 'daily_budget', 0 ),
            // Indexed by JS Date.getDay(): [0]=Sunday … [6]=Saturday.
            'dailyBudgetByDay'       => array(
                (float) self::get( 'daily_budget_sun', 0 ),
                (float) self::get( 'daily_budget_mon', 0 ),
                (float) self::get( 'daily_budget_tue', 0 ),
                (float) self::get( 'daily_budget_wed', 0 ),
                (float) self::get( 'daily_budget_thu', 0 ),
                (float) self::get( 'daily_budget_fri', 0 ),
                (float) self::get( 'daily_budget_sat', 0 ),
            ),
            'notificationsEnabled'   => ( self::get( 'notifications_enabled', '0' ) === '1' ),
            'saturdayRate'           => (float) self::get( 'saturday_rate', 25 ),
            'sundayRate'             => (float) self::get( 'sunday_rate',   50 ),
        );

        return $settings;
    }
}
