<?php

namespace App\Controllers;

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

class Customers extends BaseController {

    public function index() {
        $model = model(CustomersModel::class);

        $data['customer_list'] = $model->getCustomers();
        echo view('customers/index', $data);
    }

    public function show(?string $id = null) {
        $model = model(CustomersModel::class);
        $data['customer'] = $model->getCustomers($id);

        echo view('customers/view', $data);
    }

    public function new() {
        helper('form');

        return view('templates/header', ['title' => 'Create a customer'])
                . view('customers/create')
                . view('templates/footer');
    }

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

    public function save() {
        helper('form');

        $data = $this->request->getPost(['customer_name', 'customer_email', 'customer_password']);

        // Checks whether the submitted data passed the validation rules.
        if (!$this->validateData($data, [
                    'customer_name' => 'required|max_length[255]|min_length[3]',
                    'customer_email' => 'required|max_length[255]|min_length[10]',
                    'customer_password' => 'required|max_length[255]|min_length[10]',
                ])) {
            // The validation fails, so returns the form.
            return $this->new();
        }

        // Gets the validated data.
        $customer = $this->validator->getValidated();

        $model = model(CustomersModel::class);

        $model->save([
            'customer_name' => $customer['customer_name'],
            'customer_email' => $customer['customer_email'],
            'customer_password' => password_hash($customer['customer_password'], PASSWORD_DEFAULT),
            'created_at' => date('Y-m-d H:i:s'),
        ]);

//         echo view('customers/index', ['title' => 'Customers List']);
        return redirect()->to(base_url('customers'));
    }

    public function upload() {
        $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('customers/add_file', $data);
        }

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

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

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

