<?php

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

if (!empty($_FILES['new_photo']['name'])){
    $photo_name = $_FILES['new_photo']['name'];
    $photo_tmpname = $_FILES['new_photo']['tmp_name'];
    $photo_size = $_FILES['new_photo']['size'];
    $username = $_POST['username'];

    $photofilenameAr = explode('.', $photo_name);
    $photo_extension = end($photofilenameAr);
    $photo_ext = strtolower($photo_extension);


    //check if Image was selected
    if (!empty($photo_name)) {
        if ($photo_size > 2000000) {
            echo "<script>
            toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
            toastr['error']('Photo Size Exceeded, Max Size is 2MB');
            </script>";
            return false;
        }
        if ($photo_ext == 'png' || $photo_ext == 'jpg' || $photo_ext == 'jpeg' || $photo_ext == 'svg') {
            $link = "upload/".$photo_name;
            $strgPath = $link;
            if (file_exists($strgPath)) {
                echo "<script>
                toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
                toastr['error']('Photo With Same Name Already Exists');
                </script>";
                return false;

            }else {
                    $photo_upload = move_uploaded_file($photo_tmpname, $strgPath);
                    if ($photo_upload) {
                        //update photo details in the database
                        $sql = "UPDATE pastors SET photo =:photo WHERE username =:username";
                        $conn->query($sql);
                        $conn->bind(":photo", $photo_name);
                        $conn->bind(":username", $username);

                        try{
                            $conn->execute();
                            echo "<script>
                            toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
                            toastr['success']('Profile Photo Updated Successfully');
                            </script> <meta http-equiv='refresh' content='5'>";



                        }catch(PDOException $err) {
                    $error = $err->getMessage();

                }
                    }
            else {
                            echo "<script>
                            toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
                            toastr['error']('Select Photo Cannot Upload');
                            </script>";
            }}}else {
                            echo "<script>
                            toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
                            toastr['error']('Only png, jpg, jpeg or svg Formats Are Allowed. Photo Cannot Upload');
                            </script>";}}}



