<?php
include(__DIR__ . '/../includes/functions.php');
header('Content-Type: application/json');
global $db;
$jsonData = file_get_contents('php://input');
$data = json_decode($jsonData, true);

$action = $data['action'] ?? null;
$sc = $data['sc'] ?? '123456789789456123321456987';
$deviceID = $data['deviceid'] ?? '123456789789456123321456987';
$announcement_id = $data['announcement_id'] ?? '123456789789456123321456987';

if (!$action) {
    echo json_encode(['result' => 'error', 'message' => 'No action specified']);
    exit();
}


switch ($action) {
    case 'check-maintainencemode':
        echo checkMaintenanceMode($sc);//
        break;
    case 'get_advertisemnt_status':
        echo getAdvertisementStatus($sc);//
        break;
    case 'read-announcement':
        echo seenstatus($sc,$deviceID,$announcement_id);//
        break;       
    case 'get-advertisement':
        echo getadvertisement($sc);//
        break;
    case 'add-device':
        echo addDevice($sc,$data);//
        break;
    case 'addreport':
        echo addReport($sc, $data);//
        break;
    case 'addclientfeedback':
        echo addClientFeedback($data);//
        break;
    case 'get-announcements':
        echo getAnnouncement($sc,$deviceID);//
        break;
    case 'get_lastupdated':
        echo getLastUpdated($sc);//
        break;
    case 'get-enhanced-announcements':
        echo getEnhancedAnnouncement($sc);//
        break;
    case 'get-allcombinedashrequest':
        echo processAdData($sc);//
        break;
    case 'get-ovpnzip':
        echo getovpnzip($sc);//
        break;
    default:
        echo json_encode(['result' => 'error', 'message' => 'Invalid action']);
        break;
}

function getovpnzip($scn) {
	$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
    $domain = $_SERVER['HTTP_HOST'];
    $path = dirname($_SERVER['SCRIPT_NAME']);
    $current_url = $protocol . $domain . $path;
	
	echo '{"result":"success","sc":"'.$scn.'","message":"Data retrieved successfully","vpnstatus":"on","link":"'.$current_url.'/ovpn_bundle.zip'.'"}';

}
function addDevice($scn,$data) {
	global $db;
    $table_name = 'devices';
	$deviceid = $data['deviceid'] ?? '';
	$deviceusername = $data['deviceusername'] ?? '';
	$date = $data['d'] ?? '';
	
	
	    $datanew = [
            'deviceid' => $deviceid,
            'deviceusername' => $deviceusername,
            'added_on' => $date
        ];
        $db->insertOrReplace($table_name, $datanew);
        $db->close();

	
	$response = [
		"result" => "success",
		"sc" => $scn,
		"message" => "Details Updated Successfully"
	];

	return json_encode($response);
}
function seenstatus($scn,$devid,$annid){
    global $db;
    $table_name = 'seen_announ';
    $data = ['device_id' => '00','annouse_is' => '00','status' => '1'];
    $db->insertIfEmpty($table_name, $data);
    
    
    $ret = $db->select($table_name, '*', 'device_id = :device_id', '', [':device_id' => $devid]);
    
    $count = 0;

    foreach ($ret as $row) {
        if ($row['annouse_is'] == $annid) {
            $count++;
        }
    }

    if($count == 0){
        $datanew = [
            'device_id' => $devid,
            'annouse_is' => $annid,
            'status' => '1'
        ];
        $db->insert($table_name, $datanew);
        $db->close();
    }

    
    $response = [
        'a' => 'FwvuSRK7kODy1Wm',
        's' => '6BuW8O7drqw0YmTMX43aLjNKyHDEPFgCs5zGnSUI1vQ2icxRpk',
        'r' => '1754558',
        'd' => date('Y-m'),
        'sc' => $scn,
        'action' => 'read-announcement',
        'deviceid' => $devid,
        'announcement_id' => $annid,
        'seen' => '1'
    ];

    return json_encode($response);


}

function getseenstatus($devid, $annid) {
    global $db;
    $table_name = 'seen_announ';

    // Ensure table has at least one default row
    $data = ['device_id' => '00', 'annouse_is' => '00', 'status' => '1'];
    $db->insertIfEmpty($table_name, $data);

    // Get all rows with matching device_id
    $ret = $db->select($table_name, '*', 'device_id = :device_id', '', [
        ':device_id' => $devid
    ]);

    // Search for specific annouse_is and status
    foreach ($ret as $row) {
        if ($row['annouse_is'] == $annid && $row['status'] == '1') {
            return 1;
        }
    }

    return 0;
}


function addClientFeedback($data) {
	global $db;
	$table_name = 'feedback';
	
	$datanew = [
            'username' => $data['username'],
            'macaddress' => $data['macaddress'],
            'feedback_content' => $data['feedback']
        ];
    $db->insert($table_name, $datanew);
    $db->close();

	$response = [
		"result" => "success",
		"message" => "Feedback sent successfully!"
	];

	return json_encode($response);
}


function addReport($scn, $data) {
	global $db;
    $table_name = 'reports';

    // Decode report_cases from JSON string to PHP array
    $report_cases = is_string($data['report_cases']) ? json_decode($data['report_cases'], true) : $data['report_cases'];
    
	$datanew = [
        'username' => $data['username'],
        'macaddress' => $data['macaddress'],
        'section' => $data['section'],
        'section_category' => $data['section_category'],
        'report_title' => $data['report_title'],
        'stream_name' => $data['stream_name'],
        'stream_id' => $data['stream_id'],
        'report_sub_title' => $data['report_sub_title'],
        'report_cases' => json_encode($report_cases), // Store as JSON in DB
        'report_custom_message' => $data['report_custom_message']
    ];

    $db->insert($table_name, $datanew);
    $db->close();
	
	return json_encode([
		"result" => "success",
		"sc" => $scn,
		"message" => "Report added successfully"
	]);
}

