<?php

require_once DOL_DOCUMENT_ROOT . '/custom/eventwizard/class/eventlocation.class.php';

class BookingAgendaHelper
{
    public $db;
    public function __construct($db)
    {
        $this->db = $db;
    }

    function getEventdayDates($year, $month, $day)
    {
        $dates = [];
        $eventday = $year . '-';
        $eventday .= (int) $month < 10 ? '0' : '';
        $eventday .= $month . '-';
        $eventday .= (int) $day < 10 ? '0' : '';
        $eventday .= $day;
        $eventday = str_replace("-00", "-0", $eventday);
        $dates['eventday'] = $eventday;
        $dates['eventdayprint'] = date("Y M d", strtotime($eventday));
        $dates['from'] = $eventday . ' 00:00:00';
        $dates['to'] = $eventday . ' 23:59:59';
        return $dates;
    }

    /* function getMaxNumFromEVENT($eventarray){
        foreach($eventarray as $event){
            return $event['max_num'];
        }
    } */

    function getsumReservation($eventsArray, $eventday, $hourText)
    {
        $count = 0;
        $actionCommIds = [];
        $from = strtotime($eventday . ' ' . $hourText . ':00:00');
        $to = strtotime($eventday . ' ' . $hourText . ':59:59');
        foreach ($eventsArray as $event) {
            $event_from = strtotime($event['datep']);
            $event_to = strtotime($event['datep2']);
            if (($from <= $event_from && $to >= $event_from) || $from >= $event_from && $to + 1 <= $event_to) {
                $count = $count + (int)$event['participants'];
                $actionCommIds[] = (int)$event['actioncomm_id'];
            }
        }
        $array['count'] = $count > 0 ? $count : '-';
        $array['ids'] = implode(',', $actionCommIds);
        return $array;
    }

    function getsumOccupied($eventsArray, $eventday, $hourText)
    {
        $count = 0;
        $actionCommIds = [];
        $from = strtotime($eventday . ' ' . $hourText . ':00:00');
        $to = strtotime($eventday . ' ' . $hourText . ':59:59');
        foreach ($eventsArray as $event) {
            $event_from = strtotime($event['datep']);
            $event_to = strtotime($event['datep2']);
            if ($from == $event_to) {
                $count = $count + (int)$event['participants'];
                $actionCommIds[] = (int)$event['actioncomm_id'];
            }
            if (($from <= $event_from && $to >= $event_from) || $from >= $event_from && $to + 1 <= $event_to) {
                $count = $count + (int)$event['participants'];
                $actionCommIds[] = (int)$event['actioncomm_id'];
            }
        }
        $array['count'] = $count > 0 ? $count : '-';
        $array['ids'] = implode(',', $actionCommIds);
        return $array;
    }

    function getsumService($eventsArray, $eventday, $hourText)
    {
        $count = 0;
        $actionCommIds = [];
        $from = strtotime($eventday . ' ' . $hourText . ':00:00');
        foreach ($eventsArray as $event) {
            $event_to = strtotime($event['datep2']);
            if ($from == $event_to) {
                $count = $count + (int)$event['participants'];
                $actionCommIds[] = (int)$event['actioncomm_id'];
            }
        }
        $array['count'] = $count > 0 ? $count : '-';
        $array['ids'] = implode(',', $actionCommIds);
        return $array;
    }

    function getlocations()
    {
        $locationArray = [];
        $eventwizardLocationsObj = new EventLocation($this->db);
        $result = $eventwizardLocationsObj->fetchAll('ASC', 'label', 0, 0);
        if (count($result) > 0) {
            foreach ($result as $location) {
                $locationArray[$location->id] = $location->label;
            }
        }
        return $locationArray;
    }

    function getLocationLabel($event)
    {
        foreach ($event as $eventDetail) {
            return $eventDetail['fk_elventlocation_departure'];
        }
    }

    function getOneColumnFromTable($sql, $array, $column)
    {
        $eventData = $this->db->query($sql);
        if ($this->db->num_rows($eventData) > 0) {
            while ($row = $this->db->fetch_object($eventData)) {
                $array[$row->fk_elventlocation_departure][$row->$column] = (array) $row;
            }
        }
        return $array;
    }

    function getBGColor($rowcolorCounter)
    {
        return $rowcolorCounter % 2 ? 'white' : 'Gainsboro';
    }

    function getHourText($hour)
    {
        return $hour < 10 ? '0' . $hour : $hour;
    }

    private function getActionCommID($event)
    {
        return array_key_first($event);
    }

