/*
This file is part of CMS Made Simple module: Tourney.
Copyright (C) 2014-2015 Tom Phane <tpgww@onepost.net>
Refer to licence and other details at the top of file Tourney.module.php
More info at http://dev.cmsmadesimple.org/projects/tourney
*/
if (!$this->CheckAccess('admod')) {
    $this->Redirect($id, 'defaultadmin', '', array('tmt_message' => $this->PrettyMessage('lackpermission', FALSE)));
}
$bid = $params['bracket_id'];
$pref = cms_db_prefix();
$sql = 'SELECT type FROM ' . $pref . 'module_tmt_brackets WHERE bracket_id=?';
$type = $db->GetOne($sql, array($bid));
if ($type !== FALSE) {
    $sch = new tmtSchedule();
    switch (intval($type)) {
        case Tourney::DETYPE:
            $res = $sch->InitDEMatches($this, $bid);
            break;
        case Tourney::RRTYPE:
            $res = $sch->NextRRMatches($this, $bid);
            break;
        default:
            //case Tourney::KOTYPE:
            $res = $sch->InitKOMatches($this, $bid);
            break;
    }
    unset($sch);
    $newparms = $this->GetEditParms($params, 'matchestab');
    if ($res === TRUE) {
                 }
                 $db->Execute($sql, array($name, $row['seeding'], $row['contactall'], $order, $tid));
                 $order++;
                 $contact = $row['contact'];
                 if ($contact != $pcontact) {
                     $funcs->UpdateFirstPlayer($tid, FALSE, $contact);
                 }
                 //update contact in people table
                 $db->Execute($sql2, array($tid));
                 $db->Execute($sql3, array($tid));
             }
             unset($row);
         }
         if ($newtype) {
             if (!$sch) {
                 $sch = new tmtSchedule();
             }
             $sch->ScheduleMatches($this, $bracket_id);
         }
         if ($newtype || $matches || $results) {
             $sql = 'UPDATE ' . $pref . 'module_tmt_brackets SET chartbuild=1 WHERE bracket_id=?';
             $db->Execute($sql, array($bracket_id));
         }
     }
     $message = $res ? '' : $this->PrettyMessage('err_save', FALSE);
 } elseif (!empty($data->errmsg)) {
     $message = $data->errmsg;
 }
 if (isset($params['apply'])) {
     if (isset($params['newbracket'])) {
         unset($params['newbracket']);
    $val = $params['bracket_id'];
} elseif (!empty($params['alias'])) {
    $sql = 'SELECT * FROM ' . $pref . 'module_tmt_brackets WHERE alias=?';
    $val = $params['alias'];
} else {
    DisplayErrorPage($this, $smarty, $db, $params, TRUE, $this->Lang('err_tag'));
    return;
}
$bdata = $db->GetRow($sql, array($val));
if (!$bdata) {
    DisplayErrorPage($this, $smarty, $db, $params, TRUE, $this->Lang('err_missing'));
    return;
}
$bracket_id = $bdata['bracket_id'];
//refresh the matches table,if necessary
$sch = new tmtSchedule();
switch ($bdata['type']) {
    case Tourney::DETYPE:
        $res = $sch->UpdateDEMatches($this, $bracket_id);
        break;
    case Tourney::RRTYPE:
        $res = $sch->NextRRMatches($this, $bracket_id);
        break;
    default:
        // case Tourney:KOTYPE:
        $res = $sch->UpdateKOMatches($this, $bracket_id);
        break;
}
if ($res === TRUE) {
    $bdata['chartbuild'] = 1;
}
         $sql = 'INSERT INTO ' . $pref . 'module_tmt_people (' . implode(',', $fields) . ') VALUES (' . $fillers . ')';
         $db->Execute($sql, $values);
     }
 }
 if (!empty($bracketdata['matches']) && is_array($bracketdata['matches'])) {
     $fields = array_keys($bracketdata['matches'][0]);
     $fixer = array_search('bracket_id', $fields);
     $fixer2 = array_search('match_id', $fields);
     if ($fixer !== FALSE && $fixer2 !== FALSE) {
         //TODO flag 'added'
         $fixer3 = array_search('nextm', $fields);
         //irrelevant for RR
         $fixer4 = array_search('nextlm', $fields);
         //ditto and for KO
         $mc = count($bracketdata['matches']);
         $sch = new tmtSchedule();
         $mid = $sch->ReserveMatches($db, $pref, $mc);
         $offset = $mid - $bracketdata['matches'][0]['match_id'];
         //lowest match-no. is sorted 1st
         foreach ($bracketdata['matches'] as $thisone) {
             $values = array_values($thisone);
             $values[$fixer] = $bid;
             $values[$fixer2] = $mid;
             if ($fixer3 !== FALSE) {
                 if ($values[$fixer3]) {
                     $values[$fixer3] += $offset;
                 }
             }
             if ($fixer4 !== FALSE) {
                 if ($values[$fixer4]) {
                     $values[$fixer4] += $offset;
         $to = $params['real_action'] == 'moveup' ? $from - 1 : $from + 1;
         if ($to > 0) {
             $sql = 'UPDATE ' . $pref . 'module_tmt_teams SET displayorder=' . $from . ' WHERE bracket_id=? AND displayorder=' . $to;
             $db->Execute($sql, array($bid));
             $sql = 'UPDATE ' . $pref . 'module_tmt_teams SET displayorder=' . $to . ' WHERE bracket_id=? AND team_id=?';
             $db->Execute($sql, array($bid, (int) $movetid));
         }
     }
     $params['real_action'] = 'edit';
     break;
 default:
     //refresh matches if appropriate
     $pref = cms_db_prefix();
     $sql = 'SELECT COUNT(match_id) AS num FROM ' . $pref . 'module_tmt_matches WHERE bracket_id=? AND flags=0';
     if ($db->GetOne($sql, array($bid))) {
         $sch = new tmtSchedule();
         $sql = 'SELECT type FROM ' . $pref . 'module_tmt_brackets WHERE bracket_id=?';
         $type = $db->GetOne($sql, array($bid));
         switch ($type) {
             case Tourney::DETYPE:
                 $sch->UpdateDEMatches($this, $bid);
                 break;
             case Tourney::RRTYPE:
                 $sch->NextRRMatches($this, $bid);
                 break;
             default:
                 //case Tourney::KOTYPE:
                 $sch->UpdateKOMatches($this, $bid);
                 break;
         }
         unset($sch);
                 if ($errmsg) {
                     $msg .= '<br />' . $errmsg;
                 }
             }
             if ($save) {
                 $sql = 'UPDATE ' . $pref . 'module_tmt_matches SET playwhen=?, score=?,	status=? WHERE match_id=?';
                 $db->Execute($sql, array($when, $score, $res, $params['match']));
                 $t = $db->GenID($pref . 'module_tmt_history_seq');
                 if ($params['sender']) {
                     $by = $params['sender'];
                 }
                 $dt->modify('now');
                 $when = strftime('%F %T', $dt->getTimestamp());
                 $sql = 'INSERT INTO ' . $pref . 'module_tmt_history (history_id,bracket_id,changer,changewhen,olddata,newdata,comment VALUES (?,?,?,?,?,?,?)';
                 $db->Execute($sql, array($t, $bracket_id, $by, $when, NULL, $tres, $this->Lang('match_added', $params['match'])));
                 $funcs = new tmtSchedule();
                 $funcs->ScheduleMatches($this, $bracket_id);
             }
             $params = array('bracket_id' => $bracket_id, 'view' => $params['view'], 'message' => $msg);
             $this->RedirectForFrontEnd($id, $returnid, 'default', $params);
         } else {
             $key = 'err_noresult2';
         }
     } else {
         $key = 'err_nomatch';
     }
 } else {
     $key = 'err_captcha';
 }
 $smarty->assign('message', $this->Lang($key));
 //fall into repeat presentation