            $model->update($id, $data1);
            return redirect()->to(base_url('customers'));
        }

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

        return view('customers/add_file/' . $id, $data);
    }

    public function view(?int $id = null) {

        $model = model(CustomersModel::class);
        $data['customer'] = $model->getCustomers($id);

        $p = model(PersonalDetailsModel::class);
        $data['personal_details'] = $p->getPersonalDetails($id);

        $b = model(BankDetailsModel::class);
        $data['bank_details'] = $b->getBankDetails($id);

        $d = model(DocumentsModel::class);
        $data['document'] = $d->getDocuments($id);
//    echo '<pre>';
//    print_r($data);
//    die;

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

    public function edit(?int $id = null) {

        $model = model(CustomersModel::class);

        $data['customer'] = $model->getCustomers($id);

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

    public function delete($id = null) {

        $model = new CustomersModel();

        $model->where('id', $id)->delete();

        return redirect()->to(base_url('customers'));
    }

    public function viewFile() {
        $id = $this->session->id;
        $model = model(CustomersModel::class);

        $data['customer'] = $model->getCustomers($id);

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

    public function viewProfile(?int $id = null) {
        if ($this->session->id > 0) {
            $model = model(CustomersModel::class);

            $id = $this->session->id;
            $data['customer'] = $model->getCustomers($id);

            echo view('customers/profile', $data);
        }
    }

    public function viewPersonalDetails(?int $id = null) {
        if ($this->session->id > 0) {


            $id = $this->session->id;
            $c = model(CustomersModel::class);
            $data['customer'] = $c->getCustomers($id);
            $model = model(PersonalDetailsModel::class);
            $data['personal'] = $model->getPersonalDetails($id);

            echo view('customers/personal_details', $data);
        }
    }

    public function viewBankDetails(?int $id = null) {
        if ($this->session->id > 0) {

            $id = $this->session->id;
            $c = model(CustomersModel::class);
            $data['customer'] = $c->getCustomers($id);
            $b = model(BankDetailsModel::class);
            $data['bank'] = $b->getBankDetails($id);
            echo view('customers/bank_details', $data);
        }
    }

    public function viewDocuments(?int $id = null) {
        if ($this->session->id > 0) {
            $id = $this->session->id;

            $c = model(CustomersModel::class);
            $data['customer'] = $c->getCustomers($id);

            $model = model(DocumentsModel::class);
            $data['doc'] = $model->getDocuments($id);

            echo view('customers/documents', $data);
        }
    }

    public function savePersonalDetails() {
        $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[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[10]|max_length[50]',
            'ref_no_2' => 'required|min_length[10]|max_length[50]',
            'esic_no' => 'required|exact_length[17]|regex_match[^[0-9]*$]',
            'pf_no' => 'required|exact_length[22]',
        ];

        $experience_type = $this->request->getVar('experience_type');
        $height_type = $this->request->getVar('height_type');
        if ($this->validate($rules)) {
            $userModel = new PersonalDetailsModel();
            $data = [
                'customer_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'),
            ];
            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', 'Personal details save successfully');

            return redirect()->to('/customers/personal-details');
        } else {
            $data['validation'] = $this->validator;
            $c = model(CustomersModel::class);
            $data['customer'] = $c->getCustomers($id);
            $model = model(PersonalDetailsModel::class);
            $data['personal'] = $model->getPersonalDetails($id);
            echo view('customers/personal_details', $data);
        }
    }

    public function saveBankDetails() {
        $id = $this->session->id;
        $rules = [
            'bank_name' => 'required|min_length[2]|max_length[256]',
            'account_no' => 'required|exact_length[16]|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]',
        ];

        if ($this->validate($rules)) {
            $bankModel = new BankDetailsModel();
            $data = [
                'customer_id' => $id,
                'bank_name' => $this->request->getVar('bank_name'),
                'account_no' => $this->request->getVar('account_no'),
                'ifsc_code' => $this->request->getVar('ifsc_code'),
                'branch_name' => $this->request->getVar('branch_name'),
            ];
            if ($this->request->getVar('update_id') > 0) {
                $bankModel->update($this->request->getVar('update_id'), $data);
            } else {
                $bankModel->save($data);
            }

            $this->session->markAsFlashdata('success');
            $this->session->setFlashdata('success', 'Bank details save successfully');

            return redirect()->to('/customers/bank-details');
        } else {
            $data['validation'] = $this->validator;
            $model = model(CustomersModel::class);

            $data['customer'] = $model->getCustomers($id);
            echo view('customers/bank_details', $data);
        }
    }

    public function saveDocuments() {
        $id = $this->session->id;
        $validationRule = [
            '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]',
                ],
            ],
        ];

        if ($this->request->getVar('update_id') > 0) {
            $model1 = model(DocumentsModel::class);
            $doc = $model1->getDocumentsByID($this->request->getVar('update_id'));
        }
        $isValid = true;
        if (!$this->validateData([], $validationRule) && !isset($doc['person_photo'])) {
            $isValid = false;
        }
        if (!$this->validateData([], $validationRule) && !isset($doc['aadhar_card'])) {
            $isValid = false;
        }
        if (!$this->validateData([], $validationRule) && !isset($doc['pancard'])) {
            $isValid = false;
        }
        if (!$this->validateData([], $validationRule) && !isset($doc['passbook_cheque'])) {
            $isValid = false;
        }
        if (!$this->validateData([], $validationRule) && !isset($doc['reference_aaddhar_photo_1'])) {
            $isValid = false;
        }
        if (!$this->validateData([], $validationRule) && !isset($doc['reference_aaddhar_photo_2'])) {
            $isValid = false;
        }
        if (!$this->validateData([], $validationRule) && !isset($doc['education_certificate'])) {
            $isValid = false;
        }

        if (!$isValid) {
            $data = ['errors' => $this->validator->getErrors()];

            $data['validation'] = $this->validator;
            $model = model(CustomersModel::class);

            $data['customer'] = $model->getCustomers($id);
            echo view('customers/documents', $data);
        } else {
            $img1 = $this->request->getFile('person_photo');
            if ($img1 != "" && !$img1->hasMoved()) {
                $newName1 = $img1->getRandomName();
                $filepath1 = $img1->move(ROOTPATH . 'public/uploads/', $newName1);
            } else {
                $newName1 = $doc['person_photo'] ?? "";
            }

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

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

            $img4 = $this->request->getFile('passbook_cheque');
            if ($img4 != "" && !$img4->hasMoved()) {
                $newName4 = $img4->getRandomName();
                $filepath4 = $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();
                $filepath5 = $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();
                $filepath6 = $img6->move(ROOTPATH . 'public/uploads/', $newName5);
            } else {
                $newName6 = $doc['reference_aaddhar_photo_2'] ?? "";
            }

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

            $docModel = new DocumentsModel();
            $data = [
                'customer_id' => $id,
                'person_photo' => $newName1,
                'aadhar_card' => $newName2,
                'pancard' => $newName3,
                'passbook_cheque' => $newName4,
                'reference_aaddhar_photo_1' => $newName5,
                'reference_aaddhar_photo_2' => $newName6,
                'education_certificate' => $newName7,
            ];
            if ($this->request->getVar('update_id') > 0) {
                $docModel->update($this->request->getVar('update_id'), $data);
            } else {
                $docModel->save($data);
            }
            $this->session->markAsFlashdata('success');
            $this->session->setFlashdata('success', 'Documents save successfully');

            return redirect()->to('/customers/documents');
        }
    }
}
