<?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    
    class Nomorator extends CI_Controller {
        
        public function __construct() {
            parent::__construct();
            cek_session_login();
            $this->load->library('generate_nomor');
            $this->title = info()['title']; 
            $this->demo = info()['demo']; 
            $this->level = $this->session->level; 
        }
        
        public function index() {
            $data['title'] ='Nomorator | '.$this->title;
            $data['judul'] = 'Nomorator';
            $data['demo'] = $this->demo;
            $this->template->load('main/themes','nomorator/view_index',$data);
        }
        
        public function generate_numbers() {
            $titik = intval($this->input->post('jumlah_titik'));
            $digit = intval($this->input->post('jumlah_digit'));
            $rim = intval($this->input->post('rim'));
            $awal = intval($this->input->post('awal'));
            $jml_buku = intval($this->input->post('jml_buku'));
            $akhir = $awal + $rim * $titik - 1;
            $prefix = $this->input->post('awalan'); // Awalan yang ingin Anda tambahkan
            $nama_file = $this->input->post('nama_file'); // Awalan yang ingin Anda tambahkan
            $save_file = $this->input->post('save_file'); // Awalan yang ingin Anda tambahkan
            $config = array(
            array(
            'field' => 'nama_file',
            'label' => 'Nama File',
            'rules' => 'required|trim|max_length[20]',
            'errors' => array(
            'required' => '%s. Harus di isi',
            'max_length' => '%s maksimal 20 digit.',
            'is_unique'     => '%s sudah ada.'
            ),
            ),
            
            );
            $this->form_validation->set_rules($config);
            if ($this->form_validation->run() == FALSE) {
				// echo validation_errors();
				$data = array('hasil' => 'error', 'msg' => validation_errors());
                echo json_encode([
                'status' => false,
                'message' => validation_errors(),
                'data' =>generate_random_filename()
                ]);
				} else {
                $data = $this->generate_nomor->generate_dynamic_wadah($titik) . "\n" . $this->generate_nomor->generate_formatted_string($awal, $rim, $titik, $digit, $prefix);
                if($jml_buku > 0){
                    if($this->demo=='Y'){
                        
                        if(empty($prefix)){
                            $data = $this->generate_nomor->potong_data_tanpa_awalan($data);
                            }else{
                            $data = $this->generate_nomor->potong_data($data);
                        }
                        }else{
                        $data =  $data;
                    }
                    }else{
                    if($this->demo=='Y'){
                        if(empty($prefix)){
                            $data = $this->generate_nomor->potong_data_tanpa_awalan($data);
                            }else{
                            $data = $this->generate_nomor->potong_data($data);
                        }
                        }else{
                        $data =  $data;
                    }
                }
                
                if($save_file=='Y'){
                    $this->write_to_file($data,$nama_file);
                }
                
                $this->log_user_info();
                
                echo json_encode([
                'status' => true,
                'message' => "Generated numbers successfully",
                'data' => $data,
                'nama_file' => $nama_file
                ]);
            }
        }
        public function write_to_file($data,$nama_file) {
            $file_path = FCPATH . 'uploads/'.$nama_file.'.txt';
            return file_put_contents($file_path, $data) !== false;
        }
        
       	public function download($file){
            $this->load->helper(array('url','download'));		
            $file_download = $file.'.txt';
            
            force_download('uploads/'.$file_download,NULL);
        }	
        
        private function log_user_info() {
            // Mendapatkan IP pengunjung
            $ip_address = $this->get_client_ip();
            
            // Mendapatkan browser pengunjung
            $browser = $this->agent->browser();
            
            // Nama file log
            $log_file = FCPATH . 'application/logs/log.txt';
            
            // Membaca isi file log
            $log_data = [];
            if (file_exists($log_file)) {
                $log_data = json_decode(file_get_contents($log_file), true);
            }
            
            // Jika IP sudah tercatat, tambahkan kunjungan
            if (isset($log_data[$ip_address])) {
                $log_data[$ip_address]['count']++;
                } else {
                // Jika IP belum tercatat, tambahkan entri baru
                $log_data[$ip_address] = [
                'browser' => $browser,
                'count' => 1,
                'last_visited' => date('Y-m-d H:i:s')
                ];
            }
            
            // Format log dengan IP, browser, dan jumlah kunjungan
            $log_message = json_encode($log_data, JSON_PRETTY_PRINT);
            
            // Menyimpan data ke dalam file log
            if (is_writable($log_file)) {
                file_put_contents($log_file, $log_message);
                } else {
                //echo "Tidak dapat menulis ke file log.";
            }
            
            // Menampilkan jumlah kunjungan IP
            //echo "IP: $ip_address | Browser: $browser | Kunjungan: " . $log_data[$ip_address]['count'];
        }
        
        // Fungsi untuk mendapatkan IP pengunjung yang sebenarnya
        public function get_client_ip() {
            // Mengecek apakah Cloudflare mengirimkan header CF-Connecting-IP
            if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
                // Mengambil IP asli dari header CF-Connecting-IP
                return $_SERVER['HTTP_CF_CONNECTING_IP'];
                } else {
                // Jika tidak, ambil IP dari client secara langsung
                return $this->input->ip_address();
            }
        }
    }
