#!/usr/bin/php
<?php

error_reporting(E_ERROR | E_WARNING | E_PARSE);

try {
    isEmpty($argv['1'], "Missing first option", 422);
    
    $beginDate = strtotime($argv['1']);
    if($beginDate === false){
        throw new Exception("Date badly formated", 500);
    }
    
    isEmpty($argv['2'], "Missing second option", 422);
    $iterations = intval($argv['2']);
    if($iterations == 0){
        throw new Exception("Second option must be a number", 500);
    }

    isEmpty($argv['3'], "Missing third option", 422);
    $choice = $argv['3'];

    $mysqli = connectDb();

    switch (true) {
        case ($choice == "M" || $choice == "m"):
            skipMontly($mysqli, $iterations, $beginDate);
            break;
        case ($choice == "W" || $choice == "w"):
            skipWeek($mysqli, $iterations, $beginDate);
            break;
        default:
            throw new Exception("Non existent or badly formatted option", 500);
            break;
    }
    mysqli_close($mysqli);
} catch (Exception $ex) {
    error_log($ex->getMessage());
    return $ex->getCode();
}

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

    return $instance;
}

function skipMontly($mysqli, $iterations, $beginDate)
{
    for ($i = 0; $i < $iterations; $i++) {
        $initMonth = $i;
        $nextMonth = $i + 1;
        
        $dateStart = date("Y-m-d H:i:s ", strtotime("+$initMonth Month", $beginDate));
        $dateEnd = date("Y-m-d H:i:s", strtotime("+$nextMonth Month -1 Seconds", $beginDate));

        $sqlFileResult = $mysqli->query("CALL mamute.sp_import('$dateStart', '$dateEnd')");

        $sqlCount = 1;
        if ($sqlFileResult == false) {
            throw new Exception("Query#[" . $sqlCount . "], [" . $mysqli->errno . "]: '" . $mysqli->error . "' }", 500);
        }

        while ($mysqli->more_results()) {
            $sqlCount++;

            if ($mysqli->next_result() == false) {
                throw new Exception("Query#[" . $sqlCount . "], Error No: [" . $mysqli->errno . "]: '" . $mysqli->error . "' }", 500);
            }
        }
    }
}

function skipWeek($mysqli, $iterations, $beginDate)
{
    for ($i = 0; $i < $iterations; $i++) {
        $initWeek = $i;
        $nextWeek = $i + 1;

        $dateStart = date("Y-m-d H:i:s ", strtotime("+$initWeek Week", $beginDate));
        $dateEnd = date("Y-m-d H:i:s", strtotime("+$nextWeek Week -1 seconds", $beginDate));

        $sqlFileResult = $mysqli->query("CALL mamute.sp_import('$dateStart', '$dateEnd')");

        $sqlCount = 1;
        if ($sqlFileResult == false) {
            throw new Exception("Query#[" . $sqlCount . "], [" . $mysqli->errno . "]: '" . $mysqli->error . "' }", 500);
        }

        while ($mysqli->more_results()) {
            $sqlCount++;

            if ($mysqli->next_result() == false) {
                throw new Exception("Query#[" . $sqlCount . "], Error No: [" . $mysqli->errno . "]: '" . $mysqli->error . "' }", 500);
            }
        }
    }
}

function isEmpty($param, $exception, $errorNumber){
    if(empty($param)){
        throw new Exception($exception, $errorNumber);
    }
}