<?php

namespace App\Controllers;

use App\Models\EmployeeModel;
use App\Models\PersonalDetailsModel;
use App\Models\BankDetailsModel;
use App\Models\DocumentsModel;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\Files\File;

class Employee extends BaseController {

    public function Dashboard() {
        $data = [
            'name' => $this->session->get('name'),
            'email' => $this->session->get('email')
        ];
        $id = $this->session->id;
        $model = model(EmployeeModel::class);
        $data['employee_list'] = $model->getEmployeesByFieldManagerId($id);
        echo view('employee/dashboard', $data);
    }

    public function EmployeeList() {
        $model = model(EmployeeModel::class);
        $id = $this->session->id;
        $data['employee_list'] = $model->getEmployeesByFieldManagerId($id);
        echo view('employee/list', $data);
    }

    public function createEmployee() {
        helper('form');
        $id = $this->session->id;
        $data['field_manager_id'] = $id;
        return view('templates/header', ['title' => 'Create a Employee'])
                . view('employee/create_employee', $data)
                . view('templates/footer');
    }

    public function saveEmployeeData() {
        $id = $this->session->id;
        $rules = [
            'organization' => 'required|min_length[2]|max_length[200]',
            'person_name' => 'required|min_length[2]|max_length[50]',
            'gender' => 'required',
            'marital_status' => 'required',
            'person_dob' => 'required|min_length[2]|max_length[50]',
            'mother_name' => 'required|min_length[2]|max_length[50]',
            'father_name' => 'required|min_length[2]|max_length[50]',
            'education' => 'required|min_length[2]|max_length[200]',
            'experience' => 'required|min_length[1]|max_length[16]',
            'height' => 'required|min_length[1]|max_length[50]',
            'local_address' => 'required|min_length[2]|max_length[200]',
            'permanent_address' => 'required|min_length[2]|max_length[200]',
            'state' => 'required|min_length[2]|max_length[200]',
            'city' => 'required|min_length[2]|max_length[200]',
            'pincode' => 'required|exact_length[6]|regex_match[^[0-9]*$]',
            'contact_no' => 'required|exact_length[10]|regex_match[^[0-9]*$]',
            'ref_no_1' => 'required|min_length[3]|max_length[50]',
            'ref_no_2' => 'required|min_length[3]|max_length[50]',
            'esic_no' => 'required|min_length[10]|regex_match[^[0-9]*$]',
            'pf_no' => 'required|min_length[12]',
            'bank_name' => 'required|min_length[2]|max_length[256]',
            'account_no' => 'required|exact_length[11]|regex_match[^[0-9]*$]',
            'ifsc_code' => 'required|exact_length[11]|regex_match[^[A-Z]{4}0[A-Z0-9]{6}$]',
            'branch_name' => 'required|min_length[4]|max_length[256]',
            'person_photo' => [
                'label' => 'Person photo',
                'rules' => [
                    'uploaded[person_photo]',
                    'is_image[person_photo]',
                    'mime_in[person_photo,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                    'max_size[person_photo,2048]',
                    'max_dims[person_photo,1024,768]',
                ],
            ],
            'aadhar_card' => [
                'label' => 'Aadhar card photo',
                'rules' => [
                    'uploaded[aadhar_card]',
                    'is_image[aadhar_card]',
                    'mime_in[aadhar_card,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                    'max_size[aadhar_card,2048]',
                    'max_dims[aadhar_card,1024,768]',
                ],
            ],
            'pancard' => [
                'label' => 'Pancard photo',
                'rules' => [
                    'uploaded[pancard]',
                    'is_image[pancard]',
                    'mime_in[pancard,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                    'max_size[pancard,2048]',
                    'max_dims[pancard,1024,768]',
                ],
            ],
            'passbook_cheque' => [
                'label' => 'Passbook cheque photo',
                'rules' => [
                    'uploaded[passbook_cheque]',
                    'is_image[passbook_cheque]',
                    'mime_in[passbook_cheque,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                    'max_size[passbook_cheque,2048]',
                    'max_dims[passbook_cheque,1024,768]',
                ],
            ],
            'reference_aadhar_photo_1' => [
                'label' => 'Reference aadhar photo 1',
                'rules' => [
                    'uploaded[reference_aadhar_photo_1]',
                    'is_image[reference_aadhar_photo_1]',
                    'mime_in[reference_aadhar_photo_1,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                    'max_size[reference_aadhar_photo_1,2048]',
                    'max_dims[reference_aadhar_photo_1,1024,768]',
                ],
            ],
            'reference_aadhar_photo_2' => [
                'label' => 'Reference aadhar photo 2',
                'rules' => [
                    'uploaded[reference_aadhar_photo_2]',
                    'is_image[reference_aadhar_photo_2]',
                    'mime_in[reference_aadhar_photo_2,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                    'max_size[reference_aadhar_photo_2,2048]',
                    'max_dims[reference_aadhar_photo_2,1024,768]',
                ],
            ],
            'education_certificate' => [
                'label' => 'Education Certificate photo',
                'rules' => [
                    'uploaded[education_certificate]',
                    'is_image[education_certificate]',
                    'mime_in[education_certificate,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                    'max_size[education_certificate,2048]',
                    'max_dims[education_certificate,1024,768]',
                ],
            ],
        ];

        $experience_type = $this->request->getVar('experience_type');
        $height_type = $this->request->getVar('height_type');
        if ($this->validate($rules)) {
            $userModel = new EmployeeModel();

            $img1 = $this->request->getFile('person_photo');
            $newName1 = '';
            if ($img1 != "" && !$img1->hasMoved()) {
                $newName1 = $img1->getRandomName();
                $img1->move(ROOTPATH . 'public/uploads/', $newName1);
            }

            $img2 = $this->request->getFile('aadhar_card');
            $newName2 = '';
            if ($img2 != "" && !$img2->hasMoved()) {
                $newName2 = $img2->getRandomName();
                $img2->move(ROOTPATH . 'public/uploads/', $newName2);
            }

            $img3 = $this->request->getFile('pancard');
            if ($img3 != "" && !$img3->hasMoved()) {
                $newName3 = $img3->getRandomName();
                $img3->move(ROOTPATH . 'public/uploads/', $newName3);
            } else {
                $newName3 = "";
            }

            $img4 = $this->request->getFile('passbook_cheque');
            if ($img4 != "" && !$img4->hasMoved()) {
                $newName4 = $img4->getRandomName();
                $img4->move(ROOTPATH . 'public/uploads/', $newName4);
            } else {
                $newName4 = $doc['pancard'] ?? "";
            }

            $img5 = $this->request->getFile('reference_aadhar_photo_1');
            if ($img5 != "" && !$img5->hasMoved()) {
                $newName5 = $img5->getRandomName();
                $img5->move(ROOTPATH . 'public/uploads/', $newName5);
            } else {
                $newName5 = $doc['reference_aaddhar_photo_1'] ?? "";
            }

            $img6 = $this->request->getFile('reference_aadhar_photo_2');
            if ($img6 != "" && !$img6->hasMoved()) {
                $newName6 = $img6->getRandomName();
                $img6->move(ROOTPATH . 'public/uploads/', $newName6);
            } else {
                $newName6 = $doc['reference_aaddhar_photo_2'] ?? "";
            }

            $img7 = $this->request->getFile('education_certificate');
            if ($img7 != "" && !$img7->hasMoved()) {
                $newName7 = $img7->getRandomName();
                $img7->move(ROOTPATH . 'public/uploads/', $newName7);
            } else {
                $newName7 = $doc['education_certificate'] ?? "";
            }

            $data = [
                'field_manager_id' => $id,
                'organization' => $this->request->getVar('organization'),
                'person_name' => $this->request->getVar('person_name'),
                'gender' => $this->request->getVar('gender'),
                'marital_status' => $this->request->getVar('marital_status'),
                'spouse_name' => $this->request->getVar('spouse_name'),
                'person_dob' => $this->request->getVar('person_dob'),
                'mother_name' => $this->request->getVar('mother_name'),
                'father_name' => $this->request->getVar('father_name'),
                'education' => $this->request->getVar('education'),
                'experience' => $this->request->getVar('experience') . ' ' . $experience_type,
                'height' => $this->request->getVar('height') . ' ' . $height_type,
                'local_address' => $this->request->getVar('local_address'),
                'permanent_address' => $this->request->getVar('permanent_address'),
                'state' => $this->request->getVar('state'),
                'city' => $this->request->getVar('city'),
                'pincode' => $this->request->getVar('pincode'),
                'contact_no' => $this->request->getVar('contact_no'),
                'ref_no_1' => $this->request->getVar('ref_no_1'),
                'ref_no_2' => $this->request->getVar('ref_no_2'),
                'esic_no' => $this->request->getVar('esic_no'),
                'pf_no' => $this->request->getVar('pf_no'),
                'bank_name' => $this->request->getVar('bank_name'),
                'bank_account_no' => $this->request->getVar('account_no'),
                'bank_ifsc_code' => $this->request->getVar('ifsc_code'),
                'bank_branch_name' => $this->request->getVar('branch_name'),
                'doc_person_photo' => $newName1,
                'doc_aadhar_card' => $newName2,
                'doc_pancard' => $newName3,
                'doc_passbook_cheque' => $newName4,
                'doc_reference_aaddhar_photo_1' => $newName5,
                'doc_reference_aaddhar_photo_2' => $newName6,
                'doc_education_certificate' => $newName7,
            ];
            if ($this->request->getVar('update_id') > 0) {
                $userModel->update($this->request->getVar('update_id'), $data);
            } else {
                $userModel->save($data);
            }
            $this->session->markAsFlashdata('success');
            $this->session->setFlashdata('success', 'All details has been saved successfully');
            return redirect()->to('/agent/list-employee');
        } else {
            $data['validation'] = $this->validator;
            echo view('employee/create_employee', $data);
        }
    }

