<?php
// School info
Function SchoolAddress(){?>
<h2>DE GOODNESS N/P SCHOOL</h2>
<p>Oke Baby Area, Apata Igbala Community, Zone AI, <br>
  Off Ademola Ishola Road, Along Ogbomoso Ikoyi Road.
</p>
<?php 
}

Function SchoolName(){?>
  DE GOODNESS N/P SCHOOL
  <?php
}
// Function to encrypt your value
function encryptData($data, $key = 'my-secret-key') {
    $cipher = "AES-128-CTR";           // Encryption method
    $options = 0;                      // Default options
    $iv = '1234567891011121';          // Must be 16 characters long

    $encrypted = openssl_encrypt($data, $cipher, $key, $options, $iv);

    return urlencode($encrypted); // make it safe for URL
}
// Function to decrypt value
function decryptData($encryptedData, $key = 'my-secret-key') {
    $cipher = "AES-128-CTR";
    $options = 0;
    $iv = '1234567891011121'; // Same as used in encryption

    $decrypted = openssl_decrypt(urldecode($encryptedData), $cipher, $key, $options, $iv);

    return $decrypted;
}

// Creating a slug
function createSlug($string) {
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string), '-'));
    return $slug;
}

// 1. Reusable compression function
function compressImage($source, $destination, $quality = 60) {
    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg') {
        $image = imagecreatefromjpeg($source);
    } elseif ($info['mime'] == 'image/png') {
        $image = imagecreatefrompng($source);
    } else {
        return false; // unsupported type
    }

    return imagejpeg($image, $destination, $quality);
}

// Get a meaningful time and date for the message sent
Function TimeDifference(){
  
  global $timeSent;

  $time = new DateTime($timeSent);
  $now = new DateTime();

  $diff = $now->diff($time);
  if ($diff->y > 0) {
      $timediff = $diff->y.' years ago.';
  }else if ($diff-> m > 0) {
      $timediff = $diff-> m.' months ago.';
  }
  else if ($diff-> d > 0) {
      $timediff = $diff-> d.' days ago.';
  }
  else if ($diff-> h > 0) {
      $timediff = $diff-> h.' hours ago.';
  }
  else if ($diff-> i > 0) {
      $timediff = $diff-> i.' minutes ago.';
  }else{
    $timediff = 'Just now.';
  }

  return $timediff;

}

Function EditStd(){
  global $stdId;
  global $surName;
  global $otherNames;
  global $gender;
  global $class;
  global $dob;
  global $password;
  ?>
  <div id="modal-<?= $stdId ?>" class="modal">
    <div class="modal-content" style="margin-top:50px;">
      <div class="modal-header">Edit Student</div>
      <div class="modal-body">
        <!-- Input form starts here -->
        <form action="" method="POST">
          <div class="row">
            <div class="col-lg-6">
              <div class="single-input">
                <label>Surname</label>
                <div class="my-input">
                  <input type="text" 
                  required="" 
                  autocomplete="off" 
                  name="surname" 
                  value="<?= $surName?>">
                </div>
              </div>
            </div>

            <div class="col-lg-6">
              <div class="single-input">
                <label>Other Names</label>
                <div class="my-input">
                  <input type="text" 
                  required="" 
                  autocomplete="off" 
                  name="othername" 
                  value="<?=$otherNames?>">
                </div>
              </div>
            </div>

            <div class="col-lg-6">
              <div class="single-input">
                <label>Gender</label>
                <div class="my-input">
                  <select name="gender">
                    <option value="<?=$gender?>"><?=$gender?></option>
                    <option value="M">Male</option>
                    <option value="F">Female</option>
                  </select>
                </div>
              </div>
            </div>

            <div class="col-lg-6">
              <div class="single-input">
                <label>Date of birth</label>
                <div class="my-input">
                  <input type="date" 
                  name="dob" 
                  value="<?=$dob?>">
                </div>
              </div>
            </div>

            <div class="col-lg-6">
              <div class="single-input">
                <label>New Password</label>
                <div class="my-input">
                  <input type="password" 
                  name="new_pass" 
                  value="<?=$password?>">
                </div>
              </div>
            </div>

            <div class="col-lg-6">
              <div class="single-input">
                <label>Confirm Password</label>
                <div class="my-input">
                  <input type="password" 
                  name="confirm" 
                  value="<?=$password?>">
                </div>
              </div>
            </div>
            <input type="hidden" name="stdId" value="<?=$stdId?>">
          </div>
         
          <!-- End product and quality  -->
          <button type="submit" name="upd-std" class="btn btn-success mt-3">Update Student</button>
        </form>
        <!-- End Form action -->
      </div>
      <!-- End Modal body -->
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" onclick="closeModal('modal-<?= $stdId ?>')">Cancel</button>
      </div>
    </div>
    <!-- Modal Content -->
  </div>
  <!-- Modal overall -->
<?php }


