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

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

if (!isset($_SESSION['userid'])) {
    http_response_code(401);
    echo json_encode(["error" => "Unauthorized to access. Please login"]);
    exit;
}
    // $property_id = $_SESSION['property'];
    if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
    $property_id=$_POST['property_id'];

try {
    $call_cost = 0;
    $call_duration = 0;
    $total_sms = 0;
    $total_sms_amount = 0;
    $messages_amount = 0;
    $total_messages = 0;
    $rsponse_data = get_voice_calls_amount($property_id ?? null);
    if(!empty($rsponse_data['calls'])){
        $get_voice_calls_amount = $rsponse_data['calls'];
        $call_cost = $get_voice_calls_amount['call_amount'] * 2;
        $call_duration = $get_voice_calls_amount['call_duration'];
    }
    if(!empty($rsponse_data['messages'])){
        $get_messages_amount = $rsponse_data['messages'];
        $messages_amount = $get_messages_amount['messages_amount'];
        $total_messages = $get_messages_amount['total_messages'];
    }
    if (isset($_POST['getDashboardData'])) {
            if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
            $propertyId=$_POST['property_id'];
            $userId = $_SESSION['userid'];

            // Fetch users data: handle both primary and multi-property users
            $usersData = fetchData('property_users', ['status' => 'registered', 'property_id' => $propertyId]);
            $multiPropUsers = fetchData('multi_prop_users', ['user_assoc' => $userId, 'property_id' => $propertyId, 'deleted_at' => null]);

            // Merge primary and multi-property users
            if (!empty($multiPropUsers)) {
                foreach ($multiPropUsers as $multiUser) {
                    $usersData[] = $multiUser;
                }
            }

            $propertiesData = fetchData('properties', ['id' => $propertyId]);
            $doorsData = fetchData('gate_doors', ['property_id' => $propertyId]);
            $hardwaresDoorsData = fetchData('visitors', ['property_id' => $propertyId]);
            $callsData = fetchData('call_histories',['property_id' => $propertyId]);
            $is_property_user = fetchData('property_users', ['email' => $_SESSION["email"], 'creator_type' => "users"]);

            $usersLength = is_array($usersData) ? count($usersData) : 0;
            $propertiesLength = is_array($propertiesData) ? count($propertiesData) : 0;
            $doorsDataLength = is_array($doorsData) ? count($doorsData) : 0;
            $hardwaresDoorsDataLength = is_array($hardwaresDoorsData) ? count($hardwaresDoorsData) : 0;
            $callsDataLength = is_array($callsData) ? count($callsData) : 0;
            sendJsonResponse(200, [
                "usersLength" => $usersLength ?? null,
                "unitsLength" => $propertiesLength ?? null,
                "doorsLength" => $doorsDataLength ?? null,
                "activeKeysLength" => $hardwaresDoorsDataLength ?? null,
                "callsLength" => $callsDataLength ?? null,
                "voice_calls_cost" => $call_cost ?? null,
                "voice_calls_duration" => $call_duration ?? null,
                "messages_amount" => $messages_amount ?? null,
                "total_messages" => $total_messages ?? 0,
                "property_id" => $_SESSION['property_id'] ?? $_SESSION["property"] ?? null,
                "is_property_user" => !empty($is_property_user)??null,
            ]);
    }
} catch (\Throwable $th) {
    sendJsonResponse(500, ["error" => "Server error: " . $th->getMessage()]);
}
