<?php
class ChairmanRaceService {
    private $db;
    private $config;

    public function __construct(mysqli $db, array $config=array()) {
        $this->db = $db;
        $this->config = $config;
    }

    public function getRaceRanking($raceDate, $venue='', $raceNum=0) {
        if (!chairman_table_exists($this->db, 'wr_chairman_production_score_v44')) return array();
        $where=array("race_date=" . chairman_q($this->db,$raceDate));
        if($venue!=='') $where[]="venue=" . chairman_q($this->db,$venue);
        if(chairman_i($raceNum)>0) $where[]="race_num=" . chairman_i($raceNum);
        return chairman_rows($this->db, "SELECT * FROM wr_chairman_production_score_v44 WHERE ".implode(' AND ',$where)." ORDER BY race_num ASC, race_rank ASC, calibrated_score DESC");
    }

    public function getRaceSummary($raceDate, $venue='', $raceNum=0) {
        if (!chairman_table_exists($this->db, 'wr_chairman_race_optimizer_v44')) return array();
        $where=array("race_date=" . chairman_q($this->db,$raceDate));
        if($venue!=='') $where[]="venue=" . chairman_q($this->db,$venue);
        if(chairman_i($raceNum)>0) $where[]="race_num=" . chairman_i($raceNum);
        return chairman_rows($this->db, "SELECT * FROM wr_chairman_race_optimizer_v44 WHERE ".implode(' AND ',$where)." ORDER BY race_num ASC");
    }

    public function getAnalysisPayload($raceDate, $venue='', $raceNum=0) {
        return array(
            'framework_version'=>isset($this->config['framework_version']) ? $this->config['framework_version'] : '1.3',
            'race_date'=>$raceDate,
            'venue'=>$venue,
            'race_num'=>chairman_i($raceNum),
            'summary'=>$this->getRaceSummary($raceDate,$venue,$raceNum),
            'ranking'=>$this->getRaceRanking($raceDate,$venue,$raceNum),
            'generated_at'=>date('c')
        );
    }
    public function getProductionPayload($raceDate, $venue='', $raceNum=0) {
        $ranking = $this->getRaceRanking($raceDate,$venue,$raceNum);
        $summary = $this->getRaceSummary($raceDate,$venue,$raceNum);
        return array(
            'status' => 'OK',
            'source' => 'wr_chairman_production_score_v44',
            'framework_version'=>isset($this->config['framework_version']) ? $this->config['framework_version'] : '1.4',
            'race_date'=>$raceDate,
            'venue'=>$venue,
            'race_num'=>chairman_i($raceNum),
            'counts'=>array('summary'=>count($summary),'ranking'=>count($ranking)),
            'summary'=>$summary,
            'ranking'=>$ranking,
            'generated_at'=>date('c')
        );
    }

}