    public function updateEmployeeData() {
        $id = $this->session->id;
        $update_id = $this->request->getVar('update_id');
        $model = model(EmployeeModel::class);
        $oldEmployeeData = $model->getEmployeeDetails($update_id);
        $data['employee'] = $oldEmployeeData;
        $rules = [
            'organization' => 'required|min_length[2]|max_length[200]',
            'person_name' => 'required|min_length[2]|max_length[50]',
            'gender' => 'required',
            'marital_status' => 'required',
            'person_dob' => 'required|min_length[2]|max_length[50]',
            'mother_name' => 'required|min_length[2]|max_length[50]',
            'father_name' => 'required|min_length[2]|max_length[50]',
            'education' => 'required|min_length[2]|max_length[200]',
            'experience' => 'required|min_length[2]|max_length[200]',
            'height' => 'required|min_length[2]|max_length[50]',
            'local_address' => 'required|min_length[2]|max_length[200]',
            'permanent_address' => 'required|min_length[2]|max_length[200]',
            'state' => 'required|min_length[2]|max_length[200]',
            'city' => 'required|min_length[2]|max_length[200]',
            'pincode' => 'required|exact_length[6]|regex_match[^[0-9]*$]',
            'contact_no' => 'required|exact_length[10]|regex_match[^[0-9]*$]',
            'ref_no_1' => 'required|min_length[3]|max_length[50]',
            'ref_no_2' => 'required|min_length[3]|max_length[50]',
            'esic_no' => 'required|min_length[10]|regex_match[^[0-9]*$]',
            'pf_no' => 'required|min_length[12]',
            'bank_name' => 'required|min_length[2]|max_length[256]',
            'account_no' => 'required|exact_length[11]|regex_match[^[0-9]*$]',
            'ifsc_code' => 'required|exact_length[11]|regex_match[^[A-Z]{4}0[A-Z0-9]{6}$]',
            'branch_name' => 'required|min_length[4]|max_length[256]',
            'person_photo' => [
                'label' => 'Person photo',
                'rules' => [
                    'uploaded[person_photo]',
                    'is_image[person_photo]',
                    'mime_in[person_photo,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                    'max_size[person_photo,2048]',
                    'max_dims[person_photo,1024,768]',
                ],
            ],
            'aadhar_card' => [
                'label' => 'Aadhar card photo',
                'rules' => [
                    'uploaded[aadhar_card]',
                    'is_image[aadhar_card]',
                    'mime_in[aadhar_card,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                    'max_size[aadhar_card,2048]',
                    'max_dims[aadhar_card,1024,768]',
                ],
            ],
            'pancard' => [
                'label' => 'Pancard photo',
                'rules' => [
                    'uploaded[pancard]',
                    'is_image[pancard]',
                    'mime_in[pancard,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                    'max_size[pancard,2048]',
                    'max_dims[pancard,1024,768]',
                ],
            ],
            'passbook_cheque' => [
                'label' => 'Passbook cheque photo',
                'rules' => [
                    'uploaded[passbook_cheque]',
                    'is_image[passbook_cheque]',
                    'mime_in[passbook_cheque,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                    'max_size[passbook_cheque,2048]',
                    'max_dims[passbook_cheque,1024,768]',
                ],
            ],
            'reference_aadhar_photo_1' => [
                'label' => 'Reference aadhar photo 1',
                'rules' => [
                    'uploaded[reference_aadhar_photo_1]',
                    'is_image[reference_aadhar_photo_1]',
                    'mime_in[reference_aadhar_photo_1,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                    'max_size[reference_aadhar_photo_1,2048]',
                    'max_dims[reference_aadhar_photo_1,1024,768]',
                ],
            ],
            'reference_aadhar_photo_2' => [
                'label' => 'Reference aadhar photo 2',
                'rules' => [
                    'uploaded[reference_aadhar_photo_2]',
                    'is_image[reference_aadhar_photo_2]',
                    'mime_in[reference_aadhar_photo_2,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                    'max_size[reference_aadhar_photo_2,2048]',
                    'max_dims[reference_aadhar_photo_2,1024,768]',
                ],
            ],
            'education_certificate' => [
                'label' => 'Education Certificate photo',
                'rules' => [
                    'uploaded[education_certificate]',
                    'is_image[education_certificate]',
                    'mime_in[education_certificate,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                    'max_size[education_certificate,2048]',
                    'max_dims[education_certificate,1024,768]',
                ],
            ],
        ];

        $isValid = true;
        if ($oldEmployeeData['doc_person_photo'] == "" && $_FILES['person_photo']['name'] == "") {
            $isValid = false;
        }

        if ($this->validate($rules) && $isValid) {
            $userModel = new EmployeeModel();

            $img1 = $this->request->getFile('person_photo');
            $newName1 = '';
            if ($img1 != "" && !$img1->hasMoved()) {
                $newName1 = $img1->getRandomName();
                $img1->move(ROOTPATH . 'public/uploads/', $newName1);
            }

            $img2 = $this->request->getFile('aadhar_card');
            $newName2 = '';
            if ($img2 != "" && !$img2->hasMoved()) {
                $newName2 = $img2->getRandomName();
                $img2->move(ROOTPATH . 'public/uploads/', $newName2);
            }

            $img3 = $this->request->getFile('pancard');
            if ($img3 != "" && !$img3->hasMoved()) {
                $newName3 = $img3->getRandomName();
                $img3->move(ROOTPATH . 'public/uploads/', $newName3);
            } else {
                $newName3 = "";
            }

            $img4 = $this->request->getFile('passbook_cheque');
            if ($img4 != "" && !$img4->hasMoved()) {
                $newName4 = $img4->getRandomName();
                $img4->move(ROOTPATH . 'public/uploads/', $newName4);
            } else {
                $newName4 = $doc['pancard'] ?? "";
            }

            $img5 = $this->request->getFile('reference_aadhar_photo_1');
            if ($img5 != "" && !$img5->hasMoved()) {
                $newName5 = $img5->getRandomName();
                $img5->move(ROOTPATH . 'public/uploads/', $newName5);
            } else {
                $newName5 = $doc['reference_aaddhar_photo_1'] ?? "";
            }

            $img6 = $this->request->getFile('reference_aadhar_photo_2');
            if ($img6 != "" && !$img6->hasMoved()) {
                $newName6 = $img6->getRandomName();
                $img6->move(ROOTPATH . 'public/uploads/', $newName6);
            } else {
                $newName6 = $doc['reference_aaddhar_photo_2'] ?? "";
            }

            $img7 = $this->request->getFile('education_certificate');
            if ($img7 != "" && !$img7->hasMoved()) {
                $newName7 = $img7->getRandomName();
                $img7->move(ROOTPATH . 'public/uploads/', $newName7);
            } else {
                $newName7 = $doc['education_certificate'] ?? "";
            }

            $experience_type = $this->request->getVar('experience_type');
            $height_type = $this->request->getVar('height_type');
            $data = [
                'field_manager_id' => $id,
                'organization' => $this->request->getVar('organization'),
                'person_name' => $this->request->getVar('person_name'),
                'gender' => $this->request->getVar('gender'),
                'marital_status' => $this->request->getVar('marital_status'),
                'spouse_name' => $this->request->getVar('spouse_name'),
                'person_dob' => $this->request->getVar('person_dob'),
                'mother_name' => $this->request->getVar('mother_name'),
                'father_name' => $this->request->getVar('father_name'),
                'education' => $this->request->getVar('education'),
                'experience' => $this->request->getVar('experience') . ' ' . $experience_type,
                'height' => $this->request->getVar('height') . ' ' . $height_type,
                'local_address' => $this->request->getVar('local_address'),
                'permanent_address' => $this->request->getVar('permanent_address'),
                'state' => $this->request->getVar('state'),
                'city' => $this->request->getVar('city'),
                'pincode' => $this->request->getVar('pincode'),
                'contact_no' => $this->request->getVar('contact_no'),
                'ref_no_1' => $this->request->getVar('ref_no_1'),
                'ref_no_2' => $this->request->getVar('ref_no_2'),
                'esic_no' => $this->request->getVar('esic_no'),
                'pf_no' => $this->request->getVar('pf_no'),
                'bank_name' => $this->request->getVar('bank_name'),
                'bank_account_no' => $this->request->getVar('account_no'),
                'bank_ifsc_code' => $this->request->getVar('ifsc_code'),
                'bank_branch_name' => $this->request->getVar('branch_name'),
                'doc_person_photo' => $newName1,
                'doc_aadhar_card' => $newName2,
                'doc_pancard' => $newName3,
                'doc_passbook_cheque' => $newName4,
                'doc_reference_aaddhar_photo_1' => $newName5,
                'doc_reference_aaddhar_photo_2' => $newName6,
                'doc_education_certificate' => $newName7,
            ];
            $userModel->update($this->request->getVar('update_id'), $data);
            $this->session->markAsFlashdata('success');
            $this->session->setFlashdata('success', 'All details has been updated successfully');
            return redirect()->to('/agent/list-employee');
        } else {
            $data['validation'] = $this->validator;
            echo view('employee/edit', $data);
        }
    }

