<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\CustomerModel;
use App\Models\AreaModel;
use App\Models\PackageModel;
use App\Models\PaymentModel;

class Customer extends BaseController
{


    private $CustomerModel;
    private $AreaModel;
    private $PackageModel;
    private $PaymentModel;

    public function __construct()
    {

        $this->CustomerModel        = new CustomerModel();
        $this->AreaModel            = new AreaModel();   
        $this->PackageModel         = new PackageModel();   
        $this->PaymentModel         = new PaymentModel();   
    }

    public function index()
    {
    

        haveAccess(4,"is_read", session()->get('role_id'));

        $data   = [
            'title' => "Pelanggan",
        ];

        return  view('app/customer/main/customer-main-css', $data) .
        view('app/customer/main/customer-main', $data) .
        view('app/customer/main/customer-main-js', $data);

    }


    public function add()
    {


        haveAccess(4,"is_create", session()->get('role_id'));

        $data = [
            'title' => "Tambah Pelanggan"
        ];

        return  view('app/customer/add/customer-add-css', $data) .
        view('app/customer/add/customer-add', $data) .
        view('app/customer/add/customer-add-js', $data);
    }


    public function detail($id = null)
    {


        haveAccess(4,"is_read", session()->get('role_id'));

        $row = $this->CustomerModel->find($id);
        $row->villageName = $this->AreaModel->find($row->village_id)->name;
        $row->subdistrictName = $this->AreaModel->find($row->subdistrict_id)->name;
        $row->packageName = $this->PackageModel->find($row->package_id)->name;

        $data = [
            'title' => "Detail Pelanggan",
            'row'   => $row,
            'id'   => $id,
        ];

        return  view('app/customer/detail/customer-detail-css', $data) .
        view('app/customer/detail/customer-detail', $data) .
        view('app/customer/detail/customer-detail-js', $data);
    }

