<?php

namespace App\Controllers;

use App\Models\ScriptModel;
use App\Models\LeadModel;
use App\Models\AdminModel;

class Reports extends BaseController
{
    public function initController(
        \CodeIgniter\HTTP\RequestInterface $request,
        \CodeIgniter\HTTP\ResponseInterface $response,
        \Psr\Log\LoggerInterface $logger
    ) {
        parent::initController($request, $response, $logger);

        if (!is_numeric(session()->get('user_type'))) {
            redirect()->to(base_url('login/index'))->send();
            exit;
        }

        $this->ScriptModel = new ScriptModel();
        $this->LeadModel   = new LeadModel();
        $this->AdminModel  = new AdminModel();
    }

    public function activity_report()
    {
        
        $data['active'] = "reports";
        $lead_list = $this->ScriptModel->get_total_leads();
        $final_data = [];

        if (empty($lead_list) === FALSE) {
            foreach ($lead_list as $key) {
                $final_data[date('d-m-Y', strtotime($key->created_at))][$key->user_id]['user_id'] = $key->user_id;
                if (empty($final_data[date('d-m-Y', strtotime($key->created_at))][$key->user_id]['total_lead']) === TRUE) {
                    $final_data[date('d-m-Y', strtotime($key->created_at))][$key->user_id]['total_lead'] = 0;
                }
                $final_data[date('d-m-Y', strtotime($key->created_at))][$key->user_id]['total_lead']++;
                $activity = $this->ScriptModel->lead_activity_by_id($key->id);
                $opp = $this->ScriptModel->lead_opportunity($key->id);
                $activity_data = [];
                if (empty($opp) === FALSE) {
                    $activity_data[$opp['opportunity']] = $opp['total']++;
                }
                if (empty($activity) === FALSE) {
                    foreach ($activity as $val) {
                        $activity_data[$val['activity_type']] = $val['total']++;
                    }
                }
                $final_data[date('d-m-Y', strtotime($key->created_at))][$key->user_id]['activity_type'] = $activity_data;
            }
        }

        $data['report_data'] = $final_data;
        return view('header', $data) . view('activity_report', $data) . view('footer', $data);
    }

    public function sales_report()
    {
       
       
        $sales = $this->ScriptModel->get_sales_leads();
        $final_data = [];

        if (empty($sales) === FALSE) {
            foreach ($sales as $key) {
                $data = [
                    'user_id'      => $key->user_id,
                    'product'      => $key->product,
                    'sales_status' => $key->sales_status,
                    'university'   => $key->university,
                ];
                $lead_details = $this->LeadModel->get_lead_by_id($key->lead_id);
                if (empty($lead_details['lead_source']) === FALSE) {
                    $data['lead_source'] = $lead_details['lead_source'];
                } else {
                    $data['lead_source'] = NULL;
                }
                $final_data[$key->sales_date][$key->user_id][] = $data;
            }
        }

        $data['report_data'] = $final_data;
        $data['active'] = "reports";
       
        return view('header', $data) . view('sales_report', $data) . view('footer', $data);
    }

