<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Gym extends CI_Controller {

	function __construct(){
		parent::__construct();
		$this->load->helper('url');
		$this->load->model('gym_model');
	}

	public function index(){
		//load session library
		$this->load->library('session');
		$this->session->unset_userdata('user');
		$this->load->view('login');		
	}

	public function loginAction(){
		//load session library
		$this->load->library('session');
		$data['user'] = $this->gym_model->login($_POST['email'],$_POST['password']);
		if(!empty($data['user']) and $data['user'][0]['status']=='Active'){
			$this->session->set_userdata('user',$data['user']);
			$_SESSION['user'][0]['photo'] = !empty($_SESSION['user'][0]['photo']) ? $_SESSION['user'][0]['photo'] : 'assets/src/assets/img/logo.svg';
			$this->session->set_flashdata("success","<b>Selamat Datang ".$_SESSION['user'][0]['name']."</b> di aplikasi GYM!");
			redirect('gym/home');						
		}else if(!empty($data['user']) and $data['user'][0]['status']=='Non-Active'){
			$this->session->set_flashdata("error","<b>Gagal</b>, mohon maaf status member TIDAK AKTIF, pastikan status member anda aktif!");
			redirect('/');
		}else{
			$this->session->set_flashdata("error","<b>Gagal</b>, mohon maaf email atau sandi anda salah, pastikan email dan kata sandi anda terisi dengan benar!");
			redirect('/');
		}				
	}
	
	public function home(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$this->load->view('home');	
		}else{
			redirect('/');
		}	
	}

	public function akses(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$data['tot_active'] =count($this->gym_model->getData("user","status='Active' and role_id != 6"));
			$data['tot_nonactive'] =count($this->gym_model->getData("user","status='Non-Active' and role_id != 6"));
			$data['user'] =$this->gym_model->getDataUser();			
			$data['role'] =$this->gym_model->getData("role","status_role='Active'");
			$data['location'] =$this->gym_model->getData("location","status_location='Active'");
			$this->load->view('akses',$data);	
		}else{
			redirect('/');
		}	
	}

	public function adduser(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$data['role'] =$this->gym_model->getData("role","status_role='Active'");
			$data['location'] =$this->gym_model->getData("location","status_location='Active'");
			$this->load->view('adduser',$data);	
		}else{
			redirect('/');
		}	
	}

	public function insertuser(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){			
			$data['cek_email'] =$this->gym_model->getData("user","email='".$_POST['email']."'");
			if(empty($data['cek_email'])){
				$nama="";
				if(!empty($_FILES['filepond']['name'])){
					$ext = pathinfo($_FILES['filepond']['name'], PATHINFO_EXTENSION);
					$nama = $_POST['name']."_".$_POST['phone'].".".$ext;
					$file_tmp = $_FILES['filepond']['tmp_name'];
					$location="C:\\xampp\htdocs\gym\upload\user\\".$nama;
					move_uploaded_file($file_tmp, $location);
					$dataPost = array(
						'name'=> $_POST['name'],
						'address'=> $_POST['address'],
						'role_id'=> $_POST['role_id'],
						'phone'=> $_POST['phone'],
						'location_id'=> $_POST['location_id'],
						'email'=> $_POST['email'],
						'sex'=> $_POST['sex'],
						'photo'=> "upload\user\\".$nama,
						'status'=> 'Non-Active'
					);	
				}else{
					$dataPost = array(
						'name'=> $_POST['name'],
						'address'=> $_POST['address'],
						'role_id'=> $_POST['role_id'],
						'phone'=> $_POST['phone'],
						'location_id'=> $_POST['location_id'],
						'email'=> $_POST['email'],
						'sex'=> $_POST['sex'],
						'status'=> 'Non-Active'
					);	
				}
								
				$this->gym_model->insert("user",$dataPost);
				$this->session->set_flashdata("success","<b>Berhasil</b> User Baru Berhasil ditambahkan!");
			}else{
				$this->session->set_flashdata("error","<b>Gagal</b> User Sudah Ada / Email Sudah Terdaftar!");
			}			
			redirect('gym/akses');
		}else{
			redirect('/');
		}	
	}

	public function updateuser(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$data['cek_email'] =$this->gym_model->getData("user","email='".$_POST['email']."' and user_id !='".$_POST['user_id']."'");
			if(empty($data['cek_email'])){
				$nama="";
				if(!empty($_FILES['photo']['name'])){
					$ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
					$nama = $_POST['name']."_".$_POST['phone'].".".$ext;
					$file_tmp = $_FILES['photo']['tmp_name'];
					$location="C:\\xampp\htdocs\gym\upload\user\\".$nama;
					move_uploaded_file($file_tmp, $location);

					$dataPost = array(
						'name'=> $_POST['name'],
						'address'=> $_POST['address'],
						'role_id'=> $_POST['role_id'],
						'phone'=> $_POST['phone'],
						'location_id'=> $_POST['location_id'],
						'email'=> $_POST['email'],
						'sex'=> $_POST['sex'],
						'photo'=> "upload\user\\".$nama,
						'status'=> $_POST['status']
					);	
				}else{
					$dataPost = array(
						'name'=> $_POST['name'],
						'address'=> $_POST['address'],
						'role_id'=> $_POST['role_id'],
						'phone'=> $_POST['phone'],
						'location_id'=> $_POST['location_id'],
						'email'=> $_POST['email'],
						'sex'=> $_POST['sex'],
						'status'=> $_POST['status']
					);	
				}								
				$this->gym_model->update("user","user_id",$dataPost,$_POST['user_id']);
				$this->session->set_flashdata("success","<b>Berhasil</b> data User Berhasil diubah!");
			}else{
				$this->session->set_flashdata("error","<b>Gagal</b> User Sudah Ada / Email Sudah Terdaftar!");
			}			
			redirect('gym/akses');
		}else{
			redirect('/');
		}	
	}

	public function deleteuser(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$this->gym_model->delete("user","user_id",$_POST['user_id']);			
			$this->session->set_flashdata("success","<b>Berhasil</b> data User Berhasil dihapus!");
			redirect('gym/akses');
		}else{
			redirect('/');
		}	
	}

	public function member(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$data['tot_active'] =count($this->gym_model->getData("user","status='Active' and role_id = 6"));
			$data['tot_nonactive'] =count($this->gym_model->getData("user","status='Non-Active' and role_id = 6"));
			$data['user'] =$this->gym_model->getDataMember();			
			$this->load->view('member',$data);	
		}else{
			redirect('/');
		}	
	}

	public function addmember(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$this->load->view('addmember');	
		}else{
			redirect('/');
		}	
	}

	public function insertmember(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$data['cek_email'] =$this->gym_model->getData("user","email='".$_POST['email']."'");
			if(empty($data['cek_email'])){
				$nama="";
				if(!empty($_FILES['filepond']['name'])){
					$ext = pathinfo($_FILES['filepond']['name'], PATHINFO_EXTENSION);
					$nama = $_POST['name']."_".$_POST['phone'].".".$ext;
					$file_tmp = $_FILES['filepond']['tmp_name'];
					$location="C:\\xampp\htdocs\gym\upload\user\\".$nama;
					move_uploaded_file($file_tmp, $location);

					$dataPost = array(
						'name'=> $_POST['name'],
						'address'=> $_POST['address'],
						'role_id'=> 6,
						'phone'=> $_POST['phone'],
						'location_id'=> $_SESSION['user'][0]['location_id'],
						'email'=> $_POST['email'],
						'job'=> $_POST['job'],
						'sex'=> $_POST['sex'],
						'photo'=> "upload\user\\".$nama,
						'status'=> 'Non-Active'
					);
				}else{
					$dataPost = array(
						'name'=> $_POST['name'],
						'address'=> $_POST['address'],
						'role_id'=> 6,
						'phone'=> $_POST['phone'],
						'location_id'=> $_SESSION['user'][0]['location_id'],
						'email'=> $_POST['email'],
						'job'=> $_POST['job'],
						'sex'=> $_POST['sex'],
						'status'=> 'Non-Active'
					);
				}
									
				$this->gym_model->insert("user",$dataPost);$this->session->set_flashdata("success","<b>Berhasil</b> Member Baru Berhasil ditambahkan!");
			}else{
				$this->session->set_flashdata("error","<b>Gagal</b> Member Sudah Ada / Email Sudah Terdaftar!");
			}				
			redirect('gym/member');
		}else{
			redirect('/');
		}	
	}

	public function updatemember(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$data['cek_email'] =$this->gym_model->getData("user","email='".$_POST['email']."' and user_id !='".$_POST['user_id']."'");
			if(empty($data['cek_email'])){
				$nama="";
				if(!empty($_FILES['photo']['name'])){
					$ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
					$nama = $_POST['name']."_".$_POST['phone'].".".$ext;
					$file_tmp = $_FILES['photo']['tmp_name'];
					$location="C:\\xampp\htdocs\gym\upload\user\\".$nama;
					move_uploaded_file($file_tmp, $location);

					$dataPost = array(
						'name'=> $_POST['name'],
						'address'=> $_POST['address'],
						'phone'=> $_POST['phone'],
						'email'=> $_POST['email'],
						'job'=> $_POST['job'],
						'sex'=> $_POST['sex'],
						'photo'=> "upload\user\\".$nama
					);	
				}else{
					$dataPost = array(
						'name'=> $_POST['name'],
						'address'=> $_POST['address'],
						'phone'=> $_POST['phone'],
						'job'=> $_POST['job'],
						'sex'=> $_POST['sex'],
						'email'=> $_POST['email']
					);	
				}								
				$this->gym_model->update("user","user_id",$dataPost,$_POST['user_id']);
				$this->session->set_flashdata("success","<b>Berhasil</b> data Member Berhasil diubah!");
			}else{
				$this->session->set_flashdata("error","<b>Gagal</b> Member Sudah Ada / Email Sudah Terdaftar!");
			}			
			redirect('gym/member');
		}else{
			redirect('/');
		}	
	}

	public function deletemember(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$this->gym_model->delete("user","user_id",$_POST['user_id']);
			$this->session->set_flashdata("success","<b>Berhasil</b> data Member Berhasil dihapus!");
			redirect('gym/member');
		}else{
			redirect('/');
		}	
	}

	public function detilmember($id){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			include APPPATH . 'third_party/phpqrcode/qrlib.php';
			$token = md5($id.'SECRET123');
			$url = base_url(
				'absensi?id='.$id.'&token='.$token
			);
			// folder simpan qr
			$folder = FCPATH . 'assets/qrcode/';
			// buat folder jika belum ada
			if (!file_exists($folder)) {
				mkdir($folder, 0777, true);
			}
			// nama file qr
			$file_name = 'user_'.$id.'.png';
			$file_path = $folder.$file_name;
			// generate qr code
			QRcode::png(
				$url,
				$file_path,
				QR_ECLEVEL_H,
				10,
				2
			);
			// kirim data ke view
			$data['qr_image'] = base_url('assets/qrcode/'.$file_name);
			$data['current'] =$this->gym_model->getData("membership","user_id='".$id."' order by end_date desc limit 0,1");
			$data['history'] =$this->gym_model->getData("membership","user_id='".$id."' order by end_date desc limit 0,3");	
			$data['detilsession'] =$this->gym_model->getDataSessionMember($id);
			$data['detil'] =$this->gym_model->getDataById($id);
			$this->load->view('detilmember',$data);	
		}else{
			redirect('/');
		}	
	}

	public function absensi(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$id_user = $this->input->get('id');
			$token   = $this->input->get('token');
			if($token == md5($id_user.'SECRET123')){
				echo "QR Valid";
			}else{
				echo "QR Tidak Valid";
			}
		}else{
			redirect('/');
		}	
	}

	public function tambahBulan($tanggal, $jumlahBulan) {
		// Validasi format tanggal
		$d = DateTime::createFromFormat('Y-m-d', $tanggal);
		if (!$d || $d->format('Y-m-d') !== $tanggal) {
			return null; // Format tanggal tidak valid
		}

		try {
			// Buat objek DateTime
			$date = new DateTime($tanggal);

			// Jika jumlah bulan negatif, gunakan sub()
			if ($jumlahBulan >= 0) {
				$date->add(new DateInterval("P{$jumlahBulan}M"));
			} else {
				$date->sub(new DateInterval("P" . abs($jumlahBulan) . "M"));
			}

			return $date->format('Y-m-d');
		} catch (Exception $e) {
			return null; // Jika terjadi error
		}
	}

	public function perpanjang_member(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$hasil = $this->tambahBulan($_POST['start_date'], $_POST['paket']);
			$dataPost = array(
				'user_id'=> $_POST['user_id'],
				'paket'=> $_POST['paket'],
				'start_date'=> $_POST['start_date'],
				'end_date'=> $hasil,
				'nominal'=> $_POST['nominal'],
				'note'=> $_POST['note']
			);					
			$this->gym_model->insert("membership",$dataPost);

			$dataPostFinance = array(
				'name_finance'=> "Perpanjang Member ID".$_POST['user_id']." - Paket ".$_POST['paket']." Bulan",
				'type'=> 'PEMASUKAN MEMBER',
				'nominal'=> $_POST['nominal']
			);	
			$this->gym_model->insert("finance",$dataPostFinance);	

			$end   = strtotime($hasil);
            $today = strtotime(date('Y-m-d'));
			$sisaHari = ceil(($end - $today) / 86400);

			if($sisaHari>0){
			$dataPostUpdate = array(
						'status'=> 'Active',						
						'exp_date'=> $hasil
					);								
			$this->gym_model->update("user","user_id",$dataPostUpdate,$_POST['user_id']);
			}			
			redirect("gym/detilmember/".$_POST['user_id']);
		}else{
			redirect('/');
		}	
	}

	public function coach(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$data['perempuan'] =count($this->gym_model->getData("user","sex='P' and role_id = 7"));
			$data['laki'] =count($this->gym_model->getData("user","sex='L' and role_id = 7"));
			$data['user'] =$this->gym_model->getDataCoach();	
			$this->load->view('coach',$data);	
		}else{
			redirect('/');
		}	
	}

	public function addcoach(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$this->load->view('addcoach');	
		}else{
			redirect('/');
		}	
	}

	public function insertcoach(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$data['cek_email'] =$this->gym_model->getData("user","email='".$_POST['email']."'");
			if(empty($data['cek_email'])){
				$nama="";
				if(!empty($_FILES['filepond']['name'])){
					$ext = pathinfo($_FILES['filepond']['name'], PATHINFO_EXTENSION);
					$nama = $_POST['name']."_".$_POST['phone'].".".$ext;
					$file_tmp = $_FILES['filepond']['tmp_name'];
					$location="C:\\xampp\htdocs\gym\upload\user\\".$nama;
					move_uploaded_file($file_tmp, $location);

					$dataPost = array(
						'name'=> $_POST['name'],
						'address'=> $_POST['address'],
						'role_id'=> 7,
						'phone'=> $_POST['phone'],
						'location_id'=> $_SESSION['user'][0]['location_id'],
						'email'=> $_POST['email'],
						'sex'=> $_POST['sex'],
						'photo'=> "upload\user\\".$nama,
						'status'=> 'Active'
					);	
				}else{
					$dataPost = array(
						'name'=> $_POST['name'],
						'address'=> $_POST['address'],
						'role_id'=> 7,
						'phone'=> $_POST['phone'],
						'location_id'=> $_SESSION['user'][0]['location_id'],
						'email'=> $_POST['email'],
						'sex'=> $_POST['sex'],
						'status'=> 'Active'
					);	
				}								
				$this->gym_model->insert("user",$dataPost);$this->session->set_flashdata("success","<b>Berhasil</b> Coach Baru Berhasil ditambahkan!");
			}else{
				$this->session->set_flashdata("error","<b>Gagal</b> Coach Sudah Ada / Email Sudah Terdaftar!");
			}				
			redirect('gym/coach');
		}else{
			redirect('/');
		}	
	}

	public function updatecoach(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$data['cek_email'] =$this->gym_model->getData("user","email='".$_POST['email']."' and user_id !='".$_POST['user_id']."'");
			if(empty($data['cek_email'])){
				$nama="";
				if(!empty($_FILES['photo']['name'])){
					$ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
					$nama = $_POST['name']."_".$_POST['phone'].".".$ext;
					$file_tmp = $_FILES['photo']['tmp_name'];
					$location="C:\\xampp\htdocs\gym\upload\user\\".$nama;
					move_uploaded_file($file_tmp, $location);

					$dataPost = array(
						'name'=> $_POST['name'],
						'address'=> $_POST['address'],
						'phone'=> $_POST['phone'],
						'email'=> $_POST['email'],
						'sex'=> $_POST['sex'],
						'photo'=> "upload\user\\".$nama
					);	
				}else{
					$dataPost = array(
						'name'=> $_POST['name'],
						'address'=> $_POST['address'],
						'phone'=> $_POST['phone'],
						'sex'=> $_POST['sex'],
						'email'=> $_POST['email']
					);	
				}								
				$this->gym_model->update("user","user_id",$dataPost,$_POST['user_id']);
				$this->session->set_flashdata("success","<b>Berhasil</b> data Coach Berhasil diubah!");
			}else{
				$this->session->set_flashdata("error","<b>Gagal</b> Coach Sudah Ada / Email Sudah Terdaftar!");
			}			
			redirect('gym/coach');
		}else{
			redirect('/');
		}	
	}

	public function deletecoach(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$this->gym_model->delete("user","user_id",$_POST['user_id']);
			$this->session->set_flashdata("success","<b>Berhasil</b> data Coach Berhasil dihapus!");
			redirect('gym/coach');
		}else{
			redirect('/');
		}	
	}

	public function detilcoach($id){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$data['detil'] =$this->gym_model->getDataById($id);			
			$data['member'] =$this->gym_model->getData("user","status='Active' and role_id = 6");			
			$data['coachmember'] =$this->gym_model->getDataByCoachMemberId($id);			
			$data['coachvisit'] =$this->gym_model->getDataByCoachVisitId($id);
			$this->load->view('detilcoach',$data);	
		}else{
			redirect('/');
		}	
	}
	
	public function addclientcoach(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$dataPost = array(
					'coach_id'=> $_POST['coach_id'],
					'member_id'=> $_POST['member_id'],
					'member_package'=> $_POST['member_package'],
					'member_schedule'=> $_POST['member_schedule'],
					'member_notes'=> $_POST['member_notes'],
					'visitor_name'=> $_POST['visitor_name'],
					'visitor_phone'=> $_POST['visitor_phone'],
					'visitor_gender'=> $_POST['visitor_gender'],
					'visit_type'=> $_POST['visit_type'],
					'visit_date'=> $_POST['visit_date'],
					'visitor_target_weight'=> $_POST['visitor_target_weight'],
					'visitor_notes'=> $_POST['visitor_notes'],
					'nominal'=> $_POST['nominal']
				);
								
			$this->gym_model->insert("clientcoach",$dataPost);

			$dataPostFinance = array(
				'name_finance'=> "Coaching Coach ID".$_POST['coach_id'],
				'type'=> 'PEMASUKAN COACHING',
				'nominal'=> $_POST['nominal']
			);	
			$this->gym_model->insert("finance",$dataPostFinance);	

			$this->session->set_flashdata("success","<b>Berhasil</b> Clinet Baru Berhasil ditambahkan!");
			redirect("gym/detilcoach/".$_POST['coach_id']);
		}else{
			redirect('/');
		}	
	}

	public function addsessions(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$dataPost = array(
					'clientcoach_id'=> $_POST['clientcoach_id'],
					'session_date'=> $_POST['session_date'],
					'duration'=> $_POST['duration'],
					'training_type'=> $_POST['training_type'],
					'workout_notes'=> $_POST['workout_notes'],
					'weight'=> $_POST['weight'],
					'client_condition'=> $_POST['client_condition'],
					'coach_notes'=> $_POST['coach_notes']
				);
								
			$this->gym_model->insert("sessionscoach",$dataPost);
			$this->session->set_flashdata("success","<b>Berhasil</b> Sesi Latihan Baru Berhasil ditambahkan!");
			redirect("gym/detilcoach/".$_POST['coach_id']);
		}else{
			redirect('/');
		}	
	}

	public function presensi(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$data['member'] =count($this->gym_model->getData("presensi","member_id!=0"));
			$data['kunjungan'] =count($this->gym_model->getData("presensi","member_id=0"));
			$data['presensi'] =$this->gym_model->getDataPresensi();
			$this->load->view('presensi',$data);	
		}else{
			redirect('/');
		}	
	}

	public function searchmember()
	{
		$keyword = $this->input->post('keyword');

		$this->db->select('user_id,name,phone,photo');
		$this->db->from('user');
		$this->db->where('role_id', '6');
		$this->db->where('status', 'Active');

		$this->db->group_start();
		$this->db->like('name', $keyword);
		$this->db->or_like('phone', $keyword);
		$this->db->group_end();

		$this->db->limit(10);

		$query = $this->db->get()->result_array();

		echo json_encode($query);
	}

	public function addpresensi(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$dataPost = array(
				'member_id'=> $_POST['member_id'],
				'visitor_name'=> $_POST['visitor_name'],
				'visitor_phone'=> $_POST['visitor_phone'],
				'visitor_gender'=> $_POST['visitor_gender'],
				'visit_type'=> $_POST['visit_type'],
				'nominal'=> $_POST['nominal']
			);
			if(!empty($_POST['visitor_name']) or !empty($_POST['visitor_phone'])){
				$dataPostFinance = array(
					'name_finance'=> "Kunjungan",
					'type'=> 'PEMASUKAN KUNJUNGAN',
					'nominal'=> $_POST['nominal']
				);	
				$this->gym_model->insert("finance",$dataPostFinance);	
			}					
			$this->gym_model->insert("presensi",$dataPost);
			$this->session->set_flashdata("success","<b>Berhasil</b> Presensi Berhasil ditambahkan!");
			redirect("gym/presensi");
		}else{
			redirect('/');
		}	
	}

	public function report(){
		//load session library
		$this->load->library('session');
		if($this->session->userdata('user')){
			$data['tot'] =$this->gym_model->getTotalFinance();
			$data['detil'] =$this->gym_model->getData("finance","1=1");
			$this->load->view('report',$data);	
		}else{
			redirect('/');
		}	
	}
}
