chess/application/controllers/Api.php

827 lines
27 KiB
PHP

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Api extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('api_model');
$this->load->library('form_validation');
}
function index()
{
$data = $this->api_model->fetch_all();
echo json_encode($data->result_array());
}
public function insert()
{
// Set form validation rules
$this->form_validation->set_rules("tname", "Tournament Name", "required");
$this->form_validation->set_rules("entry_fee", "Entry Fee", "required");
$this->form_validation->set_rules("start_date_time", "Start Date Time", "required");
// $this->form_validation->set_rules("end_date", "End date", "required");
$this->form_validation->set_rules("win_amount", "Win Amount", "required");
$this->form_validation->set_rules("time_slot", "Time Slot", "required");
$this->form_validation->set_rules("t_type", "Tournament Type", "required");
$this->form_validation->set_rules("round[]", "Round", "required");
// Initialize the response array
$response = array();
// Check if form validation passed
if ($this->form_validation->run()) {
$data = array(
'tname' => trim($this->input->post('tname')),
'entry_fee' => trim($this->input->post('entry_fee')),
'start_date_time' => trim($this->input->post('start_date_time')),
// 'end_date' => trim($this->input->post('end_date')),
'win_amount' => trim($this->input->post('win_amount')),
'time_slot' => trim($this->input->post('time_slot')),
't_type' => trim($this->input->post('t_type')),
'round' => json_encode($this->input->post('round'))
//'round' => json_encode($this->input->post('round')) // Convert the 'round' array to a JSON string
);
// print_r($data);
// Call your API model method to insert data
$insert = $this->api_model->insert_api($data);
// Check if the insertion was successful
if ($insert) {
$response['success'] = true;
} else {
$response['error'] = true;
$response['message'] = 'Failed to insert data.';
}
} else {
// Form validation failed, return error details
$response['error'] = true;
$response['validation_errors'] = validation_errors();
}
// Return the response as JSON
echo json_encode($response);
}
function fetch_single()
{
$response = array();
if ($this->input->post('tid')) {
$user_id = $this->input->post('tid');
$data = $this->api_model->fetch_single_user($user_id);
if ($data) {
$response['success'] = true;
$response['data']['tname'] = $data[0]["tname"];
$response['data']['entry_fee'] = $data[0]["entry_fee"];
$response['data']['start_date_time'] = $data[0]["start_date_time"];
$response['data']['end_date'] = $data[0]["end_date"];
$response['data']['win_amount'] = $data[0]["win_amount"];
$response['data']['time_slot'] = $data[0]["time_slot"];
$response['data']['t_type'] = $data[0]["t_type"];
} else {
$response['success'] = false;
$response['message'] = 'User not found';
}
} else {
$response['success'] = false;
$response['message'] = 'Invalid input parameters';
}
echo json_encode($response);
}
function update()
{
$this->form_validation->set_rules("tname", "Tournament Name", "required");
$this->form_validation->set_rules("entry_fee", "Entry Fee", "required|numeric");
$this->form_validation->set_rules("start_date", "Start Date", "required");
$this->form_validation->set_rules("end_date", "End date", "required");
$this->form_validation->set_rules("win_amount", "Win Amount", "required");
$this->form_validation->set_rules("time_slot", "Time Slot", "required");
$array = array();
if($this->form_validation->run())
{
$tid = $this->input->post('tid'); // Get the tournament ID
$data = array(
'tname' => trim($this->input->post('tname')),
'entry_fee' => trim($this->input->post('entry_fee')),
'start_date' => trim($this->input->post('start_date')),
'end_date' => trim($this->input->post('end_date')),
'win_amount' => trim($this->input->post('win_amount')),
'time_slot' => trim($this->input->post('time_slot')),
);
$this->api_model->update_api($tid, $data);
$array = array(
'success' => true
);
}
else
{
$array = array(
'error' => true,
'tname_error' => form_error('tname'),
'entry_fee_error' => form_error('entry_fee'),
'start_date_error' => form_error('start_date'),
'end_date_error' => form_error('end_date'),
'win_amount_error' => form_error('win_amount'),
'time_slot_error' => form_error('time_slot')
);
}
echo json_encode($array, true);
}
function delete()
{
if($this->input->post('id'))
{
if($this->api_model->delete_single_user($this->input->post('id')))
{
$array = array(
'success' => true
);
}
else
{
$array = array(
'error' => true
);
}
echo json_encode($array);
}
}
public function user_join_tournament()
{
$user_id = $this->input->post('user_id');
$tid = $this->input->post('tid');
$round = $this->input->post('round');
if (empty($user_id) || empty($tid)) {
$response['error_code'] = 406;
$response['message'] = "Required Parameter Missing";
echo json_encode($response);
exit();
}
$where_user = '(user_id="'.$user_id.'")';
$get_wallet_amount = $this->api_model->getData($tbl = "tbl_user", $where_user);
$where_tournament = '(tid= "' . $tid . '")';
$t_data = $this->api_model->getData('tournament', $where_tournament);
if (empty($get_wallet_amount) || empty($t_data)) {
$response['error_code'] = 404;
$response['message'] = "User or Tournament Not Found";
echo json_encode($response);
exit();
}
$send_data = $get_wallet_amount['wallet_amount'];
if ($t_data['entry_fee'] > $send_data) {
$response['error_code'] = 404;
$response['message'] = "Insufficient Balance";
echo json_encode($response);
exit();
}
$deducted_amount = $send_data - $t_data['entry_fee'];
$update_data = array('wallet_amount' => $deducted_amount);
$update_user_wallet = $this->api_model->editData2($tbl = 'tbl_user', $update_data, $where_user);
$address_data = array(
'user_id' => $user_id,
'tid' => $tid,
'round' => $round,
);
$insert_id = $this->api_model->insertData('tournament_registrations', $address_data);
if ($update_user_wallet && $insert_id) {
$response['error_code'] = 200;
$response['message'] = "User Joined Successfully";
echo json_encode($response);
exit();
} else {
$response['error_code'] = 404;
$response['message'] = "Something Went Wrong";
echo json_encode($response);
exit();
}
}
// public function get_joined_user_tournament()
// {
// $tid = $this->input->post('tid');
// if (!empty($tid)) {
// $where_condition = '(tid= "' . $tid . '")';
// $data = $this->api_model->getAllData('tournament_registrations', $where_condition);
// if (!empty($data)) {
// $users_data = array();
// foreach ($data as $dat) {
// $where = '(user_id= "' . $dat['user_id'] . '")';
// $user_data = $this->api_model->getData('tbl_user', $where);
// $where_1 = '(tid= "' . $dat['tid'] . '")';
// $t_data = $this->api_model->getData('tournament', $where_1);
// $u_data = array(
// 'id' => $dat['id'],
// 'registration_time' => $dat['registration_time'],
// 'user_name' => $user_data['username'],
// 'profile_photo' => base_url() . $user_data['profile_photo'],
// );
// $users_count = count($data);
// $users_data[] = $u_data;
// }
// $response['error_code'] = 200;
// $response['message'] = "Success";
// $response['tid'] = $dat['tid'];
// $response['tournament_name'] = $t_data['tname'];
// $response['users_count'] = $users_count;
// $response['data'] = $users_data;
// echo json_encode($response);
// exit();
// } else {
// $response['error_code'] = 404;
// $response['message'] = "No Data Found";
// echo json_encode($response);
// exit();
// }
// } else {
// $response['error_code'] = 406;
// $response['message'] = "Required Parameter Missing";
// echo json_encode($response);
// exit();
// }
// }
// public function get_joined_user_tournament()
// {
// $tid = $this->input->post('tid'); // Change from post to get
// if (!empty($tid)) {
// $where_condition = '(tid= "' . $tid . '")';
// $data = $this->api_model->getAllData('tournament_registrations', $where_condition);
// if (!empty($data)) {
// $users_data = array();
// foreach ($data as $dat) {
// $where = '(user_id= "' . $dat['user_id'] . '")';
// $user_data = $this->api_model->getData('tbl_user', $where);
// $where_1 = '(tid= "' . $dat['tid'] . '")';
// $t_data = $this->api_model->getData('tournament', $where_1);
// $u_data = array(
// 'id' => $dat['id'],
// 'registration_time' => $dat['registration_time'],
// 'user_name' => $user_data['username'],
// 'user_id' => $user_data['user_id'],
// 'profile_photo' => base_url() . $user_data['profile_photo'],
// 'round' => $dat['round'],
// );
// $users_count = count($data);
// $users_data[] = $u_data;
// }
// $response['error_code'] = 200;
// $response['message'] = "Success";
// $response['tid'] = $dat['tid'];
// $response['tournament_name'] = $t_data['tname'];
// $response['users_count'] = $users_count;
// $response['data'] = $users_data;
// echo json_encode($response);
// exit();
// } else {
// $response['error_code'] = 404;
// $response['message'] = "No Data Found";
// echo json_encode($response);
// exit();
// }
// } else {
// $response['error_code'] = 406;
// $response['message'] = "Required Parameter Missing";
// echo json_encode($response);
// exit();
// }
// }
public function get_joined_user_tournament()
{
$tid = $this->input->post('tid'); // Change from post to get
if (!empty($tid)) {
$where_condition = '(tid= "' . $tid . '")';
$data = $this->api_model->getAllData('tournament_registrations', $where_condition);
if (!empty($data)) {
$users_data = array();
$highest_round = 0; // Initialize to 0
foreach ($data as $dat) {
$where = '(user_id= "' . $dat['user_id'] . '")';
$user_data = $this->api_model->getData('tbl_user', $where);
$where_1 = '(tid= "' . $dat['tid'] . '")';
$t_data = $this->api_model->getData('tournament', $where_1);
$round = (int)$dat['round']; // Convert round to integer
// If the current round is higher than the stored highest round
if ($round > $highest_round) {
$highest_round = $round;
$users_data = array(); // Reset the array for the new highest round
}
// If the current round is equal to the highest round or the first iteration
if ($round >= $highest_round) {
$u_data = array(
'id' => $dat['id'],
'registration_time' => $dat['registration_time'],
'user_name' => $user_data['username'],
'user_id' => $user_data['user_id'],
'profile_photo' => base_url() . $user_data['profile_photo'],
'round' => $round,
);
// Add $u_data to $users_data array
$users_data[] = $u_data;
}
}
$users_count = count($users_data);
// Check if any user data is present
if ($users_count > 0) {
$response['error_code'] = 200;
$response['message'] = "Success";
$response['tid'] = $dat['tid'];
$response['tournament_name'] = $t_data['tname'];
$response['users_count'] = $users_count;
$response['data'] = $users_data;
} else {
$response['error_code'] = 404;
$response['message'] = "No Data Found";
}
echo json_encode($response);
exit();
} else {
$response['error_code'] = 404;
$response['message'] = "No Data Found";
echo json_encode($response);
exit();
}
} else {
$response['error_code'] = 406;
$response['message'] = "Required Parameter Missing";
echo json_encode($response);
exit();
}
}
// public function calculate_winnings()
// {
// $tid = $this->input->post('tid');
// $participants = $this->api_model->get_tournament_participants($tid);
// usort($participants, function ($a, $b) {
// // Compare rounds first
// if ($a['round'] != $b['round']) {
// return $b['round'] - $a['round'];
// } else {
// // If rounds are the same, compare scores
// return $b['score'] - $a['score'];
// }
// });
// // Add rank to each participant
// foreach ($participants as $key => $participant) {
// $participants[$key]['rank'] = $key + 1;
// }
// $totalWinnings = $this->api_model->get_tournament_win_amount($tid);
// $winningsDistribution = array();
// $this->api_model->update_winnings_in_database($winningsDistribution, $tid);
// $response['status'] = 'success';
// $response['message'] = 'Winnings calculated for the tournament';
// $response['participants'] = $participants;
// echo json_encode($response);
// }
///main
public function calculate_winnings()
{
$tid = $this->input->post('tid');
$participants = $this->api_model->get_tournament_participants($tid);
usort($participants, function ($a, $b) {
if ($a['round'] != $b['round']) {
return $b['round'] - $a['round'];
} else {
return $b['score'] - $a['score'];
}
});
foreach ($participants as $key => $participant) {
$participants[$key]['rank'] = $key + 1;
}
$totalWinnings = $this->api_model->get_tournament_win_amount($tid);
$adminShare = 0.2 * $totalWinnings;
$playersShare = 0.8 * $totalWinnings;
$numPlayersToDistribute = ceil(0.2 * count($participants));
$winningsDistribution = array();
for ($i = 0; $i < $numPlayersToDistribute; $i++) {
$rank = $participants[$i]['rank'];
$percentage = 1 / pow(2, $rank); // 1/2, 1/4, 1/8, ...
$winningsDistribution[$participants[$i]['user_id']] = $percentage * $playersShare;
}
$this->api_model->update_winnings_in_database($winningsDistribution, $tid);
// $this->api_model->update_admin_wallet($adminShare);
$response['status'] = 'success';
$response['message'] = 'Winnings calculated for the tournament';
$response['winningsDistribution'] = $winningsDistribution;
$response['participants'] = $participants;
echo json_encode($response);
}
public function get_leaderboard()
{
$tid = $this->input->post('tid');
$participants = $this->api_model->get_tournament_leaderboard($tid);
usort($participants, function ($a, $b) {
// Compare rounds first
if ($a['round'] != $b['round']) {
return $b['round'] - $a['round'];
} else {
// If rounds are the same, compare scores
return $b['score'] - $a['score'];
}
});
// Add rank to each participant
foreach ($participants as $key => $participant) {
$participants[$key]['rank'] = $key + 1;
}
$response['status'] = 'success';
$response['message'] = 'Leaderboard retrieved successfully';
$response['leaderboard'] = $participants;
echo json_encode($response);
}
public function declare_winners()
{
$tid = $this->input->post('tid');
$winners = $this->api_model->get_tournament_winners($tid);
$response['status'] = 'success';
$response['message'] = 'Winners declared for the tournament';
$response['winners'] = $winners;
echo json_encode($response);
}
// public function get_leaderboard()
// {
// $tid = $this->input->post('tid');
// if (empty($tid)) {
// $response['status'] = 'error';
// $response['message'] = 'Tournament ID is required.';
// echo json_encode($response);
// return;
// }
// $leaderboard = $this->api_model->get_tournament_leaderboard($tid);
// $response['status'] = 'success';
// $response['message'] = 'Leaderboard data retrieved successfully.';
// $response['leaderboard'] = $leaderboard;
// echo json_encode($response);
// }
public function get_wallet_data()
{
$user_id = $this->input->post('user_id');
$where = '(user_id="'.$user_id.'")';
$get_bet_won_data = $this->api_model->getData($tbl="tbl_user",$where);
if ($get_bet_won_data) {
$send_data = $get_bet_won_data['wallet_amount'];
$response['error_code'] = "200";
$response['message'] = "Success";
$response['wallet_amount'] = $send_data;
echo json_encode($response);
exit();
}
else {
$response['error_code'] = "400";
$response['message'] = "Failed";
echo json_encode($response);
exit();
}
}
// public function get_leaderboard()
// {
// $tid = $this->input->post('tid');
// if (empty($tid)) {
// $response['status'] = 'error';
// $response['message'] = 'Tournament ID is required.';
// echo json_encode($response);
// return;
// }
// $is_tournament_completed = $this->api_model->check_tournament_completion_status($tid);
// if ($is_tournament_completed) {
// $leaderboard = $this->api_model->get_tournament_leaderboard($tid);
// $response['error_code'] = 200;
// $response['status'] = 'success';
// $response['message'] = 'Leaderboard data retrieved successfully.';
// $response['leaderboard'] = $leaderboard;
// } else {
// $response['error_code'] = 206;
// $response['status'] = 'info';
// $response['message'] = 'Tournament is ongoing. Please wait for completion.';
// }
// echo json_encode($response);
// }
public function update_user_score()
{
$user_id = $this->input->post('user_id');
$score = $this->input->post('score');
$tid = $this->input->post('tid');
$round = $this->input->post('round');
if (empty($user_id) || empty($score) || empty($tid) || empty($round)) {
$response['status'] = 'error';
$response['message'] = 'User ID, score, round, and tournament ID (tid) are required.';
echo json_encode($response);
return;
}
$this->api_model->update_user_score($user_id, $score, $tid,$round);
$response['status'] = 'success';
$response['message'] = 'User score updated successfully.';
echo json_encode($response);
}
public function update_tournament_user_playing_status()
{
$user_id = $this->input->post('user_id');
$tid = $this->input->post('tid');
$is_match_completed = $this->input->post('is_match_completed');
$opponent_id = $this->input->post('opponent_id');
$match_status = $this->input->post('match_status');
$is_tournament_won = $this->input->post('is_tournament_won');
if (empty($tid) || empty($user_id) || !is_numeric($user_id) || !in_array($is_match_completed, array(0, 1)) || !is_numeric($opponent_id) || !in_array($match_status, array('1', '0', '2', '3')) || !in_array($is_tournament_won, array(0, 1))) {
$response['status'] = 'error';
$response['message'] = 'Invalid or missing parameters.';
echo json_encode($response);
return;
}
$data = array(
'is_match_completed' => $is_match_completed,
'opponent_id' => $opponent_id,
'match_status' => $match_status,
'is_tournament_won' => $is_tournament_won,
);
$this->api_model->update_tournament_registration($user_id, $data, $tid);
$response['status'] = 'success';
$response['message'] = 'Tournament registration updated successfully.';
echo json_encode($response);
}
public function check_tournament_completion()
{
$tid = $this->input->post('tid');
if (empty($tid) || !is_numeric($tid)) {
$response['status'] = 'error';
$response['message'] = 'Invalid or missing tournament ID.';
echo json_encode($response);
return;
}
$result = $this->api_model->check_tournament_completion($tid);
$response['status'] = 'success';
$response['is_tournament_completed'] = $result['is_tournament_completed'];
$response['message'] = $result['message'];
echo json_encode($response);
}
public function played_game_history(){
if($this->input->post('user_id')!=null){
$user_id = $this->input->post('user_id');
$where = '(user_id = "'.$user_id.'")';
$user_data = $this->api_model->getData($tbl = 'tbl_user',$where);
if(!empty($user_data)){
$where1 ='(status = 1)';
$user = $this->api_model->getData($tbl = 'tbl_user', $where1);
if(empty($user)){
$response['error_code'] = 404;
$response['message'] = 'User not registered';
echo json_encode($response);
exit();
}else{
$player2 = $this->input->post('player2_id');
$game_type = $this->input->post('game_type');
$time_slot = $this->input->post('time_slot');
$status = $this->input->post('status');
$result = $this->input->post('result');
$arr = array(
"player1_id" => $user_id,
"player2_id" => $player2,
"game_type" =>$game_type,
"time_slot"=>$time_slot,
"status"=>$status,
"result" => $result
);
$insert_player = $this->api_model->insertData($tbl = 'tbl_game_data', $arr);
if($insert_player){
$response['error_code'] = 200;
$response['message'] = 'Registered Successfully!';
echo json_encode($response);
exit();
}else{
$response['error_code'] = 403;
$response['message'] = 'Data is not inserted successfully!';
echo json_encode($response);
exit();
}
}
}else{
$response['error_code'] = '404';
$response['message'] = 'Incorrect User id';
echo json_encode($response);
exit();
}
}else{
$response['error_code'] = 400;
$response['message'] = 'required parameter missing!';
echo json_encode($response);
exit();
}
}
//get_user_leaderboard
public function get_leaderboard_data() {
$where = '(status = 1) OR (status=0) OR (status= 0.5)';
$leader_data = $this->get_model->get_all1($tbl = 'tbl_game_data', $where);
$user_arr = array();
$i = 1;
foreach ($leader_data as $leader_key => $leader_value) {
$user_id = $leader_value['player1_id'];
$tbl = 'tbl_game_data';
$where = '(status = 1 AND player1_id = "' . $user_id . '")';
$win_count = $this->get_model->count_rows($tbl, $where);
$where = '(status = 0.5) AND (player1_id = "' . $user_id . '")';
$draw_count = $this->get_model->count_rows($tbl, $where);
$where = '(status = 0) AND (player1_id = "' . $user_id . '")';
$lost_count = $this->get_model->count_rows($tbl, $where);
$win = $win_count;
$drawn = $draw_count;
$lost = $lost_count;
$where1 = '(user_id = "' . $user_id . '")';
$user_data = $this->get_model->get_all($tbl = 'tbl_user', $where1);
foreach ($user_data as $user_key => $user_value) {
$country = $user_value['country'];
}
$points = $win_count*1+$draw_count*0.5+$lost_count*0;
$game_arr[] = array(
"sr_no" => $i++,
"profile_photo" => $user_value['profile_photo'],
"name" => $user_value['name'],
"win_count"=>$win_count,
"draw_count" =>$draw_count,
"lost_count"=>$lost_count,
"points"=>$points
);
}
if($game_arr){
$response['error_code']= 200;
$response['message'] = "Success";
$response['data']= $game_arr;
echo json_encode($response);
exit();
}else{
$response['error_code']=400;
$response['message'] = "Required parameter missing.";
echo json_encode($response);
}
}
}