Function UserLogin(){
	global $pdo;
	if (isset($_POST['login-btn'])) {
		
		$email = $_POST['email'];
		$password = $_POST['password'];

		if (empty($email && $password)) {
			echo "<div class='alert alert-danger'>All Fields are required</div>";
		}else{
			// Get details from the database
			$retrieve = "SELECT password, firstName FROM user_tb 
						WHERE email = ? ";
			$stmt = $pdo->prepare($retrieve);
			$stmt->execute([$email]);

			$dataDetails = $stmt->fetch(PDO::FETCH_ASSOC);
			$fetchPassword = $dataDetails['password'];
			$fetchName 		= $dataDetails['firstName'];

			if (password_verify($password, $fetchPassword)) {
				$_SESSION['mail'] = $email;
				$_SESSION['firstName'] = $fetchName;

				// Get the brandName
				$brand = "SELECT displayName FROM user_acct
							WHERE userEmail = ?";
				$brandPdo = $pdo->prepare($brand);
				$brandPdo->execute([$email]);
				$theData = $brandPdo->fetch(PDO::FETCH_ASSOC);
				$brandName = $theData['displayName'];

				$_SESSION['brandName'] = $brandName;
				$_SESSION['brandProfile'] = $brandName;

				header('Location:index.php');
			}else{
				echo "<div class='alert alert-danger'>Invalid Details.</div>";
			}

			
		}
	}
}

Function EditScores(){
  global $stdId;
  global $surName;
  global $otherNames;
  global $resultId;
  global $dataTest;
  global $secondTest;
  global $dataExam;?>
  <div id="modal-<?= $stdId ?>" class="modal">
    <div class="modal-content" style="margin-top:100px;">
      <div class="modal-header">Edit Student Grade</div>
      <div class="modal-body">
        <!-- Input form starts here -->
        <form action="" method="POST">
          <input type="hidden" name="resultId" value="<?= $resultId ?>">
          <!-- Delete Student with score Confirmation Modal -->
          <div id="delete-score-<?=$stdId?>" class="modal" style="z-index: 999999">
            <input type="hidden" name="subj-input" id="deleteSubValue">
            <div class="modal-content" style="margin-top:50px;">
              <div class="modal-header">Remove Confirmation</div>
              <div class="modal-body">
                Are you sure you want to remove this student with their score?
                <br><br><span><i>This means the student and their score(s) will no longer appear for this subject again</i></span>.
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal('delete-score-<?=$stdId?>')">No, Cancel
                </button>

                <button type="submit" name="del-stdScore" class="btn btn-danger">Yes, Remove
                </button>
              </div>
            </div>
          </div>
          <?php
          $surname = $surName;
          $others   = $otherNames;
          $fullName = $surName.' '. $others;
          ?>
          <input type="text" class="form-control" disabled="" value="<?= $fullName?>" >

          <!-- Price and Quantity -->
          <div class="input-group mt-4">
            <div class="label-wraps">
              <label>Test1</label>
              <label>Test2</label>
              <label>Exam Score</label>
            </div>
            <!-- Test1 scores -->
            <div class="input-wraps">
              <div class="price-box">
                <input type="number" name="test" autocomplete="off" 
                 value="<?php echo $dataTest;?>" 
                  required>
              </div>

              <!-- Test2 scores -->
              <div class="price-box">
                <input type="number" name="test2" autocomplete="off" 
                 value="<?php echo $secondTest;?>" 
                  required>
              </div>

              <!-- Exam Scores -->
              <div class="quant-box">
                <input type="number" name="exam" autocomplete="off"
                 value="<?php echo $dataExam;?>"
                  required>
              </div>
            </div>
          </div>
          <!-- End product and quality  -->
          <button type="submit" name="upd-std" class="btn btn-sm btn-success mt-3">
            <i class="fa fa-sync"></i>Update Student
          </button>

          <button type="button" class="btn btn-sm btn-danger mt-3" 
            onclick="openModal('delete-score-<?=$stdId?>')">
            <i class="fa fa-trash"></i> Delete Score 
          </button>
        </form>
        <!-- End Form action -->
      </div>
      <!-- End Modal body -->
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" 
          onclick="closeModal('modal-<?= $stdId ?>')"><i class="fa fa-window-close"></i> Cancel
        </button>
      </div>
    </div>
    <!-- Modal Content -->
  </div>
  <!-- Modal overall -->
<?php }

