<?php
// header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");

// session_start();
if (session_status() === PHP_SESSION_NONE) session_start();
include '../helper_functions/data_request.php';
include 'call_logs.php';

if (!isset($_SESSION['userid'])) {
    http_response_code(401);
    echo json_encode(["error" => "Unauthorized to access. Please login"]);
    exit;
}
try {
    if (isset($_POST['getEventsRequest'])) {
        $rolesData=fetchDataWithId("roles",$_SESSION['role']);
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property'] ?? null;
        if(!empty($rolesData) && ($rolesData["name"]=="dealer"||$rolesData["name"]=="sub_dealer" || $rolesData["name"]=="user" || $rolesData["name"]=="organization admin"||$rolesData["name"]=="property admin") ){
            $response = fetchData('audit_logs', ['user_email'=>$_SESSION['email'],'property_id'=>$_POST['property_id']]);
        }else if (isset($rolesData) && ($rolesData["name"]=="super_admin"||$rolesData["name"]=="admin")){
            $response = fetchData('audit_logs', ['property_id'=>$_POST['property_id']]);
        }else {
            $response = fetchData('audit_logs', ['property_id'=>$_POST['property_id'],"log_level"=>"medium","user_email"=>$_SESSION["email"]]);
        }

        if ($response === false) sendJsonResponse(500, ["error" => 'Could not fetch data ']);
        sendJsonResponse(200, [
            "success" => true,
            "data" =>array_reverse($response),
            "extras" =>$_SESSION["layer"],
            "property_id"=>$_POST['property_id'],
            "role"=>$rolesData??null
        ]);
    }

    if (isset($_POST['getEventsRequest'])) {
        $rolesData=fetchDataWithId("roles",$_SESSION['role']);
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property_id'] ?? null;
        if(!empty($rolesData) && ($rolesData["name"]=="dealer"||$rolesData["name"]=="sub_dealer" || $rolesData["name"]=="user" || $rolesData["name"]=="organization admin"||$rolesData["name"]=="property admin") ){
            $response = fetchData('audit_logs', ['user_email'=>$_SESSION['email'],'property_id'=>$_POST['property_id']]);
        }else if (isset($rolesData) && ($rolesData["name"]=="super_admin"||$rolesData["name"]=="admin")){
            $response = fetchData('audit_logs', ['property_id'=>$_POST['property_id']]);
        }else {
            $response = fetchData('audit_logs', ['property_id'=>$_POST['property_id'],"log_level"=>"medium","user_email"=>$_SESSION["email"]]);
        }

        if ($response === false) sendJsonResponse(500, ["error" => 'Could not fetch data ']);
        sendJsonResponse(200, [
            "success" => true,
            "data" =>array_reverse($response),
            "extras" =>$_SESSION["layer"],
            "property_id"=>$_POST['property_id'],
            "role"=>$rolesData??null
        ]);
    }

    if(isset($_POST['getOrgEventsRequest'])){
        $rolesData=fetchDataWithId("roles",$_SESSION['role']);
        
        if(!empty($rolesData) && ($rolesData["name"]=="dealer"||$rolesData["name"]=="sub_dealer" || $rolesData["name"]=="user" || $rolesData["name"]=="organization admin"||$rolesData["name"]=="property admin")){
            $response = fetchData('audit_logs', ['user_email'=>$_SESSION['email'], 'table_name'=> "organizations"]);
        }else if (isset($rolesData) && ($rolesData["name"]=="super_admin"||$rolesData["name"]=="admin")){
            $response = fetchData('audit_logs', ['table_name'=> "organizations"]);
        }else {
            $response = [];
        }

        if ($response === false) sendJsonResponse(500, ["error" => 'Could not fetch data']);
        sendJsonResponse(200, [
            "success" => true,
            "data" =>array_reverse($response),
            "extras" =>$_SESSION["layer"],
            "role"=>$rolesData??null
        ]);   
    }

    if(isset($_POST['getAdminEventsRequest'])){
        $rolesData=fetchDataWithId("roles",$_SESSION['role']);
        
        if(!empty($rolesData) && ($rolesData["name"]=="dealer"||$rolesData["name"]=="sub_dealer" || $rolesData["name"]=="user" || $rolesData["name"]=="organization admin"||$rolesData["name"]=="property admin")){
            $response = fetchAllDataByOperator('audit_logs', ['user_email'=>$_SESSION['email'], 'property_id'=> null, 'table_name !=' => "organizations"]);
        }else if (isset($rolesData) && ($rolesData["name"]=="super_admin"||$rolesData["name"]=="admin")){
            $response = fetchAllDataByOperator('audit_logs', ['property_id'=> null, 'table_name !=' => "organizations"]);
        }else {
            $response = [];
        }

        if ($response === false) sendJsonResponse(500, ["error" => 'Could not fetch data']);
        sendJsonResponse(200, [
            "success" => true,
            "data" =>array_reverse($response),
            "extras" =>$_SESSION["layer"],
            "role"=>$rolesData??null
        ]);   
    }

    if (isset($_POST['getCallEventsRequest'])) {
        $property_id = $_POST['property_id'];
        $start_date = $_POST['start_date'];
        $end_date = $_POST['end_date'];
        $page_size = $_POST['page_size'];
        $page_token = $_POST['page_token'];
        $type = $_POST['type'];
        if(!empty($property_id)){
            $response = get_calls_data($property_id, $start_date, $end_date, $page_size, $page_token, $type);
            if(!empty($response)){
                $response['user_type'] = $_SESSION["layer"];
            }
            else{
                $response = 0;
            }
        }
        else{
            $response = 0;
        }
        echo json_encode($response);
    }


    if (isset($_POST['save_blocked_number'])) {
        $type = $_POST['type'];
        $name = $_POST['block_name'];
        $number = preg_replace('/\D/', '', $_POST['block_number']);
        $formatted_number = format_number($number);

        if(isset($_SESSION['property']) && !empty($_SESSION['property'])){
            $check_numebr = fetchDataSingle('block_numbers', ['property_id' => $_SESSION['property'], 'formatted_number' => $formatted_number, 'type' => $type]);
            if(isset($check_numebr['id']) && !empty($check_numebr['id'])){
                $result = "This number already Blocked";
            }
            else{
                $result = save_block($_SESSION['property'], $type, $name, $number, $formatted_number);
            }
        }
        else{
           $result = "Please select a property";     
        }
        echo json_encode($result);
    }

    if(isset($_POST['get_block_data'])){
        $type = $_POST['type'];
        $data = get_block_data($type);
        echo json_encode($data);
    }

    if(isset($_POST['removed_block_number'])){
        $type = $_POST['type'];
        $number_id = $_POST['number_id'];
        $remove_number = remove_block_number($type, $number_id);
        echo json_encode($remove_number);
    }

    if(isset($_POST['get_snap_shot_data'])){
        $data = get_snapshot_data($_SESSION['property']);
        echo json_encode($data);
    }
    
} catch (\Throwable $th) {
    sendJsonResponse(500, ["error" => "Server error: " . $th->getMessage()]);
}


function format_number($phone_number) {
    // Remove all non-numeric characters
    $phone_number = preg_replace('/[^0-9]/', '', $phone_number);

    // If the number does not start with 1, add it as the country code
    if (strlen($phone_number) === 10) {
        $phone_number = '1' . $phone_number;
    }

    // Ensure the number is now 11 digits long (1 + 10)
    if (strlen($phone_number) === 11 && substr($phone_number, 0, 1) === '1') {
    }
    else if (strlen($phone_number) === 11 && strpos($phone_number, '0') === 0) {
        $phone_number = '44' . substr($phone_number, 1);
    }
    else if (strlen($phone_number) === 12 && strpos($phone_number, '00') === 0) 
    {
        $phone_number = '44' . substr($phone_number, 2);
    }
    return '+' . $phone_number;
}