<?php

// src/Controller/ProductController.php

namespace App\Service;

use Doctrine\DBAL\DBALException;
use Doctrine\ORM\ORMException;
use PDOException;
use Exception;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Uid\Uuid;
use App\Entity\Member;

//use App\Utils\StringTools;

/**
 * Members
 *
 * Data class for interacting with Member data from the DB
 */
class HandleMembers
{
    private $session;
    private $entityManager;
    private $limit = 5;

    public function __construct(
        EntityManagerInterface $entityManager,
        RequestStack $requestStack
    ) {
        $this->entityManager = $entityManager;
        $this->session       = $requestStack->getSession();
    }

    /**
     * Grabs member data object from the current section
     *
     * @return MEMBERS data object
     */
    public function getYou()
    {
        $member = $this->session->get("member");
        return $member;
    }

    public function getMemberById(int $id)
    {
        $member = $this->entityManager->getRepository(Member::class)->find($id);

        return $member;
    }

    public function getMemberPage(int $page, string $active = "all")
    {
        $members = $this->entityManager->getRepository(Member::class);
        if ($active == "true" || $active == "false") {
            $list = $members->findBy(["active" => $active], ["id" => "ASC"]);
        } else {
            $list = $members->findBy([], ["id" => "ASC"]);
        }

        $count      = ceil(count($list) / $this->limit);
        $totalCount = count($list);

        $shelf = [];
        $range = $page * $this->limit - $this->limit;
        for ($i = 0; $i <= $this->limit; $i++) {
            try {
                array_push($shelf, $list[$i + $range]);
            } catch (Exception $error) {
            }
        }

        return [
            "members"      => $shelf,
            "total"        => $count,
            "totalMembers" => $totalCount,
        ];
    }

    /**
     * Add or edit new member
     *
     * @param Request $request object containing posted data
     * @param int $memberId member identifier
     * @param string $action request task
     * @return Object
     */
    public function modifyMember($request, $memberId, $action)
    {
        $errorMessage = null;
        if ($action == "add") {
            $member = new Member();
        } else {
            $member = $this->entityManager->getRepository(Member::class)->find($memberId);
        }

        //submitted values
        $handle = $request->request->get("handle");
        $member->setHandle($handle);
        $gender = $request->request->get("gender");
        $member->setGender($gender);
        $role = $request->request->get("role");
        $member->setRole($role);
        $email = $request->request->get("email");
        $member->setEmail($email);
        $pronoun = $request->request->get("pronoun");
        $member->setPronoun($pronoun);

        //set defaults
        //$utils = new StringTools();
        if ($action == "add") {
            $hash = password_hash("passw0rd!", PASSWORD_DEFAULT);
            $member->setPassword($hash);
            $member->setActive(false);
            $member->setAvatar("default-member-avatar");
            $member->setUuid(Uuid::v4());
            $this->entityManager->persist($member);
            $member->setCreatedAt(new \DateTimeImmutable());
            $member->setLastLogin(new \DateTimeImmutable());
        } else {
            $active = ($request->request->get("active") == "true" ? true : false);
            $member->setActive($active);
            if ($request->request->get("new_pass") != "") {
                $hash = password_hash($request->request->get("new_pass"), PASSWORD_DEFAULT);
                $member->setPassword($hash);
            }
        }

        try {
            $this->entityManager->flush();
        } catch (PDOException $error) {
            $errorMessage = $error->getMessage();
        } catch (DBALException $error) {
            $errorMessage = $error->getMessage();
        } catch (ORMException $error) {
            $errorMessage = $error->getMessage();
        } catch (Exception $error) {
            $errorMessage = $error->getMessage();
        } catch (SyntaxErrorException $e) {
            $errorMessage = $error->getMessage();
        }
        // return result status
        $message = "";
        if ($action == "add") {
            $message = "New member added. Woohoo!";
        } else {
            $message = "Member Info Edited";
        }
        if ($errorMessage == null) {
            return $response = [
                "status"  => true,
                "message" => $message,
            ];
        } else {
            return $response = ["status" => false, "message" => $errorMessage];
        }
    }

    /**
     * Updates member data in db
     *
     * @param Request $request object containing posted data
     * @return JSON
     */
    public function updateMember($request)
    {
        $errorMessage = null;
        $id           = $request->request->get("member_id");
        $member       = $this->entityManager->getRepository(Members::class)->find($id);
        $image        = $request->files->get("avi");
        if (!empty($image)) {
            $name = $image->getClientOriginalName();
            $member->setAvatar($name);
        }
        $first = $request->request->get("first_name");
        $member->setFirstName($first);
        $last = $request->request->get("last_name");
        $member->setLastName($last);
        $handle = $request->request->get("handle");
        $member->setHandle($handle);
        $gender = $request->request->get("gender");
        $member->setGender($gender);
        $public = $request->request->get("public");
        if ($public == "true") {
            $member->setPublicProfile(true);
        } else {
            $member->setPublicProfile(false);
        }
        $email = $request->request->get("email");
        $member->setEmail($email);
        $pronoun = $request->request->get("pronoun");
        $member->setPronouns($pronoun);
        $pass_new = $request->request->get("password_new");
        if ($pass_new != "" || $pass_new != null) {
            $hash = password_hash($pass_new, PASSWORD_DEFAULT);
            $member->setPassword($hash);
        }
        $this->entityManager->persist($member);

        //error checking
        try {
            $this->entityManager->flush();
        } catch (PDOException $error) {
            $errorMessage = $error->getMessage();
        } catch (DBALException $error) {
            $errorMessage = $error->getMessage();
        } catch (ORMException $error) {
            $errorMessage = $error->getMessage();
        } catch (Exception $error) {
            $errorMessage = $error->getMessage();
        } catch (SyntaxErrorException $e) {
            $errorMessage = $error->getMessage();
        }
        // return result status
        if ($errorMessage == null) {
            $this->session->set("member", $member);
            return $response = [
                "status"  => true,
                "message" => "Profile Updated! Nice!",
            ];
        } else {
            return $response = ["status" => false, "message" => $errorMessage];
        }
    }
}
