From 117c605d9f86818298ea338d38f8331722f9ee6e Mon Sep 17 00:00:00 2001
From: Kenneth Ezekiel <88850771+KenEzekiel@users.noreply.github.com>
Date: Wed, 15 Nov 2023 14:02:26 +0700
Subject: [PATCH] feat: premium register and cancel

---
 public/css/styles.css                     |  55 +++++++++
 src/client/SoapClient.php                 |  51 +++++++++
 src/controllers/FilmController.php        |  16 ++-
 src/controllers/SoapPremiumController.php | 131 ++++++----------------
 src/models/SoapPremiumModel.php           |  53 ---------
 src/services/UserService.php              |  14 +--
 views/layouts/base.php                    |   7 +-
 views/premium-status.php                  | 125 +++++++--------------
 8 files changed, 199 insertions(+), 253 deletions(-)
 create mode 100644 src/client/SoapClient.php
 delete mode 100644 src/models/SoapPremiumModel.php

diff --git a/public/css/styles.css b/public/css/styles.css
index e8cc855..a0d48e1 100644
--- a/public/css/styles.css
+++ b/public/css/styles.css
@@ -503,6 +503,61 @@ select {
   margin-left: 20px;  
 }
 
+.premium-div {
+  display: flex;
+  flex-direction: column;
+  margin-top: 5%;
+}
+
+.premium-div h2 {
+  color: var(--primary-base, #5360DC);
+  text-align: center;
+  font-size: 30px;
+  font-style: normal;
+  font-weight: 700;
+  line-height: 36px; /* 120% */
+  letter-spacing: -0.225px;
+  margin-bottom: 2%;
+}
+
+.premium-div h3 {
+  color: white;
+  text-align: center;
+  font-size: 20px;
+  font-weight: 700;
+  line-height: 36px; /* 120% */
+  letter-spacing: -0.225px;
+  margin-bottom: 2%;
+  font-style: italic;
+}
+
+.list {
+  border-radius: 10px;
+  border-color: gray;
+  background-color: #21252C;
+  padding: 2% 5% 2% 5%;
+  margin: 2% 10% 1% 10%;
+}
+
+.bullets li {
+  margin-top: 2%;
+  font-weight: 600;
+  padding-left: 25%;
+  font-size: large;
+}
+
+.message {
+  font-size: large;
+  font-weight: 600;
+  color: #ddd;
+  text-align: center;
+}
+
+
+.button-container {
+  margin: 0 20% 0 20%;
+}
+
 @media only screen and (max-width: 800px) {
   .form-container {
     width: 100%;
diff --git a/src/client/SoapClient.php b/src/client/SoapClient.php
new file mode 100644
index 0000000..bf24a7a
--- /dev/null
+++ b/src/client/SoapClient.php
@@ -0,0 +1,51 @@
+<?php
+
+namespace app\client;
+
+
+class SoapClient
+{
+  private $soapclient;
+  private static $instance = null;
+
+  public function __construct()
+  {
+    $apikey = getenv('api_key');
+    // Stream context to add HTTP headers
+    $streamContext = stream_context_create([
+      'http' => [
+        'header' => "Authorization: Bearer $apikey",
+      ],
+    ]);
+    // Options for the SOAP client
+    $options = [
+      'stream_context' => $streamContext,
+      'trace' => 1, // Enable trace to view request and response headers
+      'cache_wsdl' => WSDL_CACHE_NONE
+    ];
+    $this->soapclient = new \SoapClient(getenv('soap_url'), $options);
+  }
+
+  public static function getInstance()
+  {
+    if (self::$instance == null) {
+      self::$instance = new SoapClient();
+    }
+    return self::$instance;
+  }
+
+  public function registerPremium($params)
+  {
+    return $this->soapclient->registerPremium($params);
+  }
+
+  public function checkStatus($params)
+  {
+    return $this->soapclient->checkStatus($params);
+  }
+
+  public function cancelRegister($params)
+  {
+    return $this->soapclient->cancelRegister($params);
+  }
+}
diff --git a/src/controllers/FilmController.php b/src/controllers/FilmController.php
index 470f30a..99a97c1 100644
--- a/src/controllers/FilmController.php
+++ b/src/controllers/FilmController.php
@@ -28,7 +28,7 @@ class FilmController extends BaseController
     protected function get($urlParams)
     {
         $uri = Request::getURL();
-        
+
         if ($uri == "/films" || $uri == '/search') {
             $page = (isset($_GET['page']) and (int) $_GET['page'] >= 1) ? $_GET['page'] : 1;
             $word = $_GET['q'] ?? "";
@@ -44,19 +44,17 @@ class FilmController extends BaseController
                 $data['released_years'] = $this->service->getAllCategoryValues('released_year');
                 $data['total_page'] = ceil($row_count / 10);
                 parent::render($data, 'films', "layouts/base");
-            }
-            else {
+            } else {
                 $films = [];
-    
+
                 foreach ($data['films'] as $film) {
                     $films[] = $film->toResponse();
                 }
                 $data['films'] = $films;
                 $data['total_page'] = ceil($row_count / 10);
-    
+
                 response::send_json_response($data);
             }
-
         } elseif ($uri == '/film-details') {
             $data['film'] = $this->service->getById($_GET['film_id']);
             if (isset($_SESSION['user_id'])) {
@@ -74,7 +72,8 @@ class FilmController extends BaseController
                 $films[] = array(
                     'film_id' => $film->film_id,
                     'image_path' => $film->image_path,
-                    'title' => $film->title);
+                    'title' => $film->title
+                );
             }
             response::send_json_response($films);
         } else if ($uri == '/film-image') {
@@ -90,8 +89,7 @@ class FilmController extends BaseController
                 header('Content-Length: ' . filesize($imagePath));
                 readfile($imagePath);
                 exit;
-            }
-            catch (Exception $e) {
+            } catch (Exception $e) {
                 $msg = $e->getMessage();
                 $data["error_code"] = $msg;
                 response::send_json_response($data, 400);
diff --git a/src/controllers/SoapPremiumController.php b/src/controllers/SoapPremiumController.php
index d4b84cf..018fadf 100644
--- a/src/controllers/SoapPremiumController.php
+++ b/src/controllers/SoapPremiumController.php
@@ -1,121 +1,58 @@
 <?php
 
 namespace app\controllers;
+
 use app\base\BaseController;
 use app\controllers\utils\response;
+use app\client\SoapClient;
 use app\Request;
 use app\models\SoapPremiumModel;
 use Exception;
 
-class SoapPremiumController extends BaseController {
-    private $model;
-
-    public function __construct() {
-        $this->model = SoapPremiumModel::getInstance();
-    }
+class SoapPremiumController extends BaseController
+{
+    private $soap_client;
 
-    public function checkStatus($params){
-        return $this->model->checkStatus($params);
+    public function __construct()
+    {
+        parent::__construct(null);
+        $this->soap_client = new SoapClient();
     }
 
     protected function get($urlParams)
     {
-        $uri = Request::getURL();
-        
-        if($uri == '/premium-status'){
-            if (isset($_SESSION['role']) and $_SESSION['role'] == 'admin'){
-                $premiumTemp = $this->model->getAllPremium()->listUserPremium;
-                if(!empty($premiumTemp)){
-                    if(!is_array($premiumTemp)){
-                        $premiumTemp = [$premiumTemp];
-                    }
-                    else{
-                        $premiumTemp = $premiumTemp;
-                    }
-                    $data["premium_users"] = $premiumTemp;
-                }
-
-                $pendingTemp = $this->model->getAllPending()->listUserPending;
-                if(!empty($pendingTemp)){
-                    if(!is_array($pendingTemp)){
-                        $pendingTemp = [$pendingTemp];
-                    }
-                    else{
-                        $pendingTemp = $pendingTemp;
-                    }
-                    $data["pending_users"] = $pendingTemp;
-                }
-                parent::render($data, 'premium-status', "layouts/base");
-            }
-            else{
-                $params = ["userId" => $_SESSION['user_id']];
-                $result = $this->checkStatus($params);
-                $data['userStatus'] = $result->userStatus;
-
-                parent::render($data, 'premium-status', "layouts/base");
+        // Get page for requesting premium
+        if (!isset($_SESSION['user_id'])) {
+            parent::redirect("/", $urlParams);
+        } else {
+            $registered = $this->soap_client->checkStatus(["userId" => (int)$_SESSION['user_id']]);
+            if ($registered->userStatus == "UNREGISTERED") {
+                $urlParams['registered'] = false;
+            } else {
+                $urlParams['registered'] = true;
             }
-        }
-        else{
-            throw new Exception("Invalid URL");
+            parent::render($urlParams, "premium-status", "layouts/base");
         }
     }
 
     protected function post($urlParams)
     {
-        $uri = Request::getURL();
-        
-        if($uri == '/register-premium'){
-            if(isset($_POST['email'])){
-                $params = ["userId" => $_SESSION['user_id'], "email" => $_POST['email']];
-                $result = $this->model->registerPremium($params);
-                // if($result->status == "success"){
-                    header("Location: /premium-status");
-                // }
-                // else{
-                //     throw new Exception("Invalid Email");
-                // }
+        $action = $_POST['action'];
+        if ($action == 'register') {
+            $response = $this->soap_client->registerPremium(["userId" => (int)$_SESSION['user_id'], "email" => (string)$_SESSION['user_email']]);
+            if ($response->premiumRequest == "SUCCESS") {
+                $urlParams['msg'] = "Registration successful";
+            } else {
+                $urlParams['msg'] = "Registration failed";
             }
-            else{
-                throw new Exception("Invalid URL");
+        } else if ($action == 'cancel') {
+            $response = $this->soap_client->cancelRegister(["userId" => (int)$_SESSION['user_id']]);
+            if ($response->responseCancel == "SUCCESS") {
+                $urlParams['msg'] = "Cancel premium request successful";
+            } else {
+                $urlParams['msg'] = "Cancel premium request failed";
             }
         }
-
-        elseif($uri == '/cancel-premium'){
-            $params;
-            if (isset($_SESSION['role']) and $_SESSION['role'] == 'admin')
-                $params = ["userId" => $_POST['user_id']];
-            else 
-                $params = ["userId" => $_SESSION['user_id']];
-            $result = $this->model->cancelRegister($params);
-            // if($result->status == "success"){
-                $data['premiumCancelMessage'] = $result->responseCancel;
-                header("Location: /premium-status");
-            // }
-            // else{
-            //     throw new Exception("Invalid URL");
-            // }
-        }
-        elseif($uri == '/approve-premium'){
-            $params = ["userId" => $_POST['user_id']];
-            $result = $this->model->approvePremium($params);
-            // if($result->status == "success"){
-                $data['premiumAcceptMessage'] = $result->approvalResponse;
-                header("Location: /premium-status");
-            // }
-            // else{
-            //     throw new Exception("Invalid URL");
-            // }
-        }
-        elseif($uri == '/reject-premium'){
-            $params = ["userId" => $_POST['user_id']];
-            $result = $this->model->rejectPremium($params);
-            // if($result->status == "success"){
-                $data['premiumRejectMessage'] = $result->rejectionResponse;
-                header("Location: /premium-status");
-            // }
-            // else{
-            //     throw new Exception("Invalid URL");
-            // }
-        }
+        parent::redirect("/premium-status", $urlParams);
     }
-}
\ No newline at end of file
+}
diff --git a/src/models/SoapPremiumModel.php b/src/models/SoapPremiumModel.php
deleted file mode 100644
index 764f203..0000000
--- a/src/models/SoapPremiumModel.php
+++ /dev/null
@@ -1,53 +0,0 @@
-<?php
-    namespace app\models;
-    use app\base\BaseModel;
-
-    class SoapPremiumModel
-    {
-        private $soapclient;
-        private static $instance = null;
-
-        public function __construct()
-        {
-            $apikey = getenv('api_key');
-            // Stream context to add HTTP headers
-            $streamContext = stream_context_create([
-                'http' => [
-                    'header' => "Authorization: Bearer $apikey",
-                ],
-            ]);
-            // Options for the SOAP client
-            $options = [
-                'stream_context' => $streamContext,
-                'trace' => 1, // Enable trace to view request and response headers
-                'cache_wsdl' => WSDL_CACHE_NONE
-            ];
-            $this->soapclient = new \SoapClient(getenv('soap_url'), $options);
-        }
-        public static function getInstance(){
-            if (self::$instance == null) {
-                self::$instance = new SoapPremiumModel();
-            }
-            return self::$instance;
-        }
-        public function registerPremium($params)
-        {
-            return $this->soapclient->registerPremium($params);
-        }
-        public function checkStatus($params)
-        {
-            return $this->soapclient->checkStatus($params);
-        }
-        public function cancelRegister($params){
-            return $this->soapclient->cancelRegister($params);
-        }
-        public function approvePremium($params){
-            return $this->soapclient->approvePremium($params);
-        }
-        public function getAllPremium(){
-            return $this->soapclient->getAllPremium();
-        }
-        public function getAllPending(){
-            return $this->soapclient->getAllPending();
-        }
-    }
\ No newline at end of file
diff --git a/src/services/UserService.php b/src/services/UserService.php
index dda75fe..ea48a8e 100644
--- a/src/services/UserService.php
+++ b/src/services/UserService.php
@@ -102,11 +102,13 @@ class UserService extends BaseService
     $_SESSION["user_id"] = $user->get('user_id');
     $_SESSION["role"] = $user->get('role');
     $_SESSION["username"] = $user->get('username');
+    $_SESSION["user_email"] = $user->get('email');
 
     return $user;
   }
 
-  public function loginPremium($email_or_username, $password) {
+  public function loginPremium($email_or_username, $password)
+  {
     $user = null;
 
     // Check email first
@@ -141,7 +143,7 @@ class UserService extends BaseService
     // Options for the SOAP client
     $options = [
       'stream_context' => $streamContext,
-      'trace' => 1, 
+      'trace' => 1,
       'cache_wsdl' => WSDL_CACHE_NONE
     ];
     $soapclient = new \SoapClient(getenv('soap_url'), $options);
@@ -153,11 +155,9 @@ class UserService extends BaseService
     }
     if ($response->userStatus == "UNREGISTERED") {
       throw new BadRequestException("UNREGISTERED_PREMIUM");
-    }
-    else if($response->userStatus == "PENDING") {
+    } else if ($response->userStatus == "PENDING") {
       throw new BadRequestException("PENDING_PREMIUM");
-    }
-    else if($response->userStatus == "REJECTED"){
+    } else if ($response->userStatus == "REJECTED") {
       throw new BadRequestException("REJECTED_PREMIUM");
     }
 
@@ -166,7 +166,7 @@ class UserService extends BaseService
     $userResponse["email"] = $user->get('email');
     $userResponse["role"] = $user->get('role');
     return $userResponse;
-}
+  }
 
   public function logout()
   {
diff --git a/views/layouts/base.php b/views/layouts/base.php
index ff7e241..302b2fd 100644
--- a/views/layouts/base.php
+++ b/views/layouts/base.php
@@ -33,7 +33,12 @@
     <ul class='nav-links menu'>
       <li class='menu-item' id='home'><a href='/'>Home</a></li>
       <li class='menu-item'><a href='/films'>Films</a></li>
-      <li class='menu-item'><a href='/premium-status'>Premium Status</a></li>
+      <?php
+      if (isset($_SESSION['user_id'])) {
+        echo "<li class='menu-item'><a href='/premium-status'>Premium</a></li>";
+      }
+      ?>
+
 
       <?php
 
diff --git a/views/premium-status.php b/views/premium-status.php
index bfa42f9..fa94a9c 100644
--- a/views/premium-status.php
+++ b/views/premium-status.php
@@ -1,89 +1,42 @@
-<?php if (isset($_SESSION['role']) and $_SESSION['role'] == 'admin') { ?>
-    <!-- ADMIN USERS -->
-    <div class='premium-status-admin'>
-        <table>
-            <thead>
-                <tr>
-                    <th>Username</th>
-                    <th>Action</th>
-                </tr>
-            </thead>
-            <tbody>
-                <?php if(is_array($data["premium_users"])) foreach($data["premium_users"] as $user) { ?>
-                    <tr>
-                        <td><?php echo $user->userEmail; ?></td>
-                        <td>
-                            <?php if($user->premiumStatus == "ACCEPTED") { ?>
-                                <form method="post" action="/cancel-premium">
-                                    <input type="hidden" name="user_id" value="<?php echo $user->id; ?>">
-                                    <button type="submit">Cancel Premium</button>
-                                </form>
-                            <?php } ?>
-                        </td>
-                    </tr>
-                <?php }?>
-            </tbody>
-        </table>
-        <br><p>Pending Users</p><br>
-        <table>
-            <thead>
-                <tr>
-                    <th>Username</th>
-                    <th>Action</th>
-                </tr>
-            </thead>
-            <tbody>
-                <?php if(isset($data["pending_users"])) { ?>
-                    <?php var_dump($data["pending_users"]); ?>
-                    <?php if(is_array($data["pending_users"])) foreach($data["pending_users"] as $user) { ?>
-                        <tr>
-                            <td><?php echo $user->userEmail; ?></td>
-                            <td>
-                                <?php if($user->premiumStatus == "PENDING") { ?>
-                                    <form method="post" action="/approve-premium">
-                                        <input type="hidden" name="user_id" value="<?php echo $user->id; ?>">
-                                        <button type="submit">Accept Premium</button>
-                                    </form>
-                                    <form method="post" action="/reject-premium">
-                                        <input type="hidden" name="user_id" value="<?php echo $user->id; ?>">
-                                        <button type="submit">Reject Premium</button>
-                                    </form>
-                                <?php } ?>
-                            </td>
-                        </tr>
-                    <?php } ?>
-                <?php } unset($data["pending_users"]);?>
-            </tbody>
-        </table>
+<div>
+    <div class="premium-div">
+        <h2>Become a premium member now!</h2>
+        <div class="list">
+            <h3>Benefits</h3>
+            <hr>
+            <br>
+            <ul class="bullets">
+                <li> > Create your own watchlist from your favorite movies!</li>
+                <li> > See other users' recommendations in their watchlists!</li>
+                <li> > Share your watchlists to the world!</li>
+            </ul>
+        </div>
+
     </div>
-<?php } else { ?>
-    <!-- REGULAR USERS -->
-    <div class='premium-status'>
-        <h2 id="goBack"><a class='back-button' href="/films"><?php echo "< Films" ?></a></h2>
-        <h1>Premium Status<h1>
-        <br>
-        <p>Current: <?php $result = $data["userStatus"]; echo $result;?></p>
-        <br>
-        <p>Click <a href="/premium-status">here</a> to refresh the page.</p>
-        <?php if(isset($data["premiumCancelMessage"])) { ?>
-            <p><?php echo $data["premiumCancelMessage"]; unset($data["premiumCancelMessage"]);?></p>
-        <?php } ?>
-        <?php 
-        if($result == "REJECTED" || $result == "UNREGISTERED") { ?>
-            <form method="post" action="/register-premium">
-                <label for="email">Email:</label>
-                <input type="email" id="email" name="email" required>
-                <button type="submit">Register for Premium</button>
-            </form>
-        <?php } elseif($result == "PENDING") { ?>
-            <div class="pending">
-                <p>Your request is pending. Please wait for the admin to approve your request.</p>
-                <p>Click <a href="/premium-status">here</a> to refresh the page.</p>
-            </div>
-        <?php } elseif($result == "ACCEPTED") { ?>
-            <form method="post" action="/cancel-premium">
-                <button type="submit">Cancel Premium</button>
+    <div class='message'>
+        <p>
+            <?php
+            if (isset($msg)) {
+                echo "<br><p>$msg</p><br>";
+            }
+            ?>
+        </p>
+    </div>
+    <div class='button-container'>
+        <? if ($registered == false) {
+            echo "
+                <form method='post'>
+                    <input type='hidden' name='action' value='register'>
+                    <button class='button' type='submit'>Register now!</button>
+                </form>
+                ";
+        } else {
+            echo "
+            <form method='post'>
+                <input type='hidden' name='action' value='cancel'>
+                <button class='button-delete-update' type='submit'>Cancel Registration</button>
             </form>
-        <?php } ?>
+                ";
+        }  ?>
     </div>
-<?php } ?>
\ No newline at end of file
+</div>
\ No newline at end of file
-- 
GitLab