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

class EMPR_Roles {

    /**
     * Leave types a casual employee may not request. Casuals accrue no paid
     * leave — EMPR_LeaveBalance skips accrual for them entirely — so allowing
     * these through only fills the approval queue with unentitled requests.
     */
    const CASUAL_BLOCKED_LEAVE = array( 'annual', 'sick' );

    public static function init() {
        $admin = get_role( 'administrator' );
        if ( $admin ) {
            $caps = array(
                'emr_manage_roster','emr_assign_shifts','emr_approve_leave',
                'emr_view_all_staff','emr_view_attendance','emr_edit_attendance',
                'emr_view_reports','emr_manage_settings','emr_view_own_shifts',
                'emr_clock_in_out','emr_submit_leave','emr_set_availability',
            );
            foreach ( $caps as $cap ) { $admin->add_cap( $cap ); }
        }
    }

    public static function create_roles() {
        remove_role( 'emr_employee' );
        add_role( 'emr_employee', __( 'Employee', 'employee-roster' ), array(
            'read'                 => true,
            'emr_view_own_shifts'  => true,
            'emr_clock_in_out'     => true,
            'emr_submit_leave'     => true,
            'emr_set_availability' => true,
        ) );
    }

    /** True for WP administrators — can perform management actions. */
    public static function is_manager( $user_id = 0 ) {
        $uid = $user_id ? $user_id : get_current_user_id();
        return user_can( $uid, 'manage_options' );
    }

    /** True for WP administrators — can view roster-wide data. */
    public static function can_view_all( $user_id = 0 ) {
        $uid = $user_id ? $user_id : get_current_user_id();
        return self::is_manager( $uid );
    }

    public static function is_admin( $user_id = 0 ) {
        $uid = $user_id ? $user_id : get_current_user_id();
        return user_can( $uid, 'manage_options' );
    }

    /**
     * Resolve a user's job type, defaulting to 'fulltime' for managers and
     * supervisors and 'casual' for everyone else. Mirrors the default rule in
     * EMPR_LeaveBalance::job_type() — supervisors are salaried staff and must
     * not fall through to 'casual'.
     */
    public static function job_type( $user_id = 0 ) {
        $uid = $user_id ? (int) $user_id : get_current_user_id();
        $jt  = get_user_meta( $uid, 'empr_job_type', true );
        if ( $jt ) return $jt;
        $user  = get_userdata( $uid );
        $roles = $user ? (array) $user->roles : array();
        if ( in_array( 'emr_manager', $roles, true ) || in_array( 'emr_supervisor', $roles, true ) ) {
            return 'fulltime';
        }
        return 'casual';
    }

    /** True when the user is casual and so cannot request paid leave. */
    public static function is_casual( $user_id = 0 ) {
        return self::job_type( $user_id ) === 'casual';
    }

}