Function AddProduct(){?>
  <div id="modal-add" class="modal">
      <div class="modal-content" style="margin-top:100px;">
          <div class="modal-header">Add New Product <i class="fa fa-plus-circle"></i></div>
          <div class="modal-body">
              <form action="" method="POST" enctype="multipart/form-data" >
              	<!-- Product name -->
                <label style="padding-left: 30px;">Product Name:</label>
              	<input type="text" name="prod-name" class="form-control" placeholder="Product Name" required autocomplete="off">

                  <!-- Add a product image -->
                  <!-- <input type="hidden" name="slide_image">
                  <div class="upload-wraps">
                    <div class="uploads mt-3">
                      <img alt="" src="images/logo.png" id = "image" >
                      <div class="rightRound" id = "upload">
                        <input type="file" name="slide_image" id = "fileImg" accept=".jpg, .jpeg, .png">
                        <i class = "fa fa-camera"></i>
                      </div>
                      <div class="leftRound" id = "cancel" style = "display: none;">
                        <i class = "fa fa-times"></i>
                      </div>
                    </div>
                  </div>  -->
                  <!-- Price and Quantity -->
                  <div class="input-group mt-3">
                    <div class="label-wraps">
                      <label>Unit Price</label>
                      <label>Product Quantity</label>
                    </div>
                    <div class="input-wraps">
                      <div class="price-box">
                        <span>₦</span>
                        <input type="number" name="price" step="0.01" min="1"  autocomplete="off" placeholder="Unit Price" required>
                      </div>
                      <div class="quant-box">
                        <input type="number" name="quantity" step="0.01" min="1"  autocomplete="off" placeholder="Quantity" required>
                      </div>
                    </div>
                  </div>
                  <!-- Add product button -->
                  <button type="submit" name="add-product" class="btn btn-success">Add Product <i class="fa fa-plus-square"></i></button>
              </form>
          </div>
          <div class="modal-footer">
              <button type="button" class="btn btn-danger" onclick="closeModal('modal-add')">Cancel <i class="fa fa-cancel"></i> &times;</button>
          </div>
      </div>
  </div>
<?php } 


Function TotalProduct(){
  global $pdo;

  // select 
  $select = "SELECT COUNT(prodId) AS prodId FROM products";
  $stmt = $pdo->prepare($select);
  $stmt->execute();
  $data = $stmt->fetch(PDO::FETCH_ASSOC);
  return $counter = $data['prodId'];
}

