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

use GuzzleHttp\Client;

class Home extends MY_Controller
{
	protected $per_page;
	public function __construct()
	{
		parent::__construct();
		$this->per_page = 15;
	}

	public function index()
	{

		$layoutView = $this->layouts == 1 ? "frontend/theme_{$this->layouts}/home" : "frontend/home";
		// Check if demo mode is enabled and user hasn't entered the site yet
		if (is_demo() == 1 && !$this->session->userdata('demo_entered')) {
			$data = array();
			$data['settings']  = settings();
			$this->load->view('frontend/demo_landing', $data);
			return;
		}

		if (isset($this->settings['is_landing_page']) && $this->settings['is_landing_page'] == 1) {
			redirect(prep_url($this->settings['landing_page_url']));
			exit();
		}
		$data = array();

		$data['_title'] = lang('home');
		$data['page_title'] = "Home";
		$data['page'] = "Home";
		$data['settings']  = settings();
		$data['main_content'] = $this->load->view($layoutView, $data, TRUE);
		$this->load->view('frontend/index', $data);
	}

	public function step_1()
	{
		$this->init_language();
		$layoutView = $this->layouts == 1 ? "frontend/home_content/theme_{$this->layouts}/step_1" : "frontend/home_content/step_1";
		$data = [];
		$data['settings']  = settings();
		$data['top_8_shop'] = $this->admin_m->top_10_popular_shop();
		$data['top_8_items'] = $this->admin_m->top_8_popular_items();
		$data['how_works'] = $this->common_m->select_with_status_ln('how_it_works');
		$load_data = $this->load->view($layoutView, $data, TRUE);
		echo json_encode(['st' => 1, 'load_data' => $load_data]);
	}


	public function step_2()
	{
		$this->init_language();
		$layoutView = $this->layouts == 1 ? "frontend/home_content/theme_{$this->layouts}/step_2" : "frontend/home_content/step_2";


		$data = [];
		$data['settings']  = settings();
		$data['left_features'] = $this->common_m->get_home_features_by_type('left');
		$data['right_features'] = $this->common_m->get_home_features_by_type('right');
		$data['faqs'] = $this->common_m->select_with_status_ln('faq');
		$data['services'] = $this->common_m->select_with_status_ln('site_services');
		$data['team'] = $this->common_m->select_with_status_ln('site_team');
		$data['packages'] = $this->common_m->select_with_status('packages');
		$data['all_features'] = $this->common_m->select_with_status('features');
		$data['order_types'] = $this->admin_m->get_order_types();
		$data['home_module_title_list'] = $this->admin_m->select_with_language('home_module_title_list',site_lang());
		$data['module_list'] = $this->admin_m->get_home_module_list(1);
		$load_data = $this->load->view($layoutView, $data, TRUE);
		echo json_encode(['st' => 1, 'load_data' => $load_data]);
	}

	/**
	 ** Pricing
	 **/
	public function pricing()
	{
		$ref_id = isset($_GET['ref']) && !empty($_GET['ref']) ? '?ref=' . $_GET['ref'] : '';
		$this->redirectUrl('pricing');
		$layoutView = $this->layouts == 1 ? "frontend/inc/theme_{$this->layouts}/pricing" : "frontend/home_content/pricing";
		$data = array();
		$data['_title'] = lang('pricing');
		$data['page_title'] = "Pricing";
		$data['page'] = "Home";
		$data['packages'] = $this->common_m->get_home_packages($ref_id);
		$data['all_features'] = $this->common_m->select_with_status('features');
		$data['order_types'] = $this->admin_m->get_order_types();
		$data['main_content'] = $this->load->view($layoutView, $data, TRUE);
		$this->load->view('frontend/index', $data);
	}

	public function get_popular_items($name)
	{
		$data = [];
		$data['top_8_items'] = $this->admin_m->top_8_popular_search_items($name);
		$load_data = $this->load->view('frontend/inc/popularItem_thumb', $data, TRUE);
		echo json_encode(['st' => 1, 'load_data' => $load_data]);
	}

	public function get_near_shop($lat, $lang)
	{
		$settings = settings();
		$max_distance = !empty($settings['nearby_length']) ? $settings['nearby_length'] : 5;
		$getIds = $this->admin_m->get_lat_lang();

		$unit = 'km';

		$ids = [];
		if (sizeof($getIds) > 0) :
			foreach ($getIds as $id) {
				$distance = __distance($lat, $lang, $id->latitude, $id->longitude, $unit);
				if ($distance <= $max_distance) {
					$ids[] = $id->id;
				}
			}
			$data['location_list'] = $this->common_m->get_near_shop($ids);
		else :
			$data['location_list'] = [];
		endif;




		$load_data = $this->load->view('frontend/nearby_search', $data, TRUE);

		echo json_encode(['st' => 1, 'load_data' => $load_data]);
	}

