<?php

class Calendar_model extends MY_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('invoice_model');
    }

    public function get_calendar_events($searchType = 'all', $role = null)
    {
        $searchType = !empty($searchType) ? $searchType : 'all';
        $events = array();

        if ((int) $role === 1 && config_item('payments_on_calendar') == 'on' && $this->matches_filter($searchType, 'payments')) {
            $payments_info = $this->invoice_model->all_payments_client_wise();
            if (!empty($payments_info)) {
                foreach ($payments_info as $v_payments) {
                    $this->add_event(
                        $events,
                        $v_payments->name . " (" . client_currency($v_payments->client_id) . $v_payments->amount . ")",
                        $v_payments->payment_date,
                        $v_payments->payment_date,
                        config_item('payments_color'),
                        $this->calendar_url('admin/invoice/manage_invoice/payments_details/' . $v_payments->payments_id),
                        'payments'
                    );
                }
            }
        }

        if (config_item('invoice_on_calendar') == 'on' && $this->matches_filter($searchType, 'invoices')) {
            $invoice_info = $this->get_permission('tbl_invoices');
            if (!empty($invoice_info)) {
                foreach ($invoice_info as $v_invoice) {
                    $this->add_event(
                        $events,
                        $v_invoice->reference_no,
                        $v_invoice->due_date,
                        $v_invoice->due_date,
                        config_item('invoice_color'),
                        $this->calendar_url('admin/invoice/manage_invoice/invoice_details/' . $v_invoice->invoices_id),
                        'invoices'
                    );
                }
            }
        }

        if (config_item('estimate_on_calendar') == 'on' && $this->matches_filter($searchType, 'estimates')) {
            $estimates_info = $this->get_permission('tbl_estimates');
            if (!empty($estimates_info)) {
                foreach ($estimates_info as $v_estimates) {
                    $this->add_event(
                        $events,
                        $v_estimates->reference_no,
                        $v_estimates->due_date,
                        $v_estimates->due_date,
                        config_item('estimate_color'),
                        $this->calendar_url('admin/estimates/create/estimates_details/' . $v_estimates->estimates_id),
                        'estimates'
                    );
                }
            }
        }

        if (config_item('project_on_calendar') == 'on' && ($this->matches_filter($searchType, 'projects') || $this->matches_filter($searchType, 'milestones'))) {
            $project_info = $this->get_permission('tbl_project');
            if (!empty($project_info)) {
                foreach ($project_info as $v_project) {
                    if ($this->matches_filter($searchType, 'projects')) {
                        $this->add_event(
                            $events,
                            $v_project->project_name,
                            $v_project->end_date,
                            $v_project->end_date,
                            config_item('project_color'),
                            $this->calendar_url('admin/projects/project_details/' . $v_project->project_id),
                            'projects'
                        );
                    }

                    if (config_item('milestone_on_calendar') == 'on' && $this->matches_filter($searchType, 'milestones')) {
                        $milestone_info = $this->db->where(array('project_id' => $v_project->project_id))->get('tbl_milestones')->result();
                        if (!empty($milestone_info)) {
                            foreach ($milestone_info as $v_milestone) {
                                $this->add_event(
                                    $events,
                                    $v_milestone->milestone_name,
                                    $v_milestone->end_date,
                                    $v_milestone->end_date,
                                    config_item('milestone_color'),
                                    $this->calendar_url('admin/projects/project_details/' . $v_project->project_id . '/milestones'),
                                    'milestones'
                                );
                            }
                        }
                    }
                }
            }
        }

        if (config_item('tasks_on_calendar') == 'on' && $this->matches_filter($searchType, 'tasks')) {
            $task_info = $this->get_permission('tbl_task');
            if (!empty($task_info)) {
                foreach ($task_info as $v_task) {
                    $this->add_event(
                        $events,
                        $v_task->task_name,
                        $v_task->due_date,
                        $v_task->due_date,
                        config_item('tasks_color'),
                        $this->calendar_url('admin/tasks/details/' . $v_task->task_id),
                        'tasks'
                    );
                }
            }
        }

        if (config_item('bugs_on_calendar') == 'on' && $this->matches_filter($searchType, 'bugs')) {
            $bug_info = $this->get_permission('tbl_bug');
            if (!empty($bug_info)) {
                foreach ($bug_info as $v_bug) {
                    $this->add_event(
                        $events,
                        $v_bug->bug_title,
                        $v_bug->created_time,
                        $v_bug->created_time,
                        config_item('bugs_color'),
                        $this->calendar_url('admin/bugs/view_bug_details/' . $v_bug->bug_id),
                        'bugs'
                    );
                }
            }
        }

        if (config_item('opportunities_on_calendar') == 'on' && $this->matches_filter($searchType, 'opportunities')) {
            $opportunity_info = $this->get_permission('tbl_opportunities');
            if (!empty($opportunity_info)) {
                foreach ($opportunity_info as $v_opportunity) {
                    $opportunity_base_url = 'admin/opportunities/opportunity_details/' . $v_opportunity->opportunities_id;

                    $this->add_event(
                        $events,
                        $v_opportunity->opportunity_name,
                        $v_opportunity->close_date,
                        $v_opportunity->close_date,
                        config_item('opportunities_color'),
                        $this->calendar_url($opportunity_base_url),
                        'opportunities'
                    );
                    $this->add_event(
                        $events,
                        $v_opportunity->next_action,
                        $v_opportunity->next_action_date,
                        $v_opportunity->next_action_date,
                        config_item('opportunities_color'),
                        $this->calendar_url($opportunity_base_url),
                        'opportunities'
                    );

                    $opportunity_calls = $this->db->where('opportunities_id', $v_opportunity->opportunities_id)->get('tbl_calls')->result();
                    if (!empty($opportunity_calls)) {
                        foreach ($opportunity_calls as $v_o_calls) {
                            $this->add_event(
                                $events,
                                $v_o_calls->call_summary,
                                $v_o_calls->date,
                                $v_o_calls->date,
                                config_item('opportunities_color'),
                                $this->calendar_url($opportunity_base_url . '/call'),
                                'opportunities'
                            );
                        }
                    }

                    $opportunity_meetings = $this->db->where('opportunities_id', $v_opportunity->opportunities_id)->get('tbl_mettings')->result();
                    if (!empty($opportunity_meetings)) {
                        foreach ($opportunity_meetings as $v_o_meetings) {
                            $this->add_event(
                                $events,
                                $v_o_meetings->meeting_subject,
                                $v_o_meetings->start_date,
                                $v_o_meetings->end_date,
                                config_item('opportunities_color'),
                                $this->calendar_url($opportunity_base_url . '/mettings'),
                                'opportunities'
                            );
                        }
                    }
                }
            }
        }

        if (config_item('leads_on_calendar') == 'on' && $this->matches_filter($searchType, 'leads')) {
            $leads_info = $this->get_permission('tbl_leads');
            if (!empty($leads_info)) {
                foreach ($leads_info as $v_leads) {
                    $lead_base_url = 'admin/leads/leads_details/' . $v_leads->leads_id;

                    $this->add_event(
                        $events,
                        $v_leads->lead_name,
                        $v_leads->created_time,
                        $v_leads->created_time,
                        config_item('leads_color'),
                        $this->calendar_url($lead_base_url),
                        'leads'
                    );

                    $lead_calls = $this->db->where('leads_id', $v_leads->leads_id)->get('tbl_calls')->result();
                    if (!empty($lead_calls)) {
                        foreach ($lead_calls as $v_l_calls) {
                            $this->add_event(
                                $events,
                                $v_l_calls->call_summary,
                                $v_l_calls->date,
                                $v_l_calls->date,
                                config_item('leads_color'),
                                $this->calendar_url($lead_base_url . '/call'),
                                'leads'
                            );
                        }
                    }

                    $lead_meetings = $this->db->where('leads_id', $v_leads->leads_id)->get('tbl_mettings')->result();
                    if (!empty($lead_meetings)) {
                        foreach ($lead_meetings as $v_l_meetings) {
                            $this->add_event(
                                $events,
                                $v_l_meetings->meeting_subject,
                                $v_l_meetings->start_date,
                                $v_l_meetings->end_date,
                                config_item('leads_color'),
                                $this->calendar_url($lead_base_url . '/mettings'),
                                'leads'
                            );
                        }
                    }
                }
            }
        }

        if (config_item('holiday_on_calendar') == 'on' && $this->matches_filter($searchType, 'holiday')) {
            $holiday_info = $this->db->get('tbl_holiday')->result();
            if (!empty($holiday_info)) {
                foreach ($holiday_info as $v_holiday) {
                    $this->add_event(
                        $events,
                        $v_holiday->event_name,
                        $v_holiday->start_date,
                        $v_holiday->end_date,
                        $v_holiday->color,
                        $this->calendar_url('admin/holiday/index/' . $v_holiday->holiday_id),
                        'holiday'
                    );
                }
            }
        }

        if (config_item('goal_tracking_on_calendar') == 'on' && $this->matches_filter($searchType, 'goal')) {
            $all_goal_tracking = $this->get_permission('tbl_goal_tracking');
            if (!empty($all_goal_tracking)) {
                foreach ($all_goal_tracking as $v_goal_tracking) {
                    $this->add_event(
                        $events,
                        $v_goal_tracking->subject,
                        $v_goal_tracking->end_date,
                        $v_goal_tracking->end_date,
                        config_item('goal_tracking_color'),
                        $this->calendar_url('admin/goal_tracking/goal_details/' . $v_goal_tracking->goal_tracking_id),
                        'goal'
                    );
                }
            }
        }

        if (config_item('absent_on_calendar') == 'on' && $this->matches_filter($searchType, 'absent')) {
            $absent_info = $this->db->query("SELECT tbl_account_details.fullname,tbl_account_details.user_id, tbl_attendance.date_in
                 FROM tbl_attendance
                 LEFT JOIN tbl_account_details ON tbl_attendance.user_id = tbl_account_details.user_id
                 WHERE tbl_attendance.attendance_status = 0")->result();
            if (!empty($absent_info)) {
                foreach ($absent_info as $v_absent) {
                    $this->add_event(
                        $events,
                        $v_absent->fullname,
                        $v_absent->date_in,
                        $v_absent->date_in,
                        config_item('absent_color'),
                        $this->calendar_url('admin/user/user_details/' . $v_absent->user_id),
                        'absent'
                    );
                }
            }
        }

        if (config_item('on_leave_on_calendar') == 'on' && $this->matches_filter($searchType, 'on_leave')) {
            $leave_info = $this->db->query("SELECT tbl_account_details.fullname, tbl_account_details.user_id, tbl_attendance.date_in
                 FROM tbl_attendance
                 LEFT JOIN tbl_account_details ON tbl_attendance.user_id = tbl_account_details.user_id
                 WHERE tbl_attendance.attendance_status = 3")->result();
            if (!empty($leave_info)) {
                foreach ($leave_info as $v_leave) {
                    $this->add_event(
                        $events,
                        $v_leave->fullname,
                        $v_leave->date_in,
                        $v_leave->date_in,
                        config_item('on_leave_color'),
                        $this->calendar_url('admin/user/user_details/' . $v_leave->user_id),
                        'on_leave'
                    );
                }
            }
        }

        return $events;
    }

    protected function add_event(&$events, $title, $start, $end, $color, $url, $type = '')
    {
        $start = $this->normalize_calendar_date($start);
        $end = $this->normalize_calendar_date($end);

        if (empty($start)) {
            return;
        }

        $events[] = array(
            'title' => clear_textarea_breaks((string) $title),
            'start' => $start,
            'end' => !empty($end) ? $end : $start,
            'color' => $color,
            'url' => $url,
            'type' => $type,
        );
    }

    protected function normalize_calendar_date($value)
    {
        if ($value === null || $value === '') {
            return null;
        }

        $timestamp = is_numeric($value) ? (int) $value : safe_strtotime($value);
        if (empty($timestamp)) {
            return null;
        }

        return date('Y-m-d', $timestamp);
    }

    protected function calendar_url($path)
    {
        return base_url() . ltrim($path, '/');
    }

    protected function matches_filter($searchType, $type)
    {
        return $searchType === 'all' || $searchType === $type;
    }
}