Function TrashProduct(){
  global $pdo;

  // select 
  $select = "SELECT COUNT(prodId) AS prodId FROM products_trash";
  $stmt = $pdo->prepare($select);
  $stmt->execute();
  $data = $stmt->fetch(PDO::FETCH_ASSOC);
  return $counter = $data['prodId'];
}


function TotalInvoice(){
  global $pdo;

  $count = "SELECT COUNT(invoiceId) AS invoiceNum FROM history";
  $stmt = $pdo->prepare($count);
  $stmt->execute();

  $row = $stmt->fetch(PDO::FETCH_ASSOC);
  return $TotalInvoice = $row['invoiceNum'];
}

function TotalSales(){
  global $pdo;

  $sales = "SELECT SUM(amount) AS totalAmount FROM history";
  $stmt = $pdo->prepare($sales);
  $stmt->execute();

  $row = $stmt->fetch(PDO::FETCH_ASSOC);
  return $TotalAmount = $row['totalAmount'];
}

function ThisMonth(){
  global $pdo;

  $getMonth = date('Y-m');

  // get Month data
  $month = "SELECT SUM(amount) AS totalMonth FROM history WHERE created LIKE ?";
  $stmt = $pdo->prepare($month);
  $stmt->execute(["%$getMonth%"]);

  $row = $stmt->fetch(PDO::FETCH_ASSOC);
  return $TotalMonth = $row['totalMonth'];
}

function TotalCustomer(){
  global $pdo;

  $customer = "SELECT DISTINCT (customer) AS totalCustomer FROM history";
  $stmt = $pdo->prepare($customer);
  
  $stmt->execute();
  return $counter = $stmt->rowCount();
}

function ExpiryProduct(){
  global $pdo;
  $quantity = 0;

  $expiry = "SELECT COUNT(quantity) AS expiry FROM products WHERE quantity = ?";
  $stmt = $pdo->prepare($expiry);
  $stmt->execute([$quantity]);
  $row = $stmt->fetch(PDO::FETCH_ASSOC);
  return $counter = $row['expiry'];
}

function TotalUser(){
  global $pdo;

  $user = "SELECT name AS totaluser FROM users";
  $stmt = $pdo->prepare($user);
  $stmt->execute();
  return $counter = $stmt->rowCount();
}


// ========= USERS ========

Function EditUsers(){
  global $userId;
  global $userName;
  global $mobile;
  global $roles;
  global $email;
  global $password;
  global $pdo;
  ?>
  <div id="modal-<?= $userId ?>" class="modal">
    <div class="modal-content" style="margin-top:50px; background: #fff;">
      <div class="modal-header text-success">Edit Users</div>
      <div class="modal-body">
        <form action="" method="POST">
          <div class="row">
            <div class="col-lg-12">
              <div class="single-input">
                <label>Email Address</label>
                <div class="my-input">
                  <input type="email" required="" value="<?= $email; ?>" name="email" placeholder="Email address">
                  <input type="hidden" value="<?= $userId;?>" name="singleUserId">
                </div>
              </div>
            </div>
            <div class="col-lg-6">
              <div class="single-input">
                <label>Username/Names</label>
                <div class="my-input">
                  <input type="text" required="" value="<?= $userName; ?>" name="name" placeholder="Username">
                </div>
              </div>
            </div>
            <div class="col-lg-6">
              <div class="single-input">
                <label>Phone Number</label>
                <div class="my-input">
                  <input type="number" required="" value="<?= $mobile;?>" name="mobile" placeholder="GSM">
                </div>
              </div>
            </div>
            <div class="col-lg-6">
              <div class="single-input">
                <label>Edit Password</label>
                <div class="my-input">
                  <input type="password" required="" value="<?= $password;?>" name="password" placeholder="New Password">
                </div>
              </div>
            </div>
            <div class="col-lg-6">
              <div class="single-input">
                <label>Select Role</label>
                <div class="my-input">
                  <select name="role">
                    <option value="<?= $roles;?>"><?= $roles;?></option>
                    <option value="Admin">Admin</option>
                    <option value="Cashier">Cashier</option>
                    <option value="Sales Person">Sales Person</option>
                  </select>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <div class="modal-footer">
              <button type="button" class="btn btn-danger" onclick="closeModal('modal-<?= $userId ?>')">Cancel</button>
            </div>
            <button name="update-user" class="btn btn-success">Update User <i class="fa fa-user-plus"></i></button>
          </div> 
        </form>
      </div>
    </div>
  </div>
      
<?php }