	public function ai_search()
	{
		$q = $this->input->post('q', TRUE);
		$lat = $this->input->post('lat', TRUE);
		$lon = $this->input->post('lon', TRUE);

		$this->load->library('ai_gateway');

		$prompt = "You are a search query parser for a restaurant platform. 
		Parse the user query and return ONLY a JSON object:
		{
			\"action\": \"search\" | \"near_me\",
			\"q\": \"Simplified search keywords only. Remove adjectives like 'best', 'top', 'rated', 'popular', 'hot', 'delicious'. Example: 'best pizza' -> 'pizza', 'top selling burgers' -> 'burger'\",
			\"distance\": int (default 5 if near_me),
			\"sort\": \"popular\" | \"rating\" | \"newest\"
		}
		Do not include any other text in the response, only the JSON.
		
		Examples:
		- 'best pizza near 5km' -> {\"action\": \"near_me\", \"q\": \"pizza\", \"distance\": 5, \"sort\": \"rating\"}
		- 'top selling items' -> {\"action\": \"search\", \"q\": \"\", \"sort\": \"popular\"}
		- 'best rated' -> {\"action\": \"near_me\", \"q\": \"\", \"sort\": \"rating\"}
		- 'best pizza restaurant' -> {\"action\": \"near_me\", \"q\": \"pizza\", \"sort\": \"rating\"}
		
		User Query: " . $q;

		$response = $this->ai_gateway->generate($prompt);

		// Clean response in case AI adds markdown
		$response = preg_replace('/^```json\s*|```$/m', '', $response);
		$result = json_decode(trim($response), TRUE);


		if (!$result) {
			// Fallback to normal search if AI fails or returns non-json
			$data['top_8_items'] = $this->admin_m->top_8_popular_search_items($q);
			if (empty($data['top_8_items'])) {
				echo json_encode(['st' => 0, 'msg' => '<div class="alert alert-warning text-center">No results found for "' . html_escape($q) . '". Try a different query.</div>']);
				return;
			}
			$load_data = $this->load->view('frontend/inc/popularItem_thumb', $data, TRUE);
			echo json_encode(['st' => 1, 'load_data' => $load_data, 'ai_parsed' => FALSE]);
			return;
		}

		if ($result['action'] == 'near_me' && !empty($lat) && !empty($lon)) {
			$max_distance = !empty($result['distance']) ? $result['distance'] : 5;
			$getIds = $this->admin_m->get_lat_lang();
			$ids = [];
			foreach ($getIds as $id) {
				$distance = __distance($lat, $lon, $id->latitude, $id->longitude, 'km');
				if ($distance <= $max_distance) {
					$ids[] = $id->id;
				}
			}

			if (empty($ids)) {
				echo json_encode(['st' => 0, 'msg' => '<div class="alert alert-warning text-center">No restaurants found near you matching "' . html_escape($result['q']) . '".</div>']);
				return;
			}

			if (!empty($result['q'])) {
				// Search for shops that have items matching the keyword
				$keyword = $result['q'];
				$this->db->select('shop_id');
				$this->db->from('items');
				$this->db->where_in('shop_id', $ids);
				$this->db->group_start();
				$this->db->like('title', $keyword);
				$this->db->or_like('overview', $keyword);
				$this->db->group_end();
				$this->db->group_by('shop_id');
				$shop_ids_with_items = $this->db->get()->result_array();
				$filtered_ids = array_column($shop_ids_with_items, 'shop_id');

				if (empty($filtered_ids)) {
					echo json_encode(['st' => 0, 'msg' => '<div class="alert alert-info text-center">No restaurants near you have items matching "' . html_escape($keyword) . '".</div>']);
					return;
				}
				$ids = $filtered_ids;
			}

			$data['location_list'] = $this->common_m->get_near_shop($ids);

			if (empty($data['location_list'])) {
				echo json_encode(['st' => 0, 'msg' => '<div class="alert alert-warning text-center">No active restaurants found nearby.</div>']);
				return;
			}

			if (isset($result['sort'])) {
				if ($result['sort'] == 'rating') {
					foreach ($data['location_list'] as $key => $shop) {
						$data['location_list'][$key]['rating'] = $this->common_m->total_shop_rating($shop['shop_id'], 'sum');
					}
					usort($data['location_list'], function ($a, $b) {
						return ($b['rating'] ?? 0) <=> ($a['rating'] ?? 0);
					});
				}
			}

			$load_data = $this->load->view('frontend/nearby_search', $data, TRUE);
			echo json_encode(['st' => 1, 'load_data' => $load_data, 'ai_parsed' => $result]);
		} else {
			$keyword = !empty($result['q']) ? $result['q'] : null;
			$data['top_8_items'] = $this->admin_m->top_8_popular_search_items($keyword);

			if (empty($data['top_8_items'])) {
				echo json_encode(['st' => 0, 'msg' => '<div class="alert alert-info text-center">AI found no items matching "' . html_escape($result['q']) . '".</div>']);
				return;
			}

			if (isset($result['sort'])) {
				if ($result['sort'] == 'popular') {
					usort($data['top_8_items'], function ($a, $b) {
						return ($b['total_sell'] ?? 0) <=> ($a['total_sell'] ?? 0);
					});
				} elseif ($result['sort'] == 'rating') {
					foreach ($data['top_8_items'] as $key => $item) {
						$data['top_8_items'][$key]['rating'] = $this->common_m->total_shop_rating($item['shop_id'], 'sum');
					}
					usort($data['top_8_items'], function ($a, $b) {
						return ($b['rating'] ?? 0) <=> ($a['rating'] ?? 0);
					});
				}
			}

			$load_data = $this->load->view('frontend/inc/popularItem_thumb', $data, TRUE);
			echo json_encode(['st' => 1, 'load_data' => $load_data, 'ai_parsed' => $result]);
		}
	}

	private function  distance($lat1, $lon1, $lat2, $lon2, $unit)
	{
		$radlat1 = pi() * $lat1 / 180;
		$radlat2 = pi() * $lat2 / 180;
		$theta = $lon1 - $lon2;
		$radtheta = pi() * $theta / 180;
		$dist = sin($radlat1) * sin($radlat2) + cos($radlat1) * cos($radlat2) * cos($radtheta);
		if ($dist > 1) {
			$dist = 1;
		}
		$dist = acos($dist);
		$dist = $dist * 180 / pi();
		$dist = $dist * 60 * 1.1515;
		if ($unit == "K") {
			$dist = $dist * 1.609344;
		}
		if ($unit == "N") {
			$dist = $dist * 0.8684;
		}
		return $dist;
	}

	/**
	 ** reviews
	 **/
	public function reviews()
	{
		$layoutView = $this->layouts == 1 ? "frontend/theme_{$this->layouts}/reviews" : "frontend/reviews";

		$this->redirectUrl('reviews');
		$data = array();

		$data['page_title'] = "Reviews";
		$data['_title'] = lang('review');
		$data['page'] = "Home";
		if (isset($_GET['sort'])) {
			$data['reviews'] = $this->common_m->get_reviews($_GET['sort']);
		} elseif (isset($_GET['username'])) {
			$data['reviews'] = $this->common_m->get_reviews($_GET['sort']);
		} else {
			$data['reviews'] = $this->common_m->get_reviews('newest');
		}
		$data['total_rating'] = $this->common_m->total_rating();
		$data['main_content'] = $this->load->view($layoutView, $data, TRUE);
		$this->load->view('frontend/index', $data);
	}



	/**
	 ** all users
	 **/
	public function users()
	{
		$this->redirectUrl('users');

		$layoutView = $this->layouts == 1 ? "frontend/theme_{$this->layouts}/users" : "frontend/users";
		$data = array();
		$data['_title'] = lang('restaurant');
		$data['page_title'] = "Users";
		$data['page'] = "Home";

		$config = [];
		$this->load->library('pagination');


		$per_page = $this->per_page;

		$page = $this->input->get('page');
		if (empty($page)) {
			$page = 0;
		}

		if ($page != 0) {
			$page = $page - 1;
		}
		$offset = ceil($page * $per_page);


		$total = $this->common_m->get_all_users(0, 0, $is_total = 1);
		$config['base_url'] = base_url('users');
		$config['total_rows'] = $total;
		$config['per_page'] =  $per_page;
		$this->pagination->initialize($config);

		$data['users'] = $this->common_m->get_all_users($per_page, $offset, 0);
		$data['all_packages'] = $this->common_m->select_with_status('packages');
		$data['countries'] = $this->common_m->select('country');

		$data['main_content'] = $this->load->view($layoutView, $data, TRUE);
		$this->load->view('frontend/index', $data);
	}

	/**
	 ** terms
	 **/
	public function terms()
	{
		$this->redirectUrl('terms');
		$data = array();
		$data['page_title'] = "Terms & Conditions";
		$data['page'] = "Home";
		$data['terms'] = $this->admin_m->single_select('terms');
		$data['main_content'] = $this->load->view('frontend/terms', $data, TRUE);
		$this->load->view('frontend/index', $data);
	}
	/**
	 *** privacy 
	 **/
	public function privacy()
	{
		$this->redirectUrl('privacy');
		$this->load->model('admin_m');
		$data = array();
		$data['page_title'] = "Cookies & Privacy";
		$data['page'] = "Home";
		$data['terms'] = $this->admin_m->single_select('privacy');
		$data['main_content'] = $this->load->view('frontend/terms', $data, TRUE);
		$this->load->view('frontend/index', $data);
	}

	/**
	 ***  all page_list
	 **/

	public function pages($slug)
	{
		$data = array();

		$data['_title'] = lang('pages');
		$data['page'] = "Pages";
		$data['pages'] = $this->common_m->single_select_by_slug($slug, 'pages');
		$data['page_title'] = !empty($slug) ? $slug : 'pages';
		$data['settings']  = settings();
		$data['seo'] = [
			'title' => !empty($data['pages']['title']) ? html_escape($data['pages']['title']) : $slug,
			'description' => !empty($data['pages']['details']) ? $data['pages']['details'] : '',
			'url' => base_url('pages/' . $slug),
		];

		$data['main_content'] = $this->load->view('frontend/pages', $data, TRUE);
		$this->load->view('frontend/index', $data);
	}


	public function get_tables($table)
	{
		$data = $this->common_m->select($table);
		echo "<pre>";
		print_r($data);
		exit();
	}





	/**
	 ** home page contact
	 **/
	public function contacts()
	{
		$this->redirectUrl('contacts');
		$data = array();

		$layoutView = $this->layouts == 1 ? "frontend/theme_{$this->layouts}/contacts" : "frontend/contacts";

		$data['_title'] = lang('contacts');
		$data['page_title'] = "Contacts";
		$data['page'] = "Home";
		$data['main_content'] = $this->load->view($layoutView, $data, TRUE);
		$this->load->view('frontend/index', $data);
	}

	/*  contact mail from home page
	================================================== */
	public function send_mail()
	{
		is_test();
		$this->form_validation->set_rules('name', 'your Name', 'trim|xss_clean|required');
		$this->form_validation->set_rules('email', 'Email', 'trim|xss_clean|required');
		if ($this->form_validation->run() == FALSE) {
			$msg = '<div class="alert alert-danger alert-dismissible">
			<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
			<strong><i class="fas fa-frown"></i> Sorry! </strong> ' . validation_errors() . '
			</div>';
			echo json_encode(['st' => 0, 'msg' => $msg]);
		} else {

			if (isset($_POST)) :

				$setting = settings();

				if (isset($setting['is_recaptcha']) && $setting['is_recaptcha'] == 1) :
					if ($this->security_m->recaptcha() == FALSE) {
						$msg = '<div class="alert alert-danger alert-dismissible">
						<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
						<strong><i class="fas fa-frown"></i> Sorry! </strong> Robot verification Failed
						</div>';
						echo json_encode(array('st' => 0, 'msg' => $msg));
						exit();
					}
				endif;
				$this->load->library('email');


				if (isset($this->settings['is_dynamic_mail']) && $this->settings['is_dynamic_mail'] == 1) :
					$data =  [
						'site_name' => $this->settings['site_name'],
						'name' => $this->input->post('name', TRUE),
						'email' => $this->input->post('email', TRUE),
						'message' => $this->input->post('msg', TRUE),
					];
					$send = $this->email_m->send_global_mail($data, $this->settings['smtp_mail'], 'contact_mail');
				else :
					$data = [
						'name' => $this->input->post('name', TRUE),
						'subject' => $this->input->post('subject', TRUE),
						'email' => $this->input->post('email', TRUE),
						'message' => $this->input->post('msg', TRUE),
					];
					$send = $this->email_m->home_contact_mail($data);
				endif;


				if ($send) {

					$msg = '<div class="alert alert-success alert-dismissible">
					<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
					<p><strong>Success ! </strong>Mail send successfully</p>
					</div>';
					echo json_encode(array('st' => 1, 'msg' => $msg));
				} else {
					$msg = '<div class="alert alert-danger alert-dismissible">
					<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
					<p><strong>Sorry ! </strong>Somethings Were Wrong</p>
					</div>';
					echo json_encode(array('st' => 0, 'msg' => $msg));
				}
			endif;
		}
	}



	public function error_404()
	{
		$data = array();
		$data['page_title'] = "Error 404";
		$this->load->view('404');
	}

	public function reset_password($id)
	{
		is_test();
		$data =  array(
			'password' => md5(1234),
		);
		$update = $this->admin_m->update($data, $id, 'users');
		if ($update) {
			echo json_encode(array('st' => 1));
		} else {
			echo json_encode(array('st' => 0));
		}
	}

	public function updates()
	{
		// home/updates/?field=is_update&value=1&table=settings&id=1
		is_test();
		if (isset($_GET)) {
			$field = $_GET['field'];
			$value = $_GET['value'];
			$id = $_GET['id'];
			$table = $_GET['table'];
			$key = $_GET['key'];
			$data =  array(
				$field => $value,
			);
			$update = $this->admin_m->system_update($data, $id, $table, $key);
			if ($update) {
				echo json_encode(array('st' => 1));
			} else {
				echo json_encode(array('st' => 0));
			}
		}
	}
	public function lang_switch($new_lang, $id = null)
	{
		$redirect_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

		if ($redirect_url) {
			// Remove existing lang parameter if any
			$redirect_url = preg_replace('/([?&])lang=[^&]+(&|$)/', '$1', $redirect_url);
			$redirect_url = rtrim($redirect_url, '?&');

			// Add new language parameter
			$separator = (parse_url($redirect_url, PHP_URL_QUERY)) ? '&' : '?';
			$redirect_url .= $separator . "lang=" . $new_lang;
		} else {
			$redirect_url = site_url() . "?lang=" . $new_lang;
		}

		if ($id == 'auth') {
			$this->session->set_userdata('site_lang', $new_lang);
		}

		redirect($redirect_url);
	}





	public function test_mail()
	{
		$send = $this->email_m->test_mail();
		echo "<pre>";
		print_r($send);
		exit();
	}

	public function add_users()
	{
		$st = $this->admin_m->select('settings');
		if (empty($st)) :
			$this->db->query("
				INSERT INTO users (username, password,user_role)
				VALUES ('admin', MD5('123'),1);

				INSERT INTO settings (version, site_url, license)
				VALUES ('3.2.1', 'localhost/qmenuup', 'ac_qmenu');
				");
		endif;
	}

	public function recaptcha()
	{
		$settings = settings();
		$recaptchaResponse = trim($this->input->post('g-recaptcha-response'));
		$userIp = $this->input->ip_address();
		$secret = $settings['recaptcha']->secret_key;

		try {
			$client = new Client();

			$response = $client->post('https://www.google.com/recaptcha/api/siteverify', [
				'form_params' => [
					'secret'   => $secret,
					'response' => $recaptchaResponse,
					'remoteip' => $userIp
				]
			]);
			$result = json_decode($response->getBody(), true);
			return isset($result['success']) && $result['success'] === true;
		} catch (\Exception $e) {
			return FALSE;
		}
	}

	public function master_key()
	{
		$data = array();
		$data['page_title'] = "Master Key";
		$data['page'] = "Home";
		$data['settings'] = $this->admin_m->get_settings();
		$data['main_content'] = $this->load->view('master_keys', $data, TRUE);
		$this->load->view('index', $data);
	}

	public function get_customers()
	{
		$this->load->model('updated_queries');
		$this->updated_queries->get_customers();
	}

	/**
	 * Handle demo site entry
	 * Sets session to bypass demo landing page
	 */
	public function enter_site()
	{
		// Set session to indicate user has entered the demo site
		$this->session->set_userdata('demo_entered', TRUE);

		// Redirect to home page
		redirect(base_url());
	}


	public function get_tutorials($uid)
	{
		$data['tutorial'] = $this->admin_m->single_select_by_uid($uid, 'admin_tutorial_list');
		$load_view = $this->load->view('common/tutorial_modal', $data, true);
		echo json_encode(['st' => 1, 'load_data' => $load_view]);
	}
}