    function showTable($eventdayDates, $selectedEvent)
    {
        global $langs, $db;
        //$this = new this($db);
        $k = 0;
        $dailyStartTime = 9;
        $dailyEndTime = 21;
        $eventsArray = [];
        $daysql = "SELECT 
                    ed.rowid as eventdetail_id, 
                    ed.label as eventdetail_label,
                    ac.id as actioncomm_id,
                    ac.datep,
                    ac.datep2,
                    ac.durationp,
                    ace.buffer,
                    ace.max_num,
                    ace.participants,
                    ed.fk_elventlocation_departure
                FROM llx_eventwizard_eventdetails as ed 
                INNER JOIN llx_actioncomm as ac ON ac.fk_element = ed.rowid
                INNER JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
                WHERE ed.type IN (3,4)
                AND ac.code = 'AC_EVENT'
                AND ac.datep BETWEEN '{$eventdayDates['from']}' AND '{$eventdayDates['to']}'
                AND ace.participants IS NOT NULL
                ORDER BY ac.id DESC";
        //print $daysql;
        $eventsArray = $this->getOneColumnFromTable($daysql, $eventsArray, 'actioncomm_id');
        $locationArray = $this->getlocations();
        print '<table style="width:100%">';
        print '<tr class="firstcolumn">
        <td style="width:15%">' . $langs->trans('Location') . '</td>
        <td style="width:7%">' . $langs->trans('Status') . '</td>';
        for ($i = 9; $i < 21; $i++) {
            $hourText = $i < 10 ? '0' . $i : $i;
            print '<td>' . $hourText . '</td>';
            $k++;
        }
        $k = $k + 2;
        print '<tr class="elvalaszto"><td colspan="' . $k . '"></td></tr>';
        print '</tr>';

        foreach ($eventsArray as $event) {
            print '<tr class="trheight">
            <td class="firstcolumn"></td>
            <td class="center">' . $langs->trans('Reserved') . '</td>';
            $rowcolorCounter = 0;
            print '<br>';
            for ($i = $dailyStartTime; $i < $dailyEndTime; $i++) {
                $backgroundColor = $this->getBGColor($rowcolorCounter);
                $hourText = $this->getHourText($i);
                $ReservationArray = $this->getsumReservation($event, $eventdayDates['eventday'], $hourText);
                $sumNumber = $ReservationArray['count'];
                $cursor = $sumNumber > 0 ? 'pointer' : '';
                print '<td class="center" style="background-color: ' . $backgroundColor . '; cursor:' . $cursor . ';" onclick="ShoMeTheEventDeatils(\'' . (string)$ReservationArray['ids'] . '\')">' . $sumNumber . '</td>';
                $rowcolorCounter++;
            }
            print '</tr>';
            print '<tr class="trheight foglaltsag">
            <td class="location firstcolumn">' . $locationArray[$this->getLocationLabel($event)] . '</td>
            <td class="center">' . $langs->trans('InUse') . '</td>';
            $rowcolorCounter = 0;
            for ($i = $dailyStartTime; $i < $dailyEndTime; $i++) {
                $backgroundColor = $this->getBGColor($rowcolorCounter);
                $hourText = $this->getHourText($i);
                $OccupiedArray = $this->getsumOccupied($event, $eventdayDates['eventday'], $hourText);
                $sumNumber = $OccupiedArray['count'];
                $cursor = $sumNumber > 0 ? 'pointer' : '';
                print '<td class="center" style="background-color: ' . $backgroundColor . '; cursor:' . $cursor . ';" onclick="ShoMeTheEventDeatils(\'' . (string)$OccupiedArray['ids'] . '\')">' . $sumNumber . '</td>';
                $rowcolorCounter++;
            }
            print '</tr>';
            print '<tr class="trheight">
            <td class="firstcolumn"></td>
            <td class="center">' . $langs->trans('InService') . '</td>';
            $rowcolorCounter = 0;
            for ($i = $dailyStartTime; $i < $dailyEndTime; $i++) {
                $backgroundColor = $this->getBGColor($rowcolorCounter);
                $hourText = $this->getHourText($i);
                $ServiceArray = $this->getsumService($event, $eventdayDates['eventday'], $hourText);
                $sumNumber = $ServiceArray['count'];
                $cursor = $sumNumber > 0 ? 'pointer' : '';
                print '<td class="center" style="background-color: ' . $backgroundColor . '; cursor:' . $cursor . ';" onclick="ShoMeTheEventDeatils(\'' . (string)$ServiceArray['ids'] . '\')">' . $sumNumber . '</td>';
                $rowcolorCounter++;
            }
            print '</tr>';
            print '<tr class="elvalaszto"><td colspan="' . $k . '"></td></tr>';
        }
        print '</table>';
    }

    public function getSelectedEvents($event)
    {
        global $db;
        $eventsArray = explode(',', $event);
        $everything = [];
        foreach ($eventsArray as $eventdetail) {
            $sql = "SELECT ac.id, ac.datep, ac.datep2, ac.durationp, bh.fk_facture, bh.invoice_number
            FROM llx_actioncomm as ac 
            INNER JOIN llx_booking_bookinghistory as bh ON bh.fk_event = ac.id
            WHERE ac.id = {$eventdetail} ORDER BY fk_facture DESC";
            //print $sql;
            //exit;
            $result = $db->query($sql);
            if ($db->num_rows($result) > 0) {
                print '<table><thead><tr class="firstcolumn">
                    <th>Facture</th>
                    <th>Time Range</th>
                </tr></thead><tbody>';
                $rowcolorCounter = 0;
                while ($row = $db->fetch_object($result)) {
                    print '<tr class="center" style="height:60px; background-color: ' . $this->getBGColor($rowcolorCounter) . ';">
                        <td class="" style="padding:20px;">' . $row->invoice_number . '</td>
                        <td style="padding:20px;">' . $row->datep . ' - ' . $row->datep2 . '</td>
                    </tr>';
                    $rowcolorCounter++;
                }
                print '</tbody></table>';
            }
        }
    }
}