Function UpdateUser(){
  global $pdo;

  if (isset($_POST['update-user'])) {
    $editEmail  = $_POST['email'];
    $editName   = $_POST['name'];
    $editMobile = $_POST['mobile'];
    $editRoles  = $_POST['role'];
    $editPassword = $_POST['password'];
    $singleUserId = $_POST['singleUserId'];

    $hidePassword = password_hash($editPassword, PASSWORD_DEFAULT);

    $update = "UPDATE users SET name = ?, email_address = ?, phone_number = ?, roles = ?, password = ?
                WHERE userId = ? ";
    $updatePdo = $pdo->prepare($update);
    if ($updatePdo->execute([
                      $editName, 
                      $editEmail, 
                      $editMobile, 
                      $editRoles, 
                      $hidePassword, 
                      $singleUserId])) {
      $_SESSION['message'] = 'Updated Successfully';
      $_SESSION['type'] = 'success';

      ?>
      <script type="text/javascript">
        setTimeout("location.href='javascript:history.back()';", 2000);
      </script>
      <?php 

    }else{
      $_SESSION['message'] = 'Something went wrong.';
      $_SESSION['type'] = 'error';
    }    
  }

}


// ========= CATEGORY ========

Function EditCategory(){
  global $catId;
  global $pdo;
  global $catName;
  ?>
  <div id="modal-<?= $catId ?>" class="modal">
    <div class="modal-content" style="margin-top:50px; background: #fff;">
      <div class="modal-header text-success">Edit Category</div>
      <div class="modal-body">
        <form action="" method="POST">
          <div class="row">
            <div class="col-lg-12">
              <div class="single-input">
                <label>Edit Category</label>
                <div class="my-input">
                  <input type="text" required="" value="<?= $catName; ?>" name="edit_cat" placeholder="Edit category">
                  <input type="hidden" value="<?= $catId;?>" name="singleCatId">
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <div class="modal-footer">
              <button type="button" class="btn btn-danger" onclick="closeModal('modal-<?= $catId ?>')">Cancel</button>
            </div>
            <button name="update-cat" class="btn btn-success">Update Category <i class="fa fa-plus-square"></i></button>
          </div> 
        </form>
      </div>
    </div>
  </div>
      
<?php }


Function UpdateCategory(){
  global $pdo;

  if (isset($_POST['update-cat'])) {
    $newCat     = $_POST['edit_cat'];
    $catId      = $_POST['singleCatId'];

    if (empty($newCat)) {
      $_SESSION['message'] = 'Empty Category.';
      $_SESSION['type'] = 'error';
    }
    else{
      $update = "UPDATE category SET catName = ? WHERE catId = ? ";
      $updatePdo = $pdo->prepare($update);
      if ($updatePdo->execute([ $newCat, $catId ])) {
        $_SESSION['message'] = 'Updated Successfully';
        $_SESSION['type'] = 'success';

        ?>
        <script type="text/javascript">
          setTimeout("location.href='javascript:history.back()';", 2000);
        </script>
        <?php 

      }else{
        $_SESSION['message'] = 'Something went wrong.';
        $_SESSION['type'] = 'error';
      }    

    }
    
  }

}


// ===== testing of something ======

