<?php
require("../../inc/lib.inc");

global $OMC_server;
$sysTypeNo=$_GET['sysTypeNo'];
$cstaDbConn=mysqli_connect($OMC_server[0]['host'],$OMC_server[0]['user'],$OMC_server[0]['password'], 'CSTA_DB');
$objDbConn=mysqli_connect($OMC_server[0]['host'],$OMC_server[0]['user'],$OMC_server[0]['password'], 'OBJ_'.$sysTypeNo);
$page_id=$_GET['page_id'];
$sel_date_from=$_GET['sel_date_from'];
$sel_date_to=$_GET['sel_date_to'];
$show_type=$_GET['show_type'];
$startTime=date("Y-m-d H:i:s",mktime(0,0,0,date("m"),date("d")-$sel_date_from,date("Y")));
$endTime=date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-$sel_date_to,date("Y")));
    switch($sysTypeNo){      
        case '350':

            $sumSql="SELECT SUM(MS_to_SMSC_attempt) AS total_MS_to_SMSC_attempt,SUM(MS_to_SMSC_success) AS total_MS_to_SMSC_success,
            SUM(MS_to_SMSC_sysfail+MS_to_SMSC_userfail+MS_to_SMSC_smfail) AS total_MS_to_SMSC_Failure,
            SUM(MS_to_SMSC_byte) AS total_MS_to_SMSC_byte,
            SUM(PPS_to_SMSC_attempt) AS total_PPS_to_SMSC_attempt,
            SUM(PPS_to_SMSC_success) AS total_PPS_to_SMSC_success,
            SUM(PPS_to_SMSC_sysfail+PPS_to_SMSC_userfail+PPS_to_SMSC_smfail) AS total_PPS_to_SMSC_Failure,
            SUM(PPS_to_SMSC_byte) AS total_PPS_to_SMSC_byte,
            SUM(VMS_to_SMSC_attempt) AS total_VMS_to_SMSC_attempt,
            SUM(VMS_to_SMSC_success) AS total_VMS_to_SMSC_success,
            SUM(VMS_to_SMSC_sysfail+VMS_to_SMSC_userfail+VMS_to_SMSC_smfail) AS total_VMS_to_SMSC_Failure,
            SUM(VMS_to_SMSC_byte) AS total_VMS_to_SMSC_byte,
            SUM(SMPP_to_SMSC_attempt) AS total_SMPP_to_SMSC_attempt,
            SUM(SMPP_to_SMSC_success) AS total_SMPP_to_SMSC_success,
            SUM(SMPP_to_SMSC_sysfail+SMPP_to_SMSC_userfail+SMPP_to_SMSC_smfail) AS total_SMPP_to_SMSC_Failure,
            SUM(SMPP_to_SMSC_byte) AS total_SMPP_to_SMSC_byte,
            SUM(SMSC_to_MS_attempt) AS total_SMSC_to_MS_attempt,
            SUM(SMSC_to_MS_success) AS total_SMSC_to_MS_success,
            SUM(SMSC_to_MS_sysfail+SMSC_to_MS_userfail+SMSC_to_MS_smfail) AS total_SMSC_to_MS_Failure,
            SUM(SMSC_to_MS_byte) AS total_SMSC_to_MS_byte,
            SUM(SMSC_to_PPS_attempt) AS total_SMSC_to_PPS_attempt,
            SUM(SMSC_to_PPS_success) AS total_SMSC_to_PPS_success,
            SUM(SMSC_to_PPS_sysfail+SMSC_to_PPS_smfail+SMSC_to_PPS_userfail) AS total_SMSC_to_PPS_Failure,
            SUM(SMSC_to_PPS_byte) AS total_SMSC_to_PPS_byte,
            SUM(SMSC_to_VMS_attempt) AS total_SMSC_to_VMS_attempt,
            SUM(SMSC_to_VMS_success) AS total_SMSC_to_VMS_success,
            SUM(SMSC_to_VMS_sysfail+SMSC_to_VMS_userfail+SMSC_to_VMS_smfail) AS total_SMSC_to_VMS_Failure,
            SUM(SMSC_to_VMS_byte) AS total_SMSC_to_VMS_byte,
            SUM(SMSC_to_SMPP_attempt) AS total_SMSC_to_SMPP_attempt,
            SUM(SMSC_to_SMPP_success) AS total_SMSC_to_SMPP_success,
            SUM(SMSC_to_SMPP_sysfail+SMSC_to_SMPP_userfail+SMSC_to_SMPP_smfail) AS total_SMSC_to_SMPP_Failure,
            SUM(SMSC_to_SMPP_byte) AS total_SMSC_to_SMPP_byte
            FROM CSTA_DB.smscDetailData
             WHERE csta_datetime >= '{$startTime}' 
          AND csta_datetime <= '{$endTime}'";
       // echo "sumSql=$sumSql";     
        $res=mysqli_query($cstaDbConn,$sumSql);
        echo mysqli_error($cstaDbConn);
        $num=mysqli_num_rows($res);
        $row=@mysqli_fetch_array($res,MYSQLI_ASSOC);

        $title=array('Type');
        $valueArr=array();

        foreach ($row as $key => $value) {
           ///echo "Key: $key, Value: $value\n<br>";
            if(!$value) $value=0;
            $parts = explode('_', $key);
            $title[]= $parts[1].'_' .$parts[2]."\n".$parts[3];
            $hang=$parts[4];
            $lie=$parts[1].'_' .$parts[2].'_'.$parts[3];
            $valueArr[$hang][$lie]=$value;
        }

        $uniqueTitle=array_unique($title);

       // var_dump($uniqueTitle);
       
        $file_name = 'SMSC-CDR.csv';
        $file = fopen($file_name, 'w');
        fputcsv($file, $uniqueTitle);
             foreach ($valueArr as $one => $two) {
                //塞入每行数据
                $nowData=array("$one");
                foreach ($two as $key => $value) {
                    $nowData[]=$value;
                }
             fputcsv($file, $nowData);
            }


        //  关闭文件 
        fclose($file);
        // 检查文件是否存在
        if (file_exists($file_name)) {
            header("Content-type: application/csv");
            //use for download csv in https
            header('Expires: 0'); 
            header('Pragma: public'); 
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
            header('Cache-Control: public'); 
            header("Content-Disposition: attachment; filename=$file_name");
            readfile($file_name);
        } else {
            // 文件不存在时的处理
            echo "Error: File does not exist.";
        }
        break;
    case '320':
    //Service
	if($page_id == 0)
	{
               
       $file_name = 'MSC-Service.csv';
        $file = fopen($file_name, 'w');
     
        //没有hour 20240920
    $hang= [
        "Subs to sbus-GSM" => 5,
        "Subs to trunk-GSM" => 6,
        "Trunk to subs-GSM" => 7,
        "Trunk to trunk" => 8,
        "Intraconnection" => 9,
        "Subs to IP-GSM" => 10,
        "Trunk to IP" => 11,
        "Mobile originated-GSM" => 12,
        "Mobile terminated-GSM" => 13,
        "In trunk" => 14,
        "Out trunk" => 15,
        "IP terminated"=>16,
        "Subs to sbus-UMTS" => 17,
        "Subs to trunk-UMTS" => 18,
        "Trunk to subs-UMTS" => 19,
        "Subs to IP-UMTS" => 20,
        "Mobile originated-UMTS" => 21,
        "Mobile terminated-UMTS" => 22,
    ];
    $lie=array("Type","Attempt","Success","CallDeny","NetBusy","CallerClear","SubBusy","NoAnswer","SignalErr","Duration");
    fputcsv($file, $lie);
    foreach ($hang as $key => $value) {
        //echo "Key: $key, Value: $value\n<br>";
        if($value<17){
            $database="mscSumData";
        }else{
            $database="mscSum3gData";
        }
        $sql="SELECT
        SUM( Attempt ) AS TotalAttempts,
        SUM( Success ) AS TotalSuccess,
        SUM( CallDeny ) AS TotalCallDeny,
        SUM( NetBusy ) AS TotalNetBusy,
        SUM( CallerClear ) AS TotalCallerClear,
        SUM( SubBusy ) AS TotalSubBusy,
        SUM( NoAnswer ) AS TotalNoAnswer,
        SUM( SignalErr ) AS TotalSignalErr,
        SUM( Duration ) AS TotalDuration
        FROM
        CSTA_DB.{$database} 
        WHERE csta_datetime >= '{$startTime}' 
        AND csta_datetime <= '{$endTime}'
        AND key_type = '{$value}'";
        //echo "sql=$sql<br>";
        $res=mysqli_query($cstaDbConn,$sql);
        echo mysqli_error($cstaDbConn);
        $num=mysqli_num_rows($res);
        // if (!$num){
        //     echo "<script>alert('MSC-Service Data is null');
        //     window.location.href='./general_csta_down.php?sysTypeNo=$sysTypeNo&show_type=$show_type&page_id=$page_id&sel_date_from=$sel_date_from&sel_date_to=$sel_date_to&keyOne=$keyOne&keyTwo=$keyTwo';
        //     </script>";
        //     fclose($file);
        //     return false;
        // }
        $row=@mysqli_fetch_array($res,MYSQLI_ASSOC);
        //   echo "<pre>";
        //   print_r($row);
        //   echo "</pre>";
        $valueArr=array($key);
        foreach ($row as $rowKey => $rowValue) {
            if(!$rowValue) $rowValue=0;
            // echo "Key: $rowKey, Value: $rowValue\n<br>";
             $valueArr[]=$rowValue;
         }
         fputcsv($file, $valueArr);
     }
            //  关闭文件 
            fclose($file);
        // 检查文件是否存在
        if (file_exists($file_name)) {
            header("Content-type: application/csv");
            //use for download csv in https
            header('Expires: 0'); 
            header('Pragma: public'); 
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
            header('Cache-Control: public'); 
            header("Content-Disposition: attachment; filename=$file_name");
            readfile($file_name);
        } else {
            // 文件不存在时的处理
            echo "Error: File does not exist.";
        }

	}
	//Trunk Group
	else if($page_id == 1)
	{
        $titleSql="
        SELECT
            T1.* 
        FROM
            OBJ_320.param_99 AS T1,
            paramConf AS T2 
        WHERE
            T1.level_1 = T2.level_1 
            AND T1.level_2 = T2.level_2 
            AND T1.level_3 = T2.level_3 
            AND T1.level_4 = T2.level_4 
            AND T1.level_5 = T2.level_5 
            AND T1.level_6 = T2.level_6 
            AND T1.level_7 = T2.level_7 
            AND T1.level_8 = T2.level_8 
            AND T1.level_9 = T2.level_9 
            AND T1.level_10 = T2.level_10 
            AND T2.name_2 = 'tgTitle'
        ";
    
        $result=@mysqli_query($objDbConn,$titleSql);
        $TrunkGroupCount=mysqli_num_rows($result);
       // $rows = @mysqli_fetch_array($result,MYSQLI_ASSOC);
        if($TrunkGroupCount>0)
        {
            while($rows = @mysqli_fetch_array($result))
            {
                //get the instanceNo of the tg
                $trunk_no=$rows[instanceNo]+0;
                $trunk_status[$trunk_no]=1;
                $trunk_element_title[$trunk_no]=$rows[initValue];
            }
        }
        // echo "<pre>";
        // echo print_r($trunk_element_title);
        // echo "</pre>";
    $dataSql="
	SELECT 
    key_e1_tg,
    SUM(Attempt) AS Total_Attempt,
    SUM(Success) AS Total_Success,
    SUM(Duration) AS Total_Duration,
    SUM(SignalErr) AS Total_SignalErr,
    SUM(CallDeny) AS Total_CallDeny,
    SUM(NetBusy) AS Total_NetBusy,
    SUM(CallerClear) AS Total_CallerClear,
    SUM(SubBusy) AS Total_SubBusy,
    SUM(NoAnswer) AS Total_NoAnswer
    FROM 
    (
        SELECT 
            Attempt, Success, Duration, SignalErr, CallDeny, NetBusy, CallerClear, SubBusy, NoAnswer, key_type, key_e1_tg 
        FROM 
            CSTA_DB.mscSumData 
        WHERE 
            csta_datetime >= '{$startTime}' 
           AND csta_datetime <= '{$endTime}' 
            AND key_type IN ('3', '4')
    ) AS combined
GROUP BY 
    key_e1_tg;
        ";


    $data=@mysqli_query($cstaDbConn,$dataSql);
    echo mysqli_error($cstaDbConn);
    $dataNum=mysqli_num_rows($data);
    if (!$dataNum){
        echo "<script>alert('MSC-Trunk Group Data is null');
        window.location.href='./general_csta_down.php?sysTypeNo=$sysTypeNo&show_type=$show_type&page_id=$page_id&sel_date_from=$sel_date_from&sel_date_to=$sel_date_to&keyOne=$keyOne&keyTwo=$keyTwo';
        </script>";
        return false;
    }
   // $dataRow=@mysqli_fetch_array($data,MYSQLI_ASSOC);
   $columnTitle=array(
    "TG No.",
    "Element Title",
    "Attempt",
    "Success",
    "Call Deny",
    "Net Busy",
    "Caller Clear",
    "Sub Busy",
    "No Answer",
    "Signal Error",
    "Total Call Duration",
);
   $file_name = 'MSC-Trunk Group.csv';
   $file = fopen($file_name, 'w');
   fputcsv($file, $columnTitle);
   if($dataNum>0)
    {
        while($dataRow = @mysqli_fetch_array($data,MYSQLI_ASSOC))
        {
            // echo "<pre>";
            // print_r($dataRow);
            // echo "</pre>";
            if($trunk_element_title[$dataRow['key_e1_tg']])
            {
     fputcsv($file,[$dataRow['key_e1_tg'],$trunk_element_title[$dataRow['key_e1_tg']],$dataRow['Total_Attempt'],
     $dataRow['Total_Success'],$dataRow['Total_CallDeny'],$dataRow['Total_NetBusy'],$dataRow['Total_CallerClear'],
     $dataRow['Total_SubBusy'],$dataRow['Total_NoAnswer'],$dataRow['Total_SignalErr'],$dataRow['Total_Duration']]);
            }

        }
    }
        //  关闭文件 
        fclose($file);
        // 检查文件是否存在
        if (file_exists($file_name)) {
            header("Content-type: application/csv");
            //use for download csv in https
            header('Expires: 0'); 
            header('Pragma: public'); 
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
            header('Cache-Control: public'); 
            header("Content-Disposition: attachment; filename=$file_name");
            readfile($file_name);
        } else {
            // 文件不存在时的处理
            echo "Error: File does not exist.";
        }
	}
	else if($page_id == 2)
	{
        $service_label=array(
			1=>"SUB SUB",
			2=>"SUB TRK",
			3=>"TRK SUB",
			4=>"TRK TRK",
			5=>"INTRA",
			6=>"SUB IP",
			7=>"TRK IP",
			8=>"MO",
			9=>"MT",
			10=>"IN TRK",
			11=>"OUT TRK",
		);
		$service_num=sizeof($service_label);
		
		$service_labelobj=array(
			"SUB SUB"=>"5,17",
			"SUB TRK"=>"6,18",
			"TRK SUB"=>"7,19",
			"TRK TRK"=>"8",
			"INTRA"=>"9",
			"SUB IP"=>"10,20",
			"TRK IP"=>"11",
			"MO"=>"12,21",
			"MT"=>"13,22",
			"IN TRK"=>"14",
			"OUT TRK"=>"15",
		);
        $file_name = 'MSC-Erlang.csv';
        $file = fopen($file_name, 'w');
        for($i=1;$i<=$service_num;$i++){
            fputcsv($file, [$service_label[$i].":"]);
            $keyType= explode(",",  $service_labelobj["".$service_label[$i]]); 
            $hourSql="
            SELECT 
            DATE_FORMAT(csta_datetime, '%m-%d %H:00:00') AS hour,
            SUM(Duration) AS Total_Duration
            FROM 
                CSTA_DB.mscSumData
            WHERE 
               csta_datetime >= '{$startTime}' 
                AND csta_datetime <= '{$endTime}' 
                AND key_type = '".$keyType[0]."'
            GROUP BY 
                hour
            ORDER BY 
                hour;
            ";
            //echo "$=$hourSql<br>";
            $hourData=@mysqli_query($cstaDbConn,$hourSql);
            echo mysqli_error($cstaDbConn);
            $hourDataNum=mysqli_num_rows($hourData);
            //echo "hourDataNum=$hourDataNum";
            $timeArr=array('','');
            $valueArr=array('','GSM');
            //GSM
            while($hourDataRow = @mysqli_fetch_array($hourData,MYSQLI_ASSOC))
            {
                // echo "<pre>";
                // print_r($hourDataRow);
                // echo "</pre>";
                $timeArr[]= str_replace(" ", "\r\n", $hourDataRow['hour']);
                if($hourDataRow['Total_Duration']){
                    $valueArr[]=change2point($hourDataRow['Total_Duration']/3600);    
                }else{
                    $valueArr[]="0";
                }
            }


            fputcsv($file, $timeArr);
            fputcsv($file, $valueArr);
            if(count($keyType)==2){
                $hour3GSql="
                SELECT 
                DATE_FORMAT(csta_datetime, '%m-%d %H:00:00') AS hour,
                SUM(Duration) AS Total_Duration
                FROM 
                    CSTA_DB.mscSum3gData
                WHERE 
                csta_datetime >= '{$startTime}' 
                AND csta_datetime <= '{$endTime}' 
                    AND key_type = '".$keyType[1]."'
                GROUP BY 
                    hour
                ORDER BY 
                    hour;
                ";
    
                $hour3GData=@mysqli_query($cstaDbConn,$hour3GSql);
                echo mysqli_error($cstaDbConn);
                $hour3GDataNum=mysqli_num_rows($hour3GData);
                if (!$hourDataNum &&!$hour3GDataNum){
                    echo "<script>alert('MSC-Erlang Data is null');
                    window.location.href='./general_csta_down.php?sysTypeNo=$sysTypeNo&show_type=$show_type&page_id=$page_id&sel_date_from=$sel_date_from&sel_date_to=$sel_date_to&keyOne=$keyOne&keyTwo=$keyTwo';
                    </script>";
                    fclose($file);
                    return false;
                }
                $value3GArr=array('',"UMTS");
                //UMTS
                while($hour3GDataRow = @mysqli_fetch_array($hour3GData,MYSQLI_ASSOC))
                {
                    $value3GArr[]=$hour3GDataRow['Total_Duration'];
                }
                fputcsv($file, $value3GArr);
            }
         

            // echo "<pre>";
            // print_r($value3GArr);
            // echo "</pre>";
            //fputcsv($file, []);
            //fputcsv($file, []);
        }
//  关闭文件 
fclose($file);
// 检查文件是否存在
if (file_exists($file_name)) {
    header("Content-type: application/csv");
    //use for download csv in https
    header('Expires: 0'); 
    header('Pragma: public'); 
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header('Cache-Control: public'); 
    header("Content-Disposition: attachment; filename=$file_name");
    readfile($file_name);
} else {
    // 文件不存在时的处理
    echo "Error: File does not exist.";
}
	}
	else if($page_id == 3)
	{
		$service_label=array(
			1=>"SUB SUB",
			2=>"SUB TRK",
			3=>"TRK SUB",
			4=>"TRK TRK",
			5=>"INTRA",
			6=>"SUB IP",
			7=>"TRK IP",
			8=>"MO",
			9=>"MT",
			10=>"IN TRK",
			11=>"OUT TRK",
		);
		$service_num=sizeof($service_label);
		
		$service_labelobj=array(
			"SUB SUB"=>"5,17",
			"SUB TRK"=>"6,18",
			"TRK SUB"=>"7,19",
			"TRK TRK"=>"8",
			"INTRA"=>"9",
			"SUB IP"=>"10,20",
			"TRK IP"=>"11",
			"MO"=>"12,21",
			"MT"=>"13,22",
			"IN TRK"=>"14",
			"OUT TRK"=>"15",
		);
        $file_name = 'MSC-BHCA.csv';
        $file = fopen($file_name, 'w');
        for($i=1;$i<=$service_num;$i++){
            fputcsv($file, [$service_label[$i].":"]);
            $keyType= explode(",",  $service_labelobj["".$service_label[$i]]); 
            $hourSql="
            SELECT 
            DATE_FORMAT(csta_datetime, '%m-%d %H:00:00') AS hour,
            SUM(Success) AS Total_Success
            FROM 
                CSTA_DB.mscSumData
            WHERE 
                csta_datetime >= '{$startTime}' 
                AND csta_datetime <= '{$endTime}'  
                AND key_type = '".$keyType[0]."'
            GROUP BY 
                hour
            ORDER BY 
                hour;
            ";
            $hourData=@mysqli_query($cstaDbConn,$hourSql);
            echo mysqli_error($cstaDbConn);
            $hourDataNum=mysqli_num_rows($hourData);
            $timeArr=array('','');
            $valueArr=array('','GSM');
            //GSM
            while($hourDataRow = @mysqli_fetch_array($hourData,MYSQLI_ASSOC))
            {
                // echo "<pre>";
                // print_r($hourDataRow);
                // echo "</pre>";
                $timeArr[]= str_replace(" ", "\r\n", $hourDataRow['hour']);
                $valueArr[]=$hourDataRow['Total_Success'];
            }


            fputcsv($file, $timeArr);
            fputcsv($file, $valueArr);
            if(count($keyType)==2){
                $hour3GSql="
                SELECT 
                DATE_FORMAT(csta_datetime, '%m-%d %H:00:00') AS hour,
                SUM(Success) AS Total_Success
                FROM 
                    CSTA_DB.mscSum3gData
                WHERE 
                csta_datetime >= '{$startTime}' 
                AND csta_datetime <= '{$endTime}'  
                    AND key_type = '".$keyType[1]."'
                GROUP BY 
                    hour
                ORDER BY 
                    hour;
                ";
    
                $hour3GData=@mysqli_query($cstaDbConn,$hour3GSql);
                echo mysqli_error($cstaDbConn);
                $hour3GDataNum=mysqli_num_rows($hour3GData);
                if (!$hourDataNum &&!$hour3GDataNum){
                    echo "<script>alert('MSC-BHCA Data is null');
                    window.location.href='./general_csta_down.php?sysTypeNo=$sysTypeNo&show_type=$show_type&page_id=$page_id&sel_date_from=$sel_date_from&sel_date_to=$sel_date_to&keyOne=$keyOne&keyTwo=$keyTwo';
                    </script>";
                    fclose($file);
                    return false;
                }
                $value3GArr=array('',"UMTS");
                //UMTS
                while($hour3GDataRow = @mysqli_fetch_array($hour3GData,MYSQLI_ASSOC))
                {
                    $value3GArr[]=$hour3GDataRow['Total_Success'];
                }
                fputcsv($file, $value3GArr);
            }
         

            // echo "<pre>";
            // print_r($value3GArr);
            // echo "</pre>";
            fputcsv($file, []);
            fputcsv($file, []);
        }       
//  关闭文件 
fclose($file);
// 检查文件是否存在
if (file_exists($file_name)) {
    header("Content-type: application/csv");
    //use for download csv in https
    header('Expires: 0'); 
    header('Pragma: public'); 
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header('Cache-Control: public'); 
    header("Content-Disposition: attachment; filename=$file_name");
    readfile($file_name);
} else {
    // 文件不存在时的处理
    echo "Error: File does not exist.";
}
    }
        break;
    default:
	    break;
    }

?>