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

class EMPR_Attendance {

    public static function query( $args = array() ) {
        global $wpdb;
        $where  = array( '1 = %d' );
        $params = array( 1 );

        if ( ! empty( $args['user_id'] ) ) { $where[] = 'a.user_id = %d';         $params[] = (int) $args['user_id']; }
        if ( ! empty( $args['start'] ) )   { $where[] = 'DATE(a.clock_in) >= %s'; $params[] = $args['start']; }
        if ( ! empty( $args['end'] ) )     { $where[] = 'DATE(a.clock_in) <= %s'; $params[] = $args['end']; }
        if ( ! empty( $args['status'] ) )  { $where[] = 'a.status = %s';          $params[] = $args['status']; }

        $limit = isset( $args['limit'] ) ? 'LIMIT ' . (int) $args['limit'] : 'LIMIT 200';

        $sql = "SELECT a.*, u.display_name
                FROM {$wpdb->prefix}emr_attendance a
                INNER JOIN {$wpdb->users} u ON u.ID = a.user_id
                WHERE " . implode( ' AND ', $where ) . "
                ORDER BY a.clock_in DESC $limit";

        $results = $wpdb->get_results( $wpdb->prepare( $sql, ...$params ) );
        return $results ? $results : array();
    }

    public static function total_hours( $user_id, $start, $end ) {
        global $wpdb;
        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT clock_in, clock_out, break_minutes FROM {$wpdb->prefix}emr_attendance WHERE user_id=%d AND status='completed' AND DATE(clock_in)>=%s AND DATE(clock_in)<=%s",
            (int) $user_id, $start, $end
        ) );
        $total = 0.0;
        if ( $rows ) {
            foreach ( $rows as $r ) {
                if ( $r->clock_in && $r->clock_out ) {
                    $diff   = ( strtotime( $r->clock_out ) - strtotime( $r->clock_in ) ) / 3600;
                    $total += max( 0.0, $diff - ( (int) $r->break_minutes / 60 ) );
                }
            }
        }
        return round( $total, 2 );
    }
}