    public function deleteEmployee($id = null) {
        $model = new EmployeeModel();

        $model->where('id', $id)->delete();
        $this->session->markAsFlashdata('success');
        $this->session->setFlashdata('success', 'Deleted successfully.');
        return redirect()->to(base_url('agent/list-employee'));
    }

    public function editEmployee($id) {
        $model = model(EmployeeModel::class);

        $data['employee'] = $model->getEmployeeDetails($id);

        return view('templates/header', ['title' => 'Edit Employee'])
                . view('employee/edit', $data)
                . view('templates/footer');
    }

    public function viewEmployee($id) {
        $model = model(EmployeeModel::class);

        $data['employee'] = $model->getEmployeeDetails($id);
//        echo '<pre>';
//        print_r($data);
//        die;

        return view('templates/header', ['title' => 'View Employee'])
                . view('employee/view', $data)
                . view('templates/footer');
    }

    public function addEmployeeFile($id) {
        helper('form');
        $data = ['id' => $id];
        return view('templates/header', ['title' => 'Upload File'])
                . view('employee/add_offer_file', $data)
                . view('templates/footer');
    }

    public function saveOfferFile() {
        $id = $this->request->getPost('id');
        $validationRule = [
            'userfile' => [
                'label' => 'Image File',
                'rules' => [
                    'uploaded[userfile]',
                    'is_image[userfile]',
                    'mime_in[userfile,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                    'max_size[userfile,100]',
                    'max_dims[userfile,1024,768]',
                ],
            ],
        ];
        if (!$this->validateData([], $validationRule)) {
            $data = ['errors' => $this->validator->getErrors(), 'id' => $id];

            return view('agent/add-employee-file/' . $id, $data);
        }

        $img = $this->request->getFile('userfile');
        if (!$img->hasMoved()) {

            $newName = $img->getRandomName();
            $filepath = $img->move(ROOTPATH . 'public/uploads/', $newName);

            $model = model(EmployeeModel::class);
            $data1 = [
                'offer_letter' => 'public/uploads/' . $newName,
            ];

            $model->update($id, $data1);
            return redirect()->to(base_url('agent/list-employee'));
        }

        $data = ['errors' => 'The file has already been moved.', 'title' => 'Upload File', 'id' => $id];

        return view('agent/add-employee-file/' . $id, $data);
    }