function ModalAdd(){
  global $prodName;
  global $price;
  global $prodId;
  ?>
  <div id="modal-<?= $prodId ?>" class="modal">
    <div class="modal-content" style="margin-top:100px;">
       <div class="modal-header"><?= $prodName; ?> - ₦<?=$price;?></div>
        <div class="modal-body">
         <!-- Input form starts here -->
          <form action="" method="POST">
            <div class="row">
              <div class="col-lg-6">
                <div class="single-input">
                  <label>How Many Quantity?</label>
                  <div class="my-input">
                    <input type="number" required="" name="quantity" placeholder="Enter Quantity" autocomplete="off" style="text-align: center;" 
                    onkeyup="numberResult(<?= $prodId ?>)" 
                    id="quantity-<?= $prodId ?>">
                    <input type="hidden" value="<?php echo $prodName?>" name="product">
                    <input type="hidden" name="price" id="takePrice-<?= $prodId ?>" value="<?= $price ?>">
                  </div>
                </div>
              </div>
              
              <div class="col-lg-6">
                <div class="single-input">
                  <label>Amount will be:</label>
                  <div class="my-input">
                    <input type="text" style="text-align:center" name="" disabled="" placeholder="0" id="showResult-<?= $prodId ?>">
                  </div>
                </div>
              </div>
            </div>
            <button name="add-btn" class="btn btn-success mt-3">Add Product 
              <i class="fa fa-plus-circle"></i>
            </button>
          </form>
         <!-- End Form action -->
        </div>
       <!-- End Modal body -->
       <div class="modal-footer">
         <button type="button" class="btn btn-danger" onclick="closeModal('modal-<?= $prodId ?>')">Cancel</button>
       </div>

     </div>
     <!-- Modal Content -->
  </div>
<?php 
}



function EditCartel(){
  global $catalogId;
  global $prodName;
  global $quantity;

  ?>
  <div id="modal-<?= $catalogId ?>" class="modal">
    <div class="modal-content" style="margin-top:100px;">
       <div class="modal-header">Change Quantity</div>
        <div class="modal-body">
         <!-- Input form starts here -->
          <form action="" method="POST" enctype="multipart/form-data">
           
           <input type="hidden" name="edit-id" value="<?= $catalogId ?>">
           <input type="hidden" name="prodName" value="<?php echo $prodName;?>">
           <label>Product Name:</label>
           <input type="text" class="form-control" disabled="" name="prod-name" value="<?= htmlspecialchars($prodName) ?>" required>
           <!-- Quantity -->
           <small>Change Quantity</small>
           <div class="quant-box">
             <input type="number" name="quantity" step="0.01" min="0" autocomplete="off" placeholder="Quantity" value="<?php echo $quantity;?>" required>
           </div>
  
           <button name="upd-product" class="btn btn-success mt-2">Update Product</button>
          </form>
         <!-- End Form action -->
        </div>
       <!-- End Modal body -->
       <div class="modal-footer">
         <button type="button" class="btn btn-danger" onclick="closeModal('modal-<?= $catalogId ?>')">Cancel</button>
       </div>

     </div>
     <!-- Modal Content -->
  </div>
  <?php 
}




function DeleteCarte(){
  global $catalogId;
  global $prodName;
  global $quantity;
  global $price;

  ?>
  <div id="modal-delete-<?= $catalogId ?>" class="modal">
    <div class="modal-content" style="margin-top:150px;">
      <div class="modal-header">Delete Confirmation</div>
      <div class="modal-body">Are you sure you want to remove 
        <b><?php echo $prodName;?></b> from the list?
      </div>

      <form action="" method="POST">
        <div class="modal-footer">
          <input type="hidden" name="catalogId" value="<?php echo $catalogId;?>">
          <input type="hidden" name="cart_prodName" value="<?php echo $prodName;?>">
          <input type="hidden" name="cart_price" value="<?php echo $price;?>">
          <input type="hidden" name="cart_quantity" value="<?php echo $quantity;?>">

          <button type="button" class="btn btn-secondary" 
            onclick="closeModal('modal-delete-<?= $catalogId ?>')">No, Cancel</button>
          <button type="submit" name="DeleteBtn" class="btn btn-danger">Yes, Remove</button>
        </div>
      </form> 
    </div>
  </div>
<?php 
}





?>