    public function save()
    {


        haveAccess(4,"is_create", session()->get('role_id'));

        $request    = json_decode(json_encode($this->request->getPOST()));
        $rules = [
            'name' => [
                'rules' => 'required|min_length[3]|max_length[256]',
                'errors' => [
                    'required'   => 'Nama wajib diisi',
                    'min_length' => 'Nama minimal 3 karakter',
                    'max_length' => 'Nama tidak boleh lebih dari 256 karakter',
                ]
            ],
            // 'phone' => [
            //     'rules' => 'required|numeric|min_length[12]|max_length[16]',
            //     'errors' => [
            //         'required'   => 'Telepon wajib diisi',
            //         'numeric' => 'Telepon cuman bisa berupa angka',
            //         'min_length' => 'Telepon minimal 12 digit',
            //         'max_length' => 'Telepon tidak boleh lebih dari 16 digit',
            //     ]
            // ],
            'village' => [
                'rules' => 'required',
                'errors' => [
                    'required'   => 'Desa tidak boleh kosong',
                ]
            ],
            'subdistrict' => [
                'rules' => 'required',
                'errors' => [
                    'required'   => 'Kecamatan tidak boleh kosong',
                ]
            ],
            'package' => [
                'rules' => 'required',
                'errors' => [
                    'required'   => 'Paket internet tidak boleh kosong',
                ]
            ],
        ];


        if (!$this->validate($rules)) {
            $message = $this->validator->getErrors();
            return $this->response->setJSON(['code' => 200, 'success' => false, 'message' => $message]);
        }

            

        $data = [
            'name'          => $request->name,
            'phone'         => empty($request->phone)||!isset($request->phone) ? '000000000000' : $this->_normalizePhoneNumber($request->phone),
            'package_id'          => $request->package,
            'subdistrict_id'          => $request->subdistrict,
            'village_id'          => $request->village,
            'description'   => !empty($request->description) ? $request->description : "-",
            'created_by'    => session()->get('id'),
            'created_at'    => date('Y-m-d H:i:s'),
        ];

        if(!$this->CustomerModel->insert($data)){
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data gagal disimpan. pastikan anda terkoneksi dengan internet"
            ]);
        }



        $userId = session()->get('id');
        $nameUser = session()->get('name');
        insertLog("Customer","Create","User $nameUser berhasil membuat data pelanggan $request->name ",$userId);


        return $this->response->setJSON([
            'code'      => 200,
            'success'   => true,
            'message'   => "Data berhasil disimpan"
        ]);


    }


    public function getAllData()
    {
        
        $this->CustomerModel->draw     = $this->request->getPOST('draw');
        $this->CustomerModel->start    = $this->request->getPOST('start');
        $this->CustomerModel->limit    = $this->request->getPOST('length');
        $this->CustomerModel->search   = $this->request->getPOST('search')['value'];
        $this->CustomerModel->columns  = $this->request->getPOST('columns');
        $this->CustomerModel->order    = $this->request->getPOST('order');

        echo $this->CustomerModel->getAllData();
    }

    public function delete()
    {


        haveAccess(4,"is_delete", session()->get('role_id'));

        $request;
        if ($this->request->hasHeader('Content-Type') && strpos($this->request->getHeaderLine('Content-Type'), 'application/json') !== false) {
            $request    = $this->request->getJSON();
        }else{
            $request    = $this->request->getPOST();
        }

        $request = json_decode(json_encode($request));


        //             $this->AreaModel->where('parent_id',$request->id);
        // $isExits = $this->AreaModel->first();
        // if(!empty((array)$isExits)){
            
        //     return $this->response->setJSON([
        //         'code'      => 200,
        //         'success'   => false,
        //         'message'   => "Data kecamatan tidak bisa dihapus dikarenakan sudah digunakan di beberapa desa"
        //     ]);            
        // }


        $this->CustomerModel->where('id', $request->id);
        if(!$this->CustomerModel->delete()){

            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data gagal dihapus. pastikan anda terkoneksi dengan internet"
            ]);
        }


        $userId = session()->get('id');
        $nameUser = session()->get('name');
        insertLog("Role","Delete","User $nameUser berhasil menghapus data pelanggan",$userId);

        return $this->response->setJSON([
            'code'      => 200,
            'success'   => true,
            'message'   => "Data berhasil dihapus"
        ]);

    }


    public function edit($id = null)
    {


        haveAccess(4,"is_update", session()->get('role_id'));

        $row = $this->CustomerModel->find($id);
        $row->villageName = $this->AreaModel->find($row->village_id)->name;
        $row->subdistrictName = $this->AreaModel->find($row->subdistrict_id)->name;
        $row->packageName = $this->PackageModel->find($row->package_id)->name;

        $data = [
            'title' => "Edit Pelanggan",
            'row'   => $row
        ];

        return  view('app/customer/edit/customer-edit-css', $data) .
        view('app/customer/edit/customer-edit', $data) .
        view('app/customer/edit/customer-edit-js', $data);
        
    }



    public function update()
    {

        
        haveAccess(4,"is_update", session()->get('role_id'));

        $request    = json_decode(json_encode($this->request->getPOST()));
        $rules = [
            'name' => [
                'rules' => 'required|min_length[3]|max_length[256]',
                'errors' => [
                    'required'   => 'Nama wajib diisi',
                    'min_length' => 'Nama minimal 3 karakter',
                    'max_length' => 'Nama tidak boleh lebih dari 256 karakter',
                ]
            ],
            // 'phone' => [
            //     'rules' => 'required|numeric|min_length[12]|max_length[16]',
            //     'errors' => [
            //         'required'   => 'Telepon wajib diisi',
            //         'numeric' => 'Telepon cuman bisa berupa angka',
            //         'min_length' => 'Telepon minimal 12 digit',
            //         'max_length' => 'Telepon tidak boleh lebih dari 16 digit',
            //     ]
            // ],
            'village' => [
                'rules' => 'required',
                'errors' => [
                    'required'   => 'Desa tidak boleh kosong',
                ]
            ],
            'subdistrict' => [
                'rules' => 'required',
                'errors' => [
                    'required'   => 'Kecamatan tidak boleh kosong',
                ]
            ],
            'package' => [
                'rules' => 'required',
                'errors' => [
                    'required'   => 'Paket internet tidak boleh kosong',
                ]
            ]
        ];


        if (!$this->validate($rules)) {
            $message = $this->validator->getErrors();
            return $this->response->setJSON(['code' => 200, 'success' => false, 'message' => $message]);
        }
            

        
        $data = [
            'name'          => $request->name,
            'phone'         => empty($request->phone)||!isset($request->phone) ? '000000000000' : $this->_normalizePhoneNumber($request->phone),
            'package_id'          => $request->package,
            'subdistrict_id'          => $request->subdistrict,
            'village_id'          => $request->village,
            'description'   => !empty($request->description) ? $request->description : "-",
            'updated_by'         => session()->get('id'),
            'updated_at'         => date('Y-m-d H:i:s'),
        ];

        if(!$this->CustomerModel->update($request->id, $data)){
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data gagal disimpan. pastikan anda terkoneksi dengan internet"
            ]);
        }


        $userId = session()->get('id');
        $nameUser = session()->get('name');
        insertLog("Customer","update","User $nameUser berhasil mengubah data pelanggan $request->name ",$userId);

        return $this->response->setJSON([
            'code'      => 200,
            'success'   => true,
            'message'   => "Data berhasil disimpan"
        ]);


    }



    public function getAllSubdistirctName()
    {
        $page  = $this->request->getPOST('page') ? $this->request->getPOST('page') - 1 : 0;
        $limit = $this->request->getPOST('limit') ? $this->request->getPOST('limit') : 30;

        $this->AreaModel->name          = $this->request->getPOST('name');
        $this->AreaModel->limit         = $limit;
        $this->AreaModel->start         = ($page * $limit);

        echo $this->AreaModel->getAllSubdistirctName();
    }


    private function _normalizePhoneNumber($phone)
    {
        // Hapus spasi, tanda +, tanda hubung, dan titik
        $phone = preg_replace('/[\s\-\.\+]/', '', $phone);

        // Jika diawali 62, ubah ke 08
        if (substr($phone, 0, 2) === '62') {
            $phone = '0' . substr($phone, 2);
        }
        
        // Jika diawali +62 (jaga-jaga kalau + tidak terhapus)
        elseif (substr($phone, 0, 3) === '+62') {
            $phone = '0' . substr($phone, 3);
        }

        // Jika sudah 08, biarkan
        elseif (substr($phone, 0, 2) === '08') {
            // do nothing
        }

        // Jika diawali angka 8 langsung (misal: 812xxxx), tambahkan 0 di depan
        elseif (substr($phone, 0, 1) === '8') {
            $phone = '0' . $phone;
        }

        return $phone;
    }


    public function export($type,$year,$village)
    {
        $data = [
            'title'     => "Export Data Pelanggan",
            'data'      => $this->CustomerModel->getExportData($year,$village),
            'type'      => $type,
            'year'      => $year,
        ];
        

        $userId = session()->get('id');
        $nameUser = session()->get('name');
        insertLog("Customer","Print","User $nameUser berhasil mencetak data pelanggan",$userId);

        return  view('app/customer/export/customer-export', $data);

    }

    public function getPaymentYear()
    {

        $request = json_decode(json_encode($this->request->getPOST()));

        $this->CustomerModel->select('tbl_customer.id, tbl_package.name AS package_name, tbl_package.price');
        $this->CustomerModel->join('tbl_package',' tbl_package.id=tbl_customer.package_id');
        $customer = $this->CustomerModel->find($request->id);

        $customer->pays = [];
        $month = 1;
        while (true) {
            
            $monthName = $month;
            if($month<10){
                $monthName = '0'.$month;
            }
            $this->PaymentModel->select('SUM(total) AS total');
            $this->PaymentModel->where('customer_id',$customer->id);
            $this->PaymentModel->where('MONTH(date)',$monthName);
            $this->PaymentModel->where('YEAR(date)',$request->year);
            $this->PaymentModel->groupBy('customer_id');
            $pay = $this->PaymentModel->first();

            if(empty((array)$pay)){
                $customer->pays[] = [
                    'have'      => false,
                    'total'     => $customer->price,
                    'month'     => $month,
                    'monthName'     => $this->_getMonthIndo($month)
                ];
            }else{
                $customer->pays[] = [
                    'have'      => true,
                    'total'     => $pay->total,
                    'month'     => $month,
                    'monthName'     => $this->_getMonthIndo($month)
                ];
            }


            if($month>=12){
                break;
            }

            $month++;

        }

        return $this->response->setJSON([
            'code'      => 200,
            'success'   => true,
            'data'      => $customer
        ]);



    }



    private function _getMonthIndo($monthNumber) {
        $months = [
            1 => 'Januari',
            2 => 'Februari',
            3 => 'Maret',
            4 => 'April',
            5 => 'Mei',
            6 => 'Juni',
            7 => 'Juli',
            8 => 'Agustus',
            9 => 'September',
            10 => 'Oktober',
            11 => 'November',
            12 => 'Desember'
        ];

        return $months[(int)$monthNumber] ?? 'Invalid';
    }



    public function getAllCustomerName()
    {
        $page  = $this->request->getPOST('page') ? $this->request->getPOST('page') - 1 : 0;
        $limit = $this->request->getPOST('limit') ? $this->request->getPOST('limit') : 30;
        $parentId = $this->request->getPOST('parentId') ? $this->request->getPOST('parentId') : null;

        $this->CustomerModel->name          = $this->request->getPOST('name');
        $this->CustomerModel->limit         = $limit;
        $this->CustomerModel->parentId      = $parentId;
        $this->CustomerModel->start         = ($page * $limit);

        echo $this->CustomerModel->getAllCustomerName();
    }


}

