<?php

namespace Velis\User\Duty;

use Velis\User\Absence\Report as ReportModel;
use Velis\Filter;
use Velis\User\Duty;

/**
 * Duty report
 * @author Bartosz Izdebski <bartosz.izdebski@velis.pl>
 */
class Report extends ReportModel
{

    /**
     * Returns absences time stats
     */
    public function getTimeStats()
    {
        $sql = "
            SELECT 
                    v.user_id,
                CASE WHEN v.minutes_left < 0 
                    THEN 
                            ('-' || to_char((abs(v.minutes_left) || 'minutes')::INTERVAL, 'HH24:MI'))
                    ELSE
                            to_char((v.minutes_left || 'minutes')::INTERVAL, 'HH24:MI')
                END AS hours_left,
                v.working_hours_count,
                to_char((v.sum || 'minutes')::interval, 'HH24:MI') as sum,
                to_char((v.emergency_sum || 'minutes')::interval, 'HH24:MI') as emergency_sum
            FROM (
              SELECT t.user_id, 
                     (t.working_hours_count * 60) - (sum(EXTRACT (EPOCH FROM ua.date_to) - EXTRACT (EPOCH FROM ua.date_from)) / 60) as minutes_left, 
                     t.working_hours_count,
                     (sum(CASE WHEN ua.is_emergency = '0' 
                            THEN 
                                EXTRACT (EPOCH FROM ua.date_to)-EXTRACT (EPOCH FROM ua.date_from)
                            ELSE 
                                0
                            END) / 60)::text as sum,
                     (sum(CASE WHEN ua.is_emergency = '1' 
                            THEN 
                                EXTRACT (EPOCH FROM ua.date_to)-EXTRACT (EPOCH FROM ua.date_from)
                            ELSE 
                                0
                            END) / 60)::text as emergency_sum
                FROM (
                        SELECT u.user_id, (u.job_time*sum(tsm.working_hours_count)) as working_hours_count
                          FROM acl.user_tab u
                          JOIN app.ticket_schedule_month_tab tsm ON tsm.month BETWEEN date_trunc('month', :date_from::date) AND date_trunc('month', :date_to::date)
                      GROUP BY u.user_id, u.job_time) t
           LEFT JOIN acl.user_absence_tab ua USING (user_id)";

        if ($this->_params['building_complex_id']) {
            $sql .= " JOIN app.building_complex_shift_tab bcs ON bcs.building_complex_shift_id = ua.building_complex_shift_id AND bcs.building_complex_id = :building_complex_id";
            $params['building_complex_id'] = $this->_params['building_complex_id'];
        }

        $sql .= " WHERE date_trunc('day', date_from) >= :date_from
                 AND date_trunc('day', date_from) <= :date_to
            GROUP BY t.user_id, t.working_hours_count
               ) AS v";

        $params['date_from'] = $this->_params['start_date'];
        $params['date_to'] = $this->_params['end_date'];

        return self::$_db->getAll($sql, $params, 'user_id');
    }


    /**
     * Prepares report data
     * @param array $params
     * @return array
     */
    public function prepare(array $params = array())
    {
        $outputData = $this->_dates;

        $absenceParams = array(
            'archive' => 1,
            'date_from' => $this->_params['start_date'],
            'date_to' => $this->_params['end_date'],
        );

        $absences = Duty::listAll($absenceParams);

        foreach ($absences as $absence) {
            $date = $absence['date_from'];

            $shiftId = $absence['building_complex_shift_id'] ?: 'Other';
            $outputData[date("Y", strtotime($date))][date("m", strtotime($date))][date("Y-m-d", strtotime($date))][$absence['user_id']][$shiftId] = $absence;

            $this->_users[$absence['user_id']] = $absence['user_id'];

            $date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
        }
        $outputData['timeStats'] = $this->getTimeStats();
        return $outputData;
    }
}