    public function exportsData($id) {

        $model = model(EmployeeModel::class);

        $employee = $model->getEmployeeDetails($id);
//        echo '<pre>';
//        print_r($data);
//        die;

        $data = array(
            'Person Name' => $employee['person_name'],
            'Gender' => $employee['gender'],
            'Marital status' => $employee['marital_status'],
            'Spouse name' => $employee['spouse_name'],
            'Person dob' => $employee['person_dob'],
            'Mother name' => $employee['mother_name'],
            'Father name' => $employee['father_name'],
            'Education' => $employee['education'],
            'Height' => $employee['height'],
            'Local_address' => $employee['local_address'],
            'Organization' => $employee['organization'],
            'State' => $employee['state'],
            'City' => $employee['city'],
            'Pincode' => $employee['pincode'],
            'Ref no. 1' => $employee['ref_no_1'],
            'Ref no. 2' => $employee['ref_no_2'],
            'Esic no' => $employee['esic_no'],
            'PF No.' => $employee['pf_no'],
            'Bank name' => $employee['bank_name'],
            'Bank account no' => $employee['bank_account_no'],
            'Bank ifsc code' => $employee['bank_ifsc_code'],
            'Bank branch name' => $employee['bank_branch_name'],
            'Contact no' => $employee['contact_no'],
            'Doc_person_photo' => $employee['doc_person_photo'],
            'Doc_aadhar_card' => $employee['doc_aadhar_card'],
            'Doc_pancard' => $employee['doc_pancard'],
            'Doc_passbook_cheque' => $employee['doc_passbook_cheque'],
            'Doc_reference_aaddhar_photo_1' => $employee['doc_reference_aaddhar_photo_1'],
            'Doc_reference_aaddhar_photo_2' => $employee['doc_reference_aaddhar_photo_2'],
            'Doc_education_certificate' => $employee['doc_education_certificate'],
            'offer letter' => $employee['offer_letter'],
            'Created at' => $employee['created_at'],
            'Updated at' => $employee['updated_at'],
        );
        header("Content-type: application/csv");
        header("Content-Disposition: attachment; filename=\"employee" . ".csv\"");
        header("Pragma: no-cache");
        header("Expires: 0");
        $handle = fopen('php://output', 'w');
        $header_columns = array_keys($data);
        fputcsv($handle, $header_columns);
        fputcsv($handle, $data);
        fclose($handle);
        exit;
    }
}