function checkMaintenanceMode($scn) {
	global $db;
	$maintemd = $db->select('maintenance', '*', 'id = :id', '', [':id' => 1]);
	$response = [
		"result" => "success",
		"sc" => $scn,
		"maintenancemode" => $maintemd[0]['mode'] ?? 'off',
		"message" => $maintemd[0]['title'] ?? '',
		"footercontent" => $maintemd[0]['body'] ?? ''
	];
	return json_encode($response);
}

function getAdvertisementStatus($scn) {
	$response = [
		"result" => "success",
		"sc" => $scn,
		"add_status" => '1',
		"add_viewable_rate" => '1',
		"message" => 'seccuesssssssss'
	];
	
	return json_encode($response);

}

function getAnnouncement($scn,$devid) {
    global $db;
    $res = $db->select('announcements', '*', '', '');   
    
    $responseData = [];   
    foreach ($res as $announcement) {      
        $responseData[] = [
            'id' => $announcement['id'],
            'title' => $announcement['title'],
            'message' => $announcement['message'],
            'whmcs_userid' => '56237',
            'whmcs_serviceid' => '115764',
            'created_on' => $announcement['created_on'],
            'updated_on' => '2024-05-24 15:31:31',
            'seen' => getseenstatus($devid, $announcement['id'])
        ]; 
    } 
    
	$response = [
		"result" => "success",
		"sc" => $scn,
		"message" => count($responseData) ? "Announcements fetched successfully" : "No announcements",
		"totalrecords" => count($responseData),
        "data" => $responseData
	];
	
	return json_encode($response);

}

function getLastUpdated($scn) {
	$response = [
		"result" => "success",
		"sc" => $scn,
		"lastupdate"=> getCurrentDateTime()
	];
	
	return json_encode($response);

}


function processAdData($scn) {
    global $db;
    $default = 'Hi, those who are connected with my service are able to experience the bliss of heaven in this world. This is very useful. Hi, those who are connected with my service are able to experience the bliss of heaven in this world. This is very useful. Hi, those who are connected with my service are able to experience the bliss of heaven in this world. This is very useful. Hi, those who are connected with my service are able to experience the bliss of heaven in this world. This is very useful.';
    
    $table_name = 'textads';
    $adsres = $db->select($table_name, '*', 'id = :id', '', [':id' => 1]);
    
    $ads_text = $adsres[0]['adstext'] ?? $default;
    $ads_status = $adsres[0]['status'] ?? '1';

    $rewardedAds = [
        [
            "id" => rand(1000, 9999),
            "title" => "xtr", 
            "type" => "message",
            "pages" => "dashboard",
            "position" => "top",
            "schedule_type" => "alltime",
            "number" => "",
            "redirect_link" => "",
            "custom_recc" => "",
            "text" => "$ads_text",
            "images" => []
        ]
    ];

    $dashboardAds = [
        [
            "id" => rand(1000, 9999),
            "title" => "Bet3", 
            "type" => "image",
            "pages" => "dashboard",
            "position" => "top",
            "schedule_type" => "alltime",
            "number" => "",
            "redirect_link" => "",
            "custom_recc" => "",
            "images" => [],
            "text" => ''
        ]
    ];

    $response = [
        "result" => "success",
        "sc" => $scn,
        "rewarded" => [
            "add_status" => "$ads_status",
            "add_viewable_rate" => "5",
            "add_type" => "rewarded",
            "message" => "ads data",
            "totalrecords" => count($rewardedAds),
            "timeinterval" => "",
            "data" => $rewardedAds
        ],
        "dashboard" => [
            "add_status" => "0",
            "message" => "ads data",
            "totalrecords" => count($dashboardAds),
            "timeinterval" => "",
            "data" => $dashboardAds
        ]
    ];

    return json_encode($response);
}

function getEnhancedAnnouncement($scn) {
    $rewardedAds = [
        'add_status' => '1', 
        'add_viewable_rate' => '2', 
        'add_type' => 'rewarded', 
        'message' => 'advertisement data', 
        'data' => []
    ];
    $dashboardAds = [
        'add_status' => '1', 
        'message' => 'advertisement data', 
        'data' => []
    ];

    $response = [
        "result" => "success",
        "sc" => $scn,
        "rewarded" => $rewardedAds,
        "dashboard" => $dashboardAds
    ];

    return json_encode($response);
}


function getadvertisement($scn) {
  global $db;
  
  $default = 'Hi, those who are connected with my service are able to experience the bliss of heaven in this world. This is very useful. Hi, those who are connected with my service are able to experience the bliss of heaven in this world. This is very useful. Hi, those who are connected with my service are able to experience the bliss of heaven in this world. This is very useful. Hi, those who are connected with my service are able to experience the bliss of heaven in this world. This is very useful.';
    
    $table_name = 'textads';
    $adsres = $db->select($table_name, '*', 'id = :id', '', [':id' => 1]);
    
    $ads_text = $adsres[0]['adstext'] ?? $default;
    $ads_status = $adsres[0]['status'] ?? '1';

  $response = json_encode([
    "result" => "success",
    "sc" => $scn,
    "message" => "advertisement data",
    "totalrecords" => 1,
    "timeinterval" => "",
    "data" => [
      [
        "id" => rand(10, 99),
        "title" => "rtx",
        "type" => "message",
        "pages" => "dashboard",
        "position" => "bottom",
        "schedule_type" => "alltime",
        "number" => "",
        "redirect_link" => "",
        "custom_recc" => "",
        "text" => "$ads_text"
      ]
    ]
  ]);

  return $response;
}

function getCurrentDateTime() {
    return date('Y-m-d H:i:s');
}

?>