<?
$servername = "db";
$username = 'kalskeborec';
$password = 'Kalskeborec1!23$';
$db = 'kalskeborec';
$race_name = $race_blob[$race_to_write];
// mail send
  function read_cb($ch, $fp, $length) {
    return fread($fp, $length);
  }



// Create connection
$conn = new mysqli($servername, $username, $password, $db);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// would be nice to check if the name / nick / email exists
$sql = "SELECT ID, NAME, SURNAME, EMAIL from REGISTERED where EMAIL_CHECK like '".$email_check."'";
  $result = $conn->query($sql);
  if ($result->num_rows > 0){
    $unique_email = False;
  }
  else{
    $unique_email = True;
  }

// Geting the values from the script above. -< register.php

if($unique_email){
  $stm = $conn->prepare("INSERT INTO REGISTERED (ID, NAME, SURNAME, EMAIL, PHONE, NICK, RACE, TIME, TRACKLOG, EMAIL_CHECK, CONFIRMED, PAID) 
  values (NULL,?,?,?,?,?,?,'[None]','[None]',?,'0','0')");
  $stm->bind_param('sssssss',$fname, $lname, $email, $phone, $nick, $race_to_write, $email_check);


  if ($stm->execute() === TRUE) {
    //echo "New record created successfully";
    $sql = "SELECT ID, NAME, SURNAME, EMAIL, PHONE, NICK, RACE from REGISTERED where EMAIL_CHECK like '".$email_check."'";
    $result = $conn->query($sql);
    if ($result->num_rows == 1){
      while($racer = $result->fetch_assoc()) {
        $racers[] = $racer;
      }
      $write_success = ["result"=> True, "reason" => "Přihlášeno"];
      $logged_racer = $racers[0];
      $id = $logged_racer['ID'];
      // Must send email somehow. :-)
        $fp = fopen('php://memory', 'r+');
        $string = "From: Kalské Borec <ventil@spoton.cz>\r\n";
        $string .= "To: <$email>\r\n";
        $string .= "Date: " . date('r') . "\r\n";
        $string .= "Subject: Kalske Borec\r\n";
        $string .= "Content-Type: text/html; charset=\"utf-8\"";
        $string .= "Content-Transfer-Encoding: quoted-printable";
        $string .= "\r\n";
        $string .= "<b>Děkuji, $fname $lname, za registraci na Kalského Borca <span style=\"color: green;\">//24</span></b>
          <p>Jako první věc, poprosím o potvrzení emailu na <a href=\"http://$base_url/confirm.php?email_check=$email_check\">
          http://$base_url/confirm.php?email_check=$email_check</a></p>
          <p>Pod tímto odkazem pak můžeš sledovat jestli s tebou počítám, nebo stav zaplacení startovného.</p>\r\n
          <p>
          Číslo registrace: $id<br>
          Okruh, resp. závod: $race_to_write ($race_name)<br>
          Pod přezdívkou: $nick<br>
          </p>
          <p>
          Datum konání: 23.3.2024<br>
          Start na závod //Kalský Borec, tedy ten největší: 9:00 <br>
          Start samostatných okruhů //Freeride a //XC: 10:00<br>
          Start //Junior a //Rodina: 12:00<br>
          </p>
          <p>
          Startovné: 400,-<br>
          Číslo účtu: 1262023012/3030<br>
          Zpráva: Kalské Borec 24, $id<br>
          Var. Symbol: $id <br>
          <img src=\"https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=SPD*1.0*ACC:CZ9430300000001262023012*RN:MILAN%20TOMAN*AM:400*CC:CZK*MSG:KALSKE%20BOREC-$id&choe=UTF-8\"><br>
          Jídlo a pití máš v ceně, nezávodníci pak přispívají na místě, pokuď bude hlad a žízeň.
          </p>
          
          <p><b>Abys k nám trefil:</b><br>
          Kaly 62, 59455, Kaly.
          <a href=\"https://en.mapy.cz/s/demanuzomo\">//MAPA</a>
          <img src=\"http://$base_url/img/mapa.jpg\" alt=\"Mapa k zavodu\">
          </p>
          
          <p>Kolu zdar,<br>
          <p>Milan \"Ventil\" Toman</p>";
        $string .= "\r\n";
        fwrite($fp, $string);
        rewind($fp);
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => 'smtps://mail.spoton.cz',
            CURLOPT_MAIL_FROM => '<ventil@spoton.cz>',
            CURLOPT_MAIL_RCPT => ["<$email>"],
            CURLOPT_USERNAME => 'ventil',
            CURLOPT_PASSWORD => '3 litry Kvasaru!',
            CURLOPT_USE_SSL => CURLUSESSL_ALL,
            CURLOPT_READFUNCTION => 'read_cb',
            CURLOPT_INFILE => $fp,
            CURLOPT_UPLOAD => true,
            CURLOPT_VERBOSE => true,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
      $x = curl_exec($ch);
      if ($x === false) {
        echo curl_errno($ch) . ' = ' . curl_strerror(curl_errno($ch)) . PHP_EOL;
      }
      curl_close($ch);
      fclose($fp);
    }
    else{
      $write_success = ["result"=> False, "reason" => "Error: Duplikátní záznam závodnika, napiš Ventilovi"];
    }
  } else {
    $write_success = ["result"=> False, "reason" => "Error: " . $stm . ": " . $conn->error];
  }
}
else {
  $write_success = ["result"=> False, "reason" => "Závodník s tímto emailem už existuje"];
}


$conn->close();
?>
