<?php

namespace App\Controllers;

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

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

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

    public function exportLeadData()
    {
        ini_set('memory_limit', '-1');
        ini_set('default_socket_timeout', 6000);
        set_time_limit(0);

        $user_id   = session()->get('user_id');
        $user_type = session()->get('user_type');
        $leadArray = $this->LeadModel->get_all_leads();
        $rowArray  = [];
        $index     = 0;

        foreach ($leadArray as $key) {
            $name          = ucwords($key->name);
            $id            = $key->id;
            $state         = $key->state;
            $city          = $key->city;
            $email         = $key->email;
            $phone         = $key->phone;
            $assigned_date = date('d-m-Y', strtotime($key->assigned_date));
            $lead_source   = $key->lead_source;
            $user_details  = get_center_by_id($key->user_id);

            if ($user_type == '0') {
                $rowArray[$index] = ["Lead No." => $id, "Name" => $name, "Mobile No" => $phone, "Email ID" => $email, "City" => $city, "State" => $state, "Lead Source" => $lead_source, "Assigned Date" => $assigned_date, "Owner" => $user_details[0]['user_name']];
            } else {
                $rowArray[$index] = ["Lead No." => $id, "Name" => $name, "Mobile No" => $phone, "Email ID" => $email, "City" => $city, "State" => $state, "Lead Source" => $lead_source, "Assigned Date" => $assigned_date, "Owner" => $user_details[0]['user_name']];
            }
            $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 = "Lead-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 exportUserData()
    {
        $userArray = $this->AdminModel->get_all_centers(0, 0);
        $rowArray  = [];
        $index     = 0;

        foreach ($userArray as $row) {
            $name      = ucwords($row['name']);
            $mobile    = ($row['mobile']);
            $email     = ($row['email']);
            $user_name = ($row['user_name']);
            $status    = ($row['status']);

            if ($status == 1) {
                $status = 'Active';
            } else {
                $status = 'inActive';
            }

            $rowArray[$index] = ["Name" => $name, "Mobile" => $mobile, "Email ID" => $email, "User Name" => $user_name, "Status" => $status];
            $index++;
        }

        $data = ($rowArray);

        function filterData2(&$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, 'filterData2');
            echo implode("\t", array_values($row)) . "\n";
        }
        return true;
    }

    public function importUserData()
    {
        $data['active'] = "student";
        return view('header', $data) . view('script', $data) . view('footer', $data);
    }

    public function importUserData1()
    {
        $file_open = fopen($file, "r");
        $i = 0;
        $j = 200;

        while (($csv = fgetcsv($file_open, 1000, ",")) !== false) {
            $row = [
                'user_id'        => '1',
                'name'           => $csv[0] . ' ' . $csv[1],
                'email'          => $csv[2],
                'lead_origin'    => $csv[3],
                'phone'          => $csv[4],
                'lead_source'    => ucwords(strtolower($csv[6])),
                'city'           => $csv[11],
                'state'          => $csv[12],
                'course'         => $csv[13],
                'specialization' => $csv[14],
                'university'     => $csv[15],
                'created_by'     => $csv[19],
                'created_at'     => date("Y-m-d H:i:s", strtotime($csv[9])),
                'updated_at'     => date("Y-m-d H:i:s", strtotime($csv[10])),
            ];
            $i++;
            echo $i;

            if ($i > 1) {
                $inserted_id = $this->ScriptModel->add_leads($row);
                if ($inserted_id > 0) {
                    $activity = [
                        'user_id'       => '1',
                        'lead_id'       => $inserted_id,
                        'activity_type' => $csv[7],
                        'created_by'    => $csv[19],
                        'created_at'    => date("Y-m-d H:i:s", strtotime($csv[9])),
                    ];
                    $inserted_id = $this->ScriptModel->add_activity($activity);
                }
            }

            if ($i % $j == 0) {
                sleep(5);
            }
        }
    }

    public function updateUserData()
    {
        $file      = $_FILES["file"]["tmp_name"];
        $file_open = fopen($file, "r");
        $i = 0;
        $j = 200;

        while (($csv = fgetcsv($file_open, 1000, ",")) !== false) {
            $row = [
                'admission_session' => $csv[0],
                'student_name'      => ucwords(strtolower($csv[1])),
                'father_name'       => ucwords(strtolower($csv[2])),
                'mother_name'       => ucwords(strtolower($csv[3])),
                'enroll_no'         => $csv[4],
            ];
            $i++;
            echo $i;
            $this->ScriptModel->update_user_details($row);

            if ($i % $j == 0) {
                sleep(5);
            }
        }
    }

    public function exportBillData()
    {
        $student_type = $this->request->getGet('student_type');
        $year         = $this->request->getGet('year');

        if ($student_type) {
            $student_type = $student_type;
        } else {
            $student_type = 'total';
        }

        if ($year) {
            $year = $year;
        } else {
            $year = 'A 18-19';
        }

        $student_details = $this->AdminModel->get_student_details($year, $student_type);
        $rowArray        = [];
        $index           = 0;

        foreach ($student_details as $key) {
            $center_details    = get_center_by_id($key->user_id);
            $subCourse_details = get_sub_courses_by_id($key->sub_course_id);
            $course            = get_courses_by_id($key->course_id);

            if ($key->admission_type == 'LATERAL ENTRY') {
                $lateralFee = $subCourse_details[0]['lateral_fees'];
            } else {
                $lateralFee = 0;
            }

            if ($key->admission_type == 'CREDIT TRANSFER') {
                $creadit_transfer = $subCourse_details[0]['credit_transfer'];
            } else {
                $creadit_transfer = 0;
            }

            $total = $key->crs_fee_in_rs + $key->exam_fee + $lateralFee + $creadit_transfer + $center_details[0]['prospectus_fee'] + $center_details[0]['service_charge'];

            $rowArray[$index] = ["Ref No." => ucfirst($key->id), "Enroll No" => ucfirst($key->enroll_num), "Student Name" => ucfirst($key->name), "Father Name" => ucfirst($key->father_name), "Admission Type" => ucfirst($key->admission_type), "Course" => $course, "Sub Course-Cat" => $subCourse_details[0]['name'], "YEAR" => $key->year, 'Uploaded By' => $center_details[0]['company_name'], 'Univ FEE' => $key->crs_fee_in_rs, "Univ Sharing %" => $key->crs_fee, "EX. FEE" => $key->exam_fee, "Lateral FEE" => $lateralFee, "Credit Transfer" => $creadit_transfer, "Prospectus FEE" => $center_details[0]['prospectus_fee'], "Service Charge" => $center_details[0]['service_charge'], "Total" => $total];
            $index++;
        }

        $data = ($rowArray);

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

        $fileName = "User-bill-" . 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, 'filterData3');
            echo implode("\t", array_values($row)) . "\n";
        }
        return true;
    }

    public function exportReRegStudentData()
    {
        ini_set('memory_limit', '-1');
        set_time_limit(0);

        $center_name = $_GET['center_name'];
        $year        = $_GET['year'];
        $user_id     = session()->get('user_id');
        $user_type   = session()->get('user_type');

        $studentArray1 = $this->AdminModel->get_re_reg_all_student(0, $year);
        $studentArray  = json_decode(json_encode($studentArray1), True);
        $rowArray      = [];
        $index         = 0;

        foreach ($studentArray as $row) {
            $name              = ucwords($row['name']);
            $ref_num           = $id = ($row['id']);
            $father_name       = ucwords($row['father_name']);
            $mother_name       = ucwords($row['mother_name']);
            $gender            = ucwords($row['gender']);
            $center_details    = get_center_by_id($row['user_id']);
            $subCourse_details = get_sub_courses_by_id($row['sub_course_id']);
            $getPendency       = get_pendency($row['id']);
            $sub_course_name   = $subCourse_details[0]['name'];
            $course_name       = get_courses_by_id($row['course_id']);
            $service_charge    = $center_details[0]['service_charge'];
            $re_reg_fee        = $center_details[0]['re_reg_fee'];
            $fee               = $row['fee'];
            $crs_fee           = $center_details[0]['crs_fee'];
            $crs_fee_in_rs     = $row['crs_fee_in_rs'];

            if ($row['admission_type'] == 'LATERAL ENTRY') {
                $lateralFee = $subCourse_details[0]['lateral_fees'];
            } else {
                $lateralFee = 0;
            }

            if ($row['admission_type'] == 'CREDIT TRANSFER') {
                $creadit_transfer = $subCourse_details[0]['credit_transfer'];
            } else {
                $creadit_transfer = 0;
            }

            $exam_fee = $row['exam_fee'];

            if (isset($row['late_fee']) && $row['late_fee'] != '') {
                $late_fee = $row['late_fee'];
            } else {
                $late_fee = 0;
            }

            $total             = $row['total'];
            $total             = $crs_fee_in_rs + $exam_fee + $lateralFee + $creadit_transfer + $service_charge + $late_fee;
            $studantEduArray   = get_student_education($row['id']);
            $year              = $row['year'];
            $calender_from     = $row['calender_from'];
            $calender_to       = $row['calender_to'];
            $enroll_num        = $row['enroll_num'];
            $re_reg_date       = $row['re_reg_date'];
            $re_reg            = $row['re_reg'];
            $admission_session = $row['admission_session'];
            $admission_type    = $row['admission_type'];
            $center_user_name  = $center_details[0]['user_name'];
            $center_name       = $center_details[0]['company_name'];
            $counselor_name    = $center_details[0]['counselor_name'];

            if ($user_type == '0') {
                $rowArray[$index] = ["REF NO." => $id, "App. Id" => $enroll_num, "Applied Date" => $re_reg_date, "Admission Session" => $admission_session, "Admission Type" => $admission_type, "Name" => $name, "Father Name" => $father_name, "Mother Name" => $mother_name, "Course Name" => $course_name, "Sub Course" => $sub_course_name, "Year" => $year, "Re Reg Year" => $re_reg, "Center Code" => $center_user_name, "Center Name" => $center_name, "Counselor Name" => $counselor_name, "CRS fee" => $crs_fee_in_rs, "CRS fee %" => $crs_fee, "Exam Fee" => $exam_fee, "Service Charge" => $service_charge, "Late Fee" => $late_fee, "Re Reg Fee" => $re_reg_fee, "Total" => $total];
            } else {
                $rowArray[$index] = ["REF NO." => $id, "App. Id" => $enroll_num, "Applied Date" => $re_reg_date, "Admission Session" => $admission_session, "Admission Type" => $admission_type, "Name" => $name, "Father Name" => $father_name, "Mother Name" => $mother_name, "Course Name" => $course_name, "Sub Course" => $sub_course_name, "Year" => $year, "Re Reg Year" => $re_reg, "Center Code" => $center_user_name, "Center Name" => $center_name, "Counselor Name" => $counselor_name, "CRS fee" => $crs_fee_in_rs, "CRS fee %" => $crs_fee, "Exam Fee" => $exam_fee, "Service Charge" => $service_charge, "Late Fee" => $late_fee, "Re Reg Fee" => $re_reg_fee, "Total" => $total];
            }
            $index++;
        }

        $data = ($rowArray);

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

        $fileName = "Student-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, 'filterData4');
            echo implode("\t", array_values($row)) . "\n";
        }
        return true;
    }

    public function lead_reminder()
    {
        ini_set('memory_limit', '-1');
        ini_set('default_socket_timeout', 6000);
        set_time_limit(0);

        $user_id   = session()->get('user_id');
        $user_type = session()->get('user_type');
        $leadArray = $this->ScriptModel->get_fresh_lead();

        foreach ($leadArray as $key) {
            $user_details = get_center_by_id($key->user_id);

            $email = \Config\Services::email();

            $email->setFrom('info@blackboardindia.com', 'Blackboardindia');
            $email->setTo('rajuraj211@gmail.com');
            $email->setCC('admin@blackboardindia.com');
            $email->setSubject('Lead Reminder');
            $email->setMessage('Hi ' . $user_details[0]['user_name'] . "\n" . "\n"
                . 'You have not contacted the lead with the below-mentioned details.'
                . "\n"
                . ' Please contact the lead asap.'
                . "\n"
                . 'Name: ' . $key->name
                . "\n"
                . 'Phone Number: ' . $key->phone
                . "\n"
                . "\n"
                . 'Regards,'
                . "\n"
                . 'Admin'
                . "\n" . "\n" . "\n"
                . 'This is an automatically generated email. Please do not reply'
            );
            $email->send();
            exit;
        }
    }
}