<?php

require_once 'GCM_Loader.php';
$clanID = $_REQUEST['clanID'];
SendNotificationToNextAttacker($clanID);
if ($result == false) {
    echo json_encode(['errorMsg' => 'An error occured: ' . dbGetErrorMsg()]);
    goto DONE;
} else {
    // If this is the first attack
    //        $sqlIdentity = "select @@identity as EntityId";
    //        $resultID    = sqlsrv_query(Database::getInstance()->getConnection(), $sqlIdentity);
    //        $rowIdentity = sqlsrv_fetch_array($resultID);
    //        $AttackID    = $rowIdentity["EntityId"];
    // SET the "NextAttacker" flag (whether it is set or not)
    // Get the next player that must attack after this one
    $sql = "\n            SELECT TOP(1) B.OurParticipantID FROM\n                (SELECT TOP (2) A.OurParticipantID, A.OurRank FROM\n                    (SELECT  GameName, OurRank, TimeOfAttack, OurParticipantID, 1 AS Priority\n                        FROM [COC].[dbo].[View_WarProgress] WHERE WarID = {$WarID} AND TimeOfAttack IS NULL AND [FirstAttack] = 1\n                    UNION\n                        SELECT  GameName, OurRank, TimeOfAttack, OurParticipantID, 0 AS Priority\n                    FROM [COC].[dbo].[View_WarProgress] WHERE WarID = {$WarID} AND TimeOfAttack IS NULL AND FirstAttack = 0\n                    ) AS A  ORDER BY A.Priority DESC, A.timeofattack ASC, A.OurRank DESC\n                ) AS B ORDER BY B.OurRank DESC\n        ";
    $result = $db->dbQuery($sql);
    if ($result == false) {
        echo json_encode(['errorMsg' => 'An error occured: ' . dbGetErrorMsg()]);
        goto DONE;
    } else {
        $record = sqlsrv_fetch_array($result, SQLSRV_FETCH_BOTH);
        $OurParticipantID = $record['OurParticipantID'];
        // Set the NextAttacker flag for the player so that he can be prompt to attack
        $sql = "\n                UPDATE OurParticipant SET NextAttacker = 1\n                WHERE OurParticipantID = {$OurParticipantID}\n            ";
        $result = $db->dbQuery($sql);
        if (!$result) {
            $data['result'][0] = array('success' => 0, 'error' => dbGetErrorMsg());
        } else {
            array('success' => 1, 'error' => '');
            SendNotificationToNextAttacker();
        }
    }
}
DONE: