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

class EMPR_Availability {

    public static function for_user( $user_id ) {
        global $wpdb;
        $results = $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}emr_availability WHERE user_id=%d ORDER BY day_of_week ASC",
            (int) $user_id
        ) );
        return $results ? $results : array();
    }

    public static function save( $user_id, $slots ) {
        global $wpdb;
        $t = EMPR_DB::table( 'availability' );
        $wpdb->delete( $t, array( 'user_id' => (int) $user_id ) );
        foreach ( $slots as $slot ) {
            $wpdb->insert( $t, array(
                'user_id'      => (int) $user_id,
                'day_of_week'  => (int)    ( isset( $slot['day_of_week'] )  ? $slot['day_of_week']  : 0 ),
                'start_time'   => sanitize_text_field( isset( $slot['start_time'] ) ? $slot['start_time'] : '09:00:00' ),
                'end_time'     => sanitize_text_field( isset( $slot['end_time'] )   ? $slot['end_time']   : '17:00:00' ),
                'is_available' => (int)    ( isset( $slot['is_available'] ) ? $slot['is_available'] : 1 ),
                'created_at'   => current_time( 'mysql' ),
            ) );
        }
        return true;
    }

    public static function all_staff() {
        $users  = EMPR_Settings::get_roster_users();
        $result = array();
        foreach ( $users as $u ) {
            $result[] = array(
                'user_id'      => $u->ID,
                'display_name' => $u->display_name,
                'availability' => self::for_user( $u->ID ),
            );
        }
        return $result;
    }
}
