<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\CustomerModel;
use App\Models\UserModel;
use CodeIgniter\Shield\Entities\User;
use CodeIgniter\Shield\Models\UserIdentityModel;

class CustomerController extends BaseController
{
    protected $userModel;
    protected $customerModel;
    protected $authModel;

    public function __construct()
    {
        $this->userModel = new userModel();
        $this->customerModel = new CustomerModel();
        $this->authModel = new UserIdentityModel();
    }

    public function index()
    {
        $data['title'] = 'Customer';
        $data['data'] = $this->customerModel->orderBy('created_at', 'desc')->findAll();
        return view('customer/index', $data);
    }

    public function create()
    {
        helper(['form']);
        $request = $this->request;

        if ($this->request->getMethod() == 'POST') {
            // Aturan validasi
            $rules = [
                'nama'         => 'required|min_length[3]|max_length[255]',
                'username'          => 'required|min_length[3]|max_length[30]|is_unique[users.username]',
                'password'          => 'required|min_length[8]|max_length[255]',
                'password_confirm'  => 'required|matches[password]',
                'telepon'             => 'required|min_length[10]|max_length[20]|numeric',
            ];

            $user = $this->customerModel->findAll();
            if (!$this->validate($rules)) {
                return view('customer/index', [
                    'title'      => 'Customer',
                    'data'       => $user,
                    'validation' =>  $this->validator
                ]);
            }

            $CustomerModal = new \App\Models\CustomerModel();

            $CustomerModal->insert([
                'nama' => $this->request->getPost('nama'),
                'username' => $this->request->getPost('username'),
                'telepon'     => $this->request->getPost('telepon')
            ]);
            $NewCustomerId = $CustomerModal->getInsertID();

            $usersModel = new \App\Models\UserModel();

            $usersModel->insert([
                'name' => $this->request->getPost('nama'),
                'username' => $this->request->getPost('username'),
                'telepon'     => $this->request->getPost('telepon'),
                'image'     => 'assets/img/avatar4.png',
                'role'     => 'customer',
                'user_id'      => $NewCustomerId
            ]);
            $newUserId = $usersModel->getInsertID();

            $identityModel = new UserIdentityModel();

            $identityModel->insert([
                'user_id' => $newUserId,
                'type' => 'email_password',
                'secret' => $this->request->getPost('username'),
                'secret2' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

            if ($identityModel->affectedRows() > 0) {
                session()->setFlashdata('success', 'Data Customer Berhasil Ditambahkan');
                return redirect()->to('/customer');
            }

            session()->setFlashdata('error', 'Terjadi kesalahan, coba lagi.');
            return redirect()->to('/customer');
        }

        return view('customer/create', ['title' => 'Tambah Customer']);
    }

    public function edit($id)
    {
        helper(['form']);
        $request = $this->request;

        if ($this->request->getMethod() == 'POST') {
            $rules = [
                'nama'              => 'required|min_length[3]|max_length[255]',
                'username'          => 'required|min_length[3]|max_length[30]|is_unique[tabel_customer.username, id_customer, ' . $id . ']',
                'telepon'             => 'required|min_length[10]|max_length[20]|numeric',
            ];

            $user = $this->customerModel->find($id);
            if (!$this->validate($rules)) {
                return view('customer/edit', [
                    'title'      => 'Edit Customer',
                    'data'       => $user,
                    'validation' =>  $this->validator
                ]);
            }

            $dataUpdate = [
                'nama' => $this->request->getPost('nama'),
                'username'    => $this->request->getPost('username'),
                'telepon'     => $this->request->getPost('telepon'),
            ];

            $dataUpdateUsername = [
                'name' => $this->request->getPost('nama'),
                'username'    => $this->request->getPost('username'),
            ];

            $this->customerModel->update($id, $dataUpdate);
            $this->userModel->where('user_id', $id)->where('role', 'customer')->update(null, $dataUpdateUsername);

            return redirect()->to('customer/edit/' . $id)->with('success', 'Edit Customer Berhasil');
        }

        $data['title'] = 'Edit Customer';
        $data['data'] = $this->customerModel->find($id);
        return view('customer/edit', $data);
    }

    // DELETE: Menghapus data
    public function delete($id)
    {
        $this->userModel->where('user_id', $id)->where('role', 'customer')->delete();
        $this->customerModel->delete($id);
        return redirect()->to('/customer')->with('success', 'Data Customer berhasil dihapus.');
    }

    /**
     * AJAX: Create customer from modal (async)
     */
    public function create_ajax()
    {
        helper(['form']);

        // Validasi input (tanpa username & password karena auto-generate)
        $rules = [
            'nama' => [
                'label' => 'Nama',
                'rules' => 'is_unique[tabel_customer.nama]|required|min_length[3]|max_length[255]',
                'errors' => [
                    'required' => 'Nama tidak boleh kosong',
                    'is_unique' => "Nama telah terdaftar pada sistem",
                    'min_length' => "Nama minimal 3 karakter",
                    'max_length' => 'Nama Maksimal 255 Karakter'
                ],
            ],
            // 'nama'              => 'is_unique[tabel_customer.nama]|required|min_length[3]|max_length[255]',
            'no_telp'           => 'required|min_length[10]|max_length[20]',
            'email'             => 'permit_empty|valid_email',
            // 'username'          => 'required|min_length[3]|max_length[30]|is_unique[users.username]',
            'alamat'            => 'permit_empty|max_length[500]'
        ];

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

        try {
            // Generate username dari nama (lowercase, tanpa spasi)
            $nama = $this->request->getPost('nama');
            $noTelp = $this->request->getPost('no_telp');
            $username = $this->request->getPost('username');

            // Generate username: namaAwallowercaseNoSpace + 4digitTerakhirTelepon
            // $namaClean = strtolower(str_replace(' ', '', explode(' ', $nama)[0]));
            // $telp4digit = substr($noTelp, -4);
            // $baseUsername = $namaClean . $telp4digit;

            // Cek apakah username sudah ada, jika ada tambahkan angka random
            // $username = $baseUsername;
            // $counter = 1;
            // while ($this->userModel->where('username', $username)->first()) {
            //     $username = $baseUsername . $counter;
            //     $counter++;
            // }

            // Generate password: 8 karakter pertama dari nomor telepon
            $generatedPassword = substr($username, 0, 8);

            // Insert ke tabel_customer
            $customerData = [
                'nama'     => $nama,
                'username' => $username,
                'telepon'  => $noTelp,
            ];

            $this->customerModel->insert($customerData);
            $newCustomerId = $this->customerModel->getInsertID();

            // Insert ke users table
            $usersModel = new \App\Models\UserModel();
            $usersModel->insert([
                'name'     => $nama,
                'username' => $username,
                'telepon'  => $noTelp,
                'image'    => 'assets/img/avatar4.png',
                'role'     => 'customer',
                'user_id'  => $newCustomerId
            ]);
            $newUserId = $usersModel->getInsertID();

            // Insert ke auth_identities (Shield)
            $identityModel = new UserIdentityModel();
            $identityModel->insert([
                'user_id'    => $newUserId,
                'type'       => 'email_password',
                'secret'     => $username,
                'secret2'    => password_hash($generatedPassword, PASSWORD_DEFAULT),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);

            return $this->response->setJSON([
                'success' => true,
                'message' => 'Customer berhasil ditambahkan',
                'data' => [
                    'id_customer' => $newCustomerId,
                    'nama'        => $nama,
                    'no_telp'     => $noTelp,
                    'username'    => $username,
                    'password'    => $generatedPassword
                ]
            ]);
        } catch (\Exception $e) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Terjadi kesalahan: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * AJAX: Search customer for autocomplete
     */
    public function search()
    {
        $query = $this->request->getGet('q');

        if (strlen($query) < 2) {
            return $this->response->setJSON([]);
        }

        $customers = $this->customerModel
            ->like('nama', $query)
            ->orLike('telepon', $query)
            ->orLike('username', $query)
            ->findAll(20);

        return $this->response->setJSON($customers);
    }
}
