<?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 Payment extends BaseController
{

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

    public function __construct()
    {

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

    public function index()
    {
    
        haveAccess(5,"is_read", session()->get('role_id'));

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

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

    }

    public function add()
    {

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

        $data = [
            'title'     => "Tambah Pembayaran",
        ];
        
        return view('app/payment/add/header').
        view('app/payment/add/css-style').
        view('app/payment/add/payment-add-css', $data) .
        view('app/payment/add/payment-add', $data) .
        view('app/payment/add/payment-add-js', $data) .
        view('app/payment/add/js-script').
        view('app/payment/add/footer');
    }

    public function getAllDataCustomer()
    {

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

        $this->CustomerModel->select('tbl_customer.*, 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);

        try {

            $customer->village_name = $this->AreaModel->find($customer->village_id)->name;
            $customer->subdistrict_name = $this->AreaModel->find($customer->subdistrict_id)->name;
        } catch (Exception $e) {
            $customer->village_name = "-";
            $customer->subdistrict_name = "-";
        }

        $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)',date('Y'));
            $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
        ]);


    }


    public function savePay()
    {

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

        $request = json_decode(json_encode($this->request->getPOST()));
        if(isset($request->month)&&!empty($request->month)){
            sort($request->month, SORT_NUMERIC);
        }

        if(empty($request->month)){
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Silahkan tentukan bulan yang ingin di bayarkan"
            ]);
        }


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

        foreach ($request->month as $month) {

            $monthName = $month;
            if($month<10){
                $monthName = "0".$month;
            }

            $this->PaymentModel->select('id');
            $this->PaymentModel->where('customer_id',$request->id);
            $this->PaymentModel->where('MONTH(date)',$monthName);
            $this->PaymentModel->where('YEAR(date)',date('Y'));
            $hasPay = $this->PaymentModel->findAll();
            // print_r($hasPay); die;
            if(count($hasPay)>0){
                continue;
            }

            $data = [
                'customer_id'       => $request->id,
                'date'              => date('Y-').$monthName.'-20',
                'package_id'        => $customer->package_id,
                'package_name'      => $customer->package_name,
                'package_price'     => $customer->package_price,
                'total'             => $customer->package_price,
                'created_by'        => session()->get('id'),
                'created_at'        => date('Y-m-d H:i:s')
            ];


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

            $customer->pays[] = $data;

        }

        
        $userId = session()->get('id');
        $nameUser = session()->get('name');
        insertLog("Payment","Create","User $nameUser berhasil membuat data pembayaran $customer->name",$userId);

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


    }


    public function getAllData()
    {

        $this->PaymentModel->draw     = $this->request->getPOST('draw');
        $this->PaymentModel->start    = $this->request->getPOST('start');
        $this->PaymentModel->limit    = $this->request->getPOST('length');
        $this->PaymentModel->search   = $this->request->getPOST('search')['value'];
        $this->PaymentModel->columns  = $this->request->getPOST('columns');
        $this->PaymentModel->order    = $this->request->getPOST('order');
        $this->PaymentModel->month    = $this->request->getPOST('month');
        $this->PaymentModel->village    = $this->request->getPOST('village');
        $this->PaymentModel->customer    = $this->request->getPOST('customer');

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


    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 detail($id = null)
    {

        haveAccess(5,"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
        ];

        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()
    {


        $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'         => $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"
            ]);
        }

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


    }


    public function getAllDataPayCustomer()
    {
        
        $this->PaymentModel->limitData     = $this->request->getPOST('limit');
        $this->PaymentModel->startData    = $this->request->getPOST('start');
        $this->PaymentModel->keyword    = $this->request->getPOST('keyword');
        $this->PaymentModel->packages   = $this->request->getPOST('packages');
        $this->PaymentModel->subdistricts  = $this->request->getPOST('subdistricts');
        $this->PaymentModel->villages    = $this->request->getPOST('villages');
        $this->PaymentModel->startDate    = $this->request->getPOST('startDate');
        $this->PaymentModel->endDate    = $this->request->getPOST('endDate');

        echo $this->PaymentModel->getAllDataPayCustomer();
    }

    public function delete()
    {

        $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->PaymentModel->where('id', $request->id);
        if(!$this->PaymentModel->delete()){

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

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

    }


    public function edit($id = null)
    {


        $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()
    {

        

        $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'         => $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"
            ]);
        }

        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;
    }


}