    public function export_center_report()
    {
        $userArray = $this->AdminModel->get_all_centers(0, 0);
        $rowArray  = [];
        $index     = 0;

        if (isset($_GET['year']) && $_GET['year'] != '') {
            $year = $_GET['year'];
        } else {
            $year = 'A 18-19';
        }

        foreach ($userArray as $row) {
            $studentCount       = get_total_student($row['uid'], $year);
            $total_enrolled     = get_total_enrolled_student($row['uid'], $year);
            $total_submited     = get_total_submited_form($row['uid'], $year);
            $uploaded_form      = get_center_last_uploaded($row['uid'], $year);
            $studentReRegCount  = get_re_reg_total_student($row['uid'], $year);
            $re_reg_data        = center_re_reg_total_fee($row['uid'], $year);
            $final_re_reg_total = 0;
            $re_reg_total       = 0;
            $subCourse_details  = [];

            if (is_array($re_reg_data)) {
                foreach ($re_reg_data as $val) {
                    $subCourse_details = get_sub_courses_by_id($val['sub_course_id']);
                    $fee               = $val['fee'];
                    $crs_fee           = $row['crs_fee'];
                    $crs_fee_in_rs     = $val['crs_fee_in_rs'];
                    if ($val['admission_type'] == 'LATERAL ENTRY') {
                        $lateralFee = $subCourse_details[0]['lateral_fees'];
                    } else {
                        $lateralFee = 0;
                    }
                    if ($val['admission_type'] == 'CREDIT TRANSFER') {
                        $creadit_transfer = $subCourse_details[0]['credit_transfer'];
                    } else {
                        $creadit_transfer = 0;
                    }
                    $exam_fee = $val['exam_fee'];
                    if (isset($val['late_fee']) && $val['late_fee'] != '') {
                        $late_fee = $val['late_fee'];
                    } else {
                        $late_fee = 0;
                    }
                    $service_charge = $row['service_charge'];
                    $total          = $crs_fee_in_rs + $exam_fee + $lateralFee + $creadit_transfer + $service_charge + $late_fee;
                    $re_reg_total   = $re_reg_total + $total;
                }
                $final_re_reg_total = $re_reg_total;
            }

            $last_uploaded     = $uploaded_form[0]['created_date'];
            $data              = center_total_fee($row['uid'], $year);
            $final_total       = 0;
            $final_fresh_total = 0;

            if (is_array($data)) {
                foreach ($data as $rows) {
                    $subCourse_details = get_sub_courses_by_id($rows['sub_course_id']);
                    $service_charge    = $row['service_charge'];
                    $prospectus_fee    = $row['prospectus_fee'];
                    $fee               = $rows['fee'];
                    $crs_fee           = $rows['crs_fee'];
                    $crs_fee_in_rs     = $rows['crs_fee_in_rs'];
                    if ($rows['admission_type'] == 'LATERAL ENTRY') {
                        $lateralFee = $subCourse_details[0]['lateral_fees'];
                    } else {
                        $lateralFee = 0;
                    }
                    if ($rows['admission_type'] == 'CREDIT TRANSFER') {
                        $creadit_transfer = $subCourse_details[0]['credit_transfer'];
                    } else {
                        $creadit_transfer = 0;
                    }
                    $exam_fee = $rows['exam_fee'];
                    if (isset($rows['late_fee']) && $rows['late_fee'] != '') {
                        $late_fee = $rows['late_fee'];
                    } else {
                        $late_fee = 0;
                    }
                    $total       = $crs_fee_in_rs + $exam_fee + $lateralFee + $creadit_transfer + $prospectus_fee + $service_charge + $late_fee;
                    $final_total = $final_total + $total;
                }
                $final_fresh_total = $final_total;
            }

            $total_fee             = $final_fresh_total + $final_re_reg_total;
            $company_name          = ($row['company_name']);
            $name                  = ucwords($row['name']);
            $mobile                = ($row['mobile']);
            $email                 = ($row['email']);
            $received_amount       = get_center_received_amount($row['uid']);
            $total_received_amount = '';
            if ($received_amount[0]['amount']) {
                $total_received_amount = $received_amount[0]['amount'];
            }
            $total_balance = '';
            if (isset($total_received_amount) && $total_received_amount != '' && $total_received_amount != '0') {
                $total_balance = $total_received_amount - $total_fee;
            }
            $service_charge = ($row['service_charge']);
            $password       = ($row['show_password']);
            $prospectus_fee = ($row['prospectus_fee']);
            $user_name      = ($row['user_name']);
            $crs_fee        = ($row['crs_fee']);

            $rowArray[$index] = [
                "Company Name"         => $company_name,
                "Fresh Student"        => $studentCount,
                "Fresh Bill"           => $final_fresh_total,
                "RR Student"           => $studentReRegCount,
                "RR Bill"              => $final_re_reg_total,
                "Enrolled Student"     => $total_enrolled,
                "Form Received"        => $total_submited,
                "Form Uploaded Date"   => $last_uploaded,
                'Prospectus Fee'       => $prospectus_fee,
                "CRS Fee (%)"          => $crs_fee,
                'Service Charge'       => $service_charge,
                'Total'                => $total_fee,
                'Total Received Amount'=> $total_received_amount,
                'Balance'              => $total_balance,
            ];
            $index++;
        }

        $data = ($rowArray);

        function filterData(&$str)
        {
            $str = preg_replace("/\t/", "\\t", $str);
            $str = preg_replace("/\r?\n/", "\\n", $str);
            if (strstr($str, '"'))
                $str = '"' . str_replace('"', '""', $str) . '"';
        }

        $fileName = "User-list-" . date('d-m-Y') . date("h:i:sa") . ".xls";

        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        $flag = false;
        foreach ($data as $row) {
            if (!$flag) {
                echo implode("\t", array_keys($row)) . "\n";
                $flag = true;
            }
            array_walk($row, 'filterData');
            echo implode("\t", array_values($row)) . "\n";
        }
        return true;
    }

    public function last_login()
    {
        $data['active']       = "reports";
        $data['centers_list'] = $this->AdminModel->latest_login_centers();
        return view('header', $data) . view('center_last_login', $data) . view('footer', $data);
    }

    public function conversion_report()
    {
        $data['active'] = "reports";
        $leads      = $this->ScriptModel->get_conversion_leads();
        $final_data = [];

        foreach ($leads as $key) {
            $final_data[$key->user_id]['user_id'] = $key->user_id;
            if (empty($final_data[$key->user_id]['total_leads']) == TRUE) {
                $final_data[$key->user_id]['total_leads'] = 0;
            }
            $final_data[$key->user_id]['total_leads'] = $final_data[$key->user_id]['total_leads'] + $key->total;
            if (empty($final_data[$key->user_id]['sales_status']) == TRUE) {
                $final_data[$key->user_id]['sales_status'] = 0;
            }
            if (isset($key->sales_status) && $key->sales_status != '') {
                $final_data[$key->user_id]['sales_status']++;
            }
            if (isset($key->lead_source) && $key->lead_source != '') {
                if (empty($final_data[$key->user_id]['lead_source'][$key->lead_source]) == TRUE) {
                    $final_data[$key->user_id]['lead_source'][$key->lead_source] = 0;
                }
                $final_data[$key->user_id]['lead_source'][$key->lead_source]++;
            } else {
                if (empty($final_data[$key->user_id]['lead_source']['Self']) == TRUE) {
                    $final_data[$key->user_id]['lead_source']['Self'] = 0;
                }
                $final_data[$key->user_id]['lead_source']['Self']++;
            }
        }

        $data['report_data'] = $final_data;
        return view('header', $data) . view('conversion_report', $data) . view('footer', $data);
    }

    public function task_report()
    {
        $data['active']       = "reports";
        $data['centers_list'] = $this->AdminModel->view_center();
        return view('header', $data) . view('task_report', $data) . view('footer', $data);
    }

    public function lead_summary()
    {
        $data['active']      = "reports";
        $lead_list           = $this->ScriptModel->get_lead_summary();
        $data['report_data'] = $lead_list;
        return view('header', $data) . view('lead_summary_report', $data) . view('footer', $data);
    }

    public function lead_source_report()
    {
        $data['active']      = "reports";
        $lead_list           = $this->ScriptModel->get_source_leads();
        $data['report_data'] = $lead_list;
        return view('header', $data) . view('lead_source_report', $data) . view('footer', $data);
    }
}