#!/usr/bin/php
<?php

error_reporting(E_ERROR | E_WARNING | E_PARSE);

checkIsCorrection();

function checkIsCorrection()
{
    try {
        $handler = connectDb();

        $result = $handler->query(
            "
            SELECT 
                u.exten AS exten,u.fullname AS fullname  
            FROM 
                phone2b.users AS u 
            WHERE  
                u.fullname LIKE '%SIP/%' AND 
                u.otherchan IS NULL OR 
                u.fullname LIKE '%DAHDI/%' AND 
                u.otherchan IS NULL;"
        );

        if (!$result) throw new Exception("failure on execute query");

        while ($row = $result->fetch_assoc()) {
            $string = strstr($row['fullname'], 'SIP') ? strstr($row['fullname'], 'SIP') : strstr($row['fullname'], 'DAHDI');
            updateUser($row['exten'], $row['fullname'], $string);
        }

        if (isset($result) && $result !== null) {
            $result->free_result();
        }
        $handler->close();
    } catch (Exception $ex) {
        error_log($ex->getMessage());
        return $ex->getCode();
    }
}

function updateUser($branch, $name, $string)
{
    try {
        $handler = connectDb();

        $result = $handler->query(
            "
            UPDATE 
                users AS u 
            SET 
                u.otherchan='$string',
                u.hasother='yes' 
            WHERE 
                u.exten='$branch'"
        );

        if (!$result) throw new Exception("failure on execute query");

        logTraderSip($branch, $name);

        $handler->close();
    } catch (Exception $ex) {
        error_log($ex->getMessage());
        return $ex->getCode();
    }
}

function logTraderSip($branch, $name)
{
    $logTraderSip = '/var/log/tsi/trader-sip/trader-sip.log';
    $currentDate = date('Y-m-d H:i:s');
    $message = " [NOTE] Correção efetuada no ramal $branch para $name";
    error_log($currentDate . $message . "\r\n", 3, $logTraderSip);
}

function connectDb($instance = null)
{
    if (!(isset($instance))) {
        $instance = mysqli_connect('localhost', 'root', '', 'phone2b', '3306');
        if (mysqli_connect_errno()) throw new Exception('failure on connect in database');
        if ($instance->connect_errno) {
            echo "Failed to connect to MySQL: (" . $instance->connect_errno . ") " . $instance->connect_error;
        }
    }

    return $instance;
}
