<?php

/**** this script contains sql statements that manipulates the database*****/
session_start();
include_once('../../config/config.php');

//if the new user form has been submitted
if (isset($_POST['create_account'])) {
  //echo "here we come";

  $first_name = filter_var($_POST['firstName']);
  $last_name  = filter_var($_POST['lastName']);
  $email      = filter_var($_POST['email']);
  $username   = filter_var($_POST['username']);
  $password   = filter_var($_POST['password']);
  $repass     = filter_var($_POST['repass']);
  $type       = filter_var("user");
  $new_pass   = sha1($password);

  if ($password != $repass) {
    echo "3"; //passwords dont match..
  } else {
    //insert sql statement
    $statement  = "insert into system_users(first_name, last_name, email_address, username, password, 
                    user_type) values(?,?,?,?,?,?)";
    try {
      //prepare the sql statement
      $sql   = $db->prepare($statement);
      $array = array($first_name, $last_name, $email, $username, $new_pass, $type);
      $result = $sql->execute($array);

      if ($result) {
        echo "1"; //a user account has been created successfully
      } else {
        echo "2"; //there was an error creating the user account
      }
    } catch (PDOException $e) {
      $e->getMessage();
    }
  }
}

//delete users
if (isset($_POST['delete_user'])) {
  $user_id   = $_POST['userid'];
  $statement = "delete  from system_users where user_id=?";
  try {
    $sql   = $db->prepare($statement);
    $array = array($user_id);
    $query = $sql->execute($array);

    if ($query) {
      echo "1";
    } else {
      echo "2";
    }
  } catch (PDOException $e) {
    echo $e->getMessage();
  }
}

//update Password
if (isset($_POST['update_password'])) {
  $oldpass = filter_var($_POST['oldpass']);
  $newpass = filter_var($_POST['newpass']);
  $repass  = filter_var($_POST['repass']);
  $user    = $_SESSION['user_id'];

  //checks if the current password entered is correct;
  $query = $db->query("select password from system_users where user_id='$user'");
  if ($query) {
    $row = $query->fetch();
    if ($row['password'] != sha1($oldpass)) {
      echo "2";
    } else {
      //checks if the new password entered is the same with the re entered password
      if ($newpass != $repass) {
        echo "3";
      } else {
        $sql = "update system_users set password=? where user_id='$user' ";
        try {
          $prepare = $db->prepare($sql);
          $array   = array(sha1($newpass));
          $execute = $prepare->execute($array);

          if ($execute) {
            echo "1";
          } else {
            echo "4";
          }
        } catch (PDOException $e) {
          //$e->getMessage();
        }
      }
    }
  }
}
