<?php
session_start();

include 'includes/database.php';
include 'includes/functions.php';
$conn= new Functions();

if(!empty($_POST['name']) && !empty($_POST['password'])
&& !empty($_POST['username'])) {
    $name = $_POST['name'];
    $username = $_POST['username'];
    $password = $_POST['password'];



    //check for username availability
    $sql = "SELECT * FROM officer WHERE username =:username";
    $conn->query($sql);
    $conn->bind(":username", $username);
    if ($conn->rowCount() > 0) {
        echo "<script>
    $(function () { //ready
    toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
        toastr.error('Username Already Exists');
    });
    </script>";
        return false;
    }


    //check if admin name already exists
    $sql = "SELECT * FROM officer WHERE name =:name";
    $conn->query($sql);
    $conn->bind(":name", $name);
    if ($conn->rowCount() > 0) {
        echo "<script>
$(function () { //ready
          toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
          toastr.error('Conference Officer Already Exists');
      });
</script>";
        return false;
    }elseif(!$conn->Checkpassword($password)){
        echo "<script>
        $(function () { //ready
                  toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
                  toastr.error('Password must include one uppercase letter, one lowercase letter, one number, one special character such as $ or % and length should be between 6 and 16');
              });
        </script>";
        return false;
    }else{
       
        //all checks passed, update password in database
        $sql = "INSERT INTO officer (name, username, password)
        VALUES(:name, :username, :password)";
        $conn->query($sql);
        $conn->bind(":name", $name); 
        $conn->bind(":username", $username); 
        $conn->bind(":password", $conn->Password_Encryption($password));


        $send = $conn->execute();
        if ($send) {
            echo "<script>
$(function () { //ready
          toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
          toastr.success('Conference Officer <b>$name</b> Added Successfully');
      });
</script><meta http-equiv='refresh' content='5; conference-officer'>";
        }else {
            echo "<script>
$(function () { //ready
          toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
          toastr.error('An Error Occurred While Updating Data');
      });
</script> <meta http-equiv='refresh' content='5; conference-officer'>";
        }
        
    }


}else{
    echo "<script>
    $(function () { //ready
              toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
              toastr.error('All Marked (*) Are Required');
          });
    </script>";
        return false;
}