From ae715d52734c10652e1e88ee675055c87aad34ff Mon Sep 17 00:00:00 2001 From: Bitha17 <16521076@mahasiswa.itb.ac.id> Date: Thu, 16 Nov 2023 21:57:25 +0700 Subject: [PATCH] revert changes --- Dockerfile | 12 +- .../Controllers/EventController.php | 5 +- .../Controllers/PembelianController.php | 3 +- .../Controllers/SubscriptionController.php | 0 .../Controllers/TicketController.php | 2 +- .../Controllers/UserController.php | 114 ++------- app/Models/Event.php | 216 ++++++++++++++++++ app/Models/Pembelian.php | 75 ++++++ {src/Server => app}/Models/Subscription.php | 0 {src/Server => app}/Models/Ticket.php | 31 ++- {src/Server => app}/Models/User.php | 42 ++-- .../pages => app/Views}/event/create.php | 5 +- .../pages => app/Views}/event/update.php | 5 +- .../pages => app/Views}/history/history.php | 5 +- {src/Client/pages => app/Views}/home/home.php | 50 ++-- app/Views/login/login.php | 37 +++ .../pages => app/Views}/login/register.php | 11 +- .../Views}/pembelian/pembelian.php | 5 +- .../Views}/profile/edit_profile.php | 0 .../Views}/profile/view_profile.php | 5 +- .../Views/template}/event.php | 0 .../Views/template}/footer.php | 0 .../Views/template}/history.php | 0 .../Views/template}/navbar.php | 2 +- app/router.php | 33 +++ app/util.php | 13 ++ database/1-create-table-users.sql | 8 - database/2-create-table-events.sql | 10 - database/3-create-table-tickets.sql | 6 - database/4-create-table-pembelian.sql | 8 - database/5-create-table-subscription.sql | 8 - database/6-seed.sql | 36 --- db/connect.php | 19 ++ db/data.php | 79 +++++++ db/init.php | 26 +++ db/init.sql | 48 ++++ db/reset.php | 15 ++ src/.htaccess | 13 -- src/Client/pages/login/login.php | 40 ---- src/Server/Controllers/HomeController.php | 11 - src/Server/Models/Event.php | 176 -------------- src/Server/Models/Model.php | 22 -- src/Server/Models/Pembelian.php | 64 ------ src/Server/Router/Router.php | 69 ------ src/Server/web.php | 55 ----- src/index.php | 11 - {src/Client => styles}/auth.css | 0 {src/Client => styles}/container.css | 0 {src/Client => styles}/dropdown.css | 0 {src/Client => styles}/footer.css | 0 {src/Client => styles}/form.css | 0 {src/Client => styles}/global.css | 0 {src/Client => styles}/navbar.css | 0 {src/Client => styles}/pagination.css | 0 54 files changed, 669 insertions(+), 726 deletions(-) rename {src/Server => app}/Controllers/EventController.php (97%) rename {src/Server => app}/Controllers/PembelianController.php (96%) rename {src/Server => app}/Controllers/SubscriptionController.php (100%) rename {src/Server => app}/Controllers/TicketController.php (96%) rename {src/Server => app}/Controllers/UserController.php (64%) create mode 100644 app/Models/Event.php create mode 100644 app/Models/Pembelian.php rename {src/Server => app}/Models/Subscription.php (100%) rename {src/Server => app}/Models/Ticket.php (66%) rename {src/Server => app}/Models/User.php (69%) rename {src/Client/pages => app/Views}/event/create.php (95%) rename {src/Client/pages => app/Views}/event/update.php (97%) rename {src/Client/pages => app/Views}/history/history.php (96%) rename {src/Client/pages => app/Views}/home/home.php (78%) create mode 100644 app/Views/login/login.php rename {src/Client/pages => app/Views}/login/register.php (81%) rename {src/Client/pages => app/Views}/pembelian/pembelian.php (96%) rename {src/Client/pages => app/Views}/profile/edit_profile.php (100%) rename {src/Client/pages => app/Views}/profile/view_profile.php (95%) rename {src/Client/components => app/Views/template}/event.php (100%) rename {src/Client/components => app/Views/template}/footer.php (100%) rename {src/Client/components => app/Views/template}/history.php (100%) rename {src/Client/components => app/Views/template}/navbar.php (90%) create mode 100644 app/router.php create mode 100644 app/util.php delete mode 100644 database/1-create-table-users.sql delete mode 100644 database/2-create-table-events.sql delete mode 100644 database/3-create-table-tickets.sql delete mode 100644 database/4-create-table-pembelian.sql delete mode 100644 database/5-create-table-subscription.sql delete mode 100644 database/6-seed.sql create mode 100644 db/connect.php create mode 100644 db/data.php create mode 100644 db/init.php create mode 100644 db/init.sql create mode 100644 db/reset.php delete mode 100644 src/.htaccess delete mode 100644 src/Client/pages/login/login.php delete mode 100644 src/Server/Controllers/HomeController.php delete mode 100644 src/Server/Models/Event.php delete mode 100644 src/Server/Models/Model.php delete mode 100644 src/Server/Models/Pembelian.php delete mode 100644 src/Server/Router/Router.php delete mode 100644 src/Server/web.php delete mode 100644 src/index.php rename {src/Client => styles}/auth.css (100%) rename {src/Client => styles}/container.css (100%) rename {src/Client => styles}/dropdown.css (100%) rename {src/Client => styles}/footer.css (100%) rename {src/Client => styles}/form.css (100%) rename {src/Client => styles}/global.css (100%) rename {src/Client => styles}/navbar.css (100%) rename {src/Client => styles}/pagination.css (100%) diff --git a/Dockerfile b/Dockerfile index 1d2b0aa..e29d064 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,3 @@ -FROM php:8.1-apache - -RUN apt-get update && apt-get upgrade -y -RUN apt-get install -y libxml2-dev libpq-dev -RUN docker-php-ext-install pgsql pdo pdo_pgsql && docker-php-ext-enable pgsql pdo pdo_pgsql -RUN a2enmod rewrite && service apache2 restart -RUN chown -R :www-data /var/www/html/ +FROM php:8.0-apache -WORKDIR /var - -EXPOSE 80 \ No newline at end of file +RUN docker-php-ext-install pdo pdo_mysql \ No newline at end of file diff --git a/src/Server/Controllers/EventController.php b/app/Controllers/EventController.php similarity index 97% rename from src/Server/Controllers/EventController.php rename to app/Controllers/EventController.php index 0e5c9be..2961a63 100644 --- a/src/Server/Controllers/EventController.php +++ b/app/Controllers/EventController.php @@ -1,7 +1,8 @@ <?php +// app/Controllers/EventController.php ob_start(); -include(__DIR__ . '../../Models/Event.php'); +require_once(__DIR__ . '/../Models/Event.php'); require_once(__DIR__ . '/TicketController.php'); @@ -9,7 +10,7 @@ class EventController { private $eventModel; public function __construct() { - $this->eventModel = new \Server\Models\EventModel(); + $this->eventModel = new EventModel(); } public function createEvent($event_name, $stock, $event_price, $event_date, $event_location, $gambar, $vid){ diff --git a/src/Server/Controllers/PembelianController.php b/app/Controllers/PembelianController.php similarity index 96% rename from src/Server/Controllers/PembelianController.php rename to app/Controllers/PembelianController.php index 5f5701d..9f5526d 100644 --- a/src/Server/Controllers/PembelianController.php +++ b/app/Controllers/PembelianController.php @@ -10,10 +10,11 @@ class PembelianController { public function __construct() { - $this->pembelianModel = new \Server\Models\PembelianModel(); + $this->pembelianModel = new PembelianModel(); } public function createPembelian($ticketId, $userId, $createdTime) { + $pembelianModel = new PembelianModel(); return $this->pembelianModel->createPembelian($ticketId, $userId, $createdTime); } diff --git a/src/Server/Controllers/SubscriptionController.php b/app/Controllers/SubscriptionController.php similarity index 100% rename from src/Server/Controllers/SubscriptionController.php rename to app/Controllers/SubscriptionController.php diff --git a/src/Server/Controllers/TicketController.php b/app/Controllers/TicketController.php similarity index 96% rename from src/Server/Controllers/TicketController.php rename to app/Controllers/TicketController.php index 8d2944d..962586f 100644 --- a/src/Server/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -8,7 +8,7 @@ class TicketController { private $ticketModel; public function __construct() { - $this->ticketModel = new \Server\Models\TicketModel(); + $this->ticketModel = new TicketModel(); } public function createTicket($name, $eventId) { diff --git a/src/Server/Controllers/UserController.php b/app/Controllers/UserController.php similarity index 64% rename from src/Server/Controllers/UserController.php rename to app/Controllers/UserController.php index 6bf0731..3ae2e6c 100644 --- a/src/Server/Controllers/UserController.php +++ b/app/Controllers/UserController.php @@ -1,15 +1,14 @@ <?php - -namespace Server\Controllers; - -include (__DIR__.'/../Models/User.php'); +// app/controllers/userController.php +ob_start(); +require_once(__DIR__ . '/../Models/User.php'); class UserController { private $userModel; public function __construct() { - $this->userModel = new \Server\Models\UserModel(); + $this->userModel = new UserModel(); } public function createUser($name, $username, $email, $hashedPass, $isAdmin) { @@ -33,15 +32,8 @@ class UserController { } public function registerUser($name, $username, $email, $password, $isAdmin) { - $hashedPassword = password_hash($password, PASSWORD_DEFAULT); - - if ($hashedPassword === false) { - return ['success' => false, 'message' => 'Password hashing failed']; - } - - return $this->createUser($name, $username, $email, $hashedPassword, $isAdmin); + return $this->createUser($name, $username, $email, password_hash($password,PASSWORD_DEFAULT), $isAdmin); } - public function loginByEmail($email,$password) { $user = $this->userModel->getUserByEmail($email); @@ -53,6 +45,18 @@ class UserController { return "wrong credentials"; } } + + public function loginByUsername($username,$password) { + $user = $this->userModel->getUserByUsername($username); + if ($user !== false && password_verify($password, $user['user_hashedPass'])) { + session_start(); + $_SESSION["user_id"] = $user['user_ID']; + return "success"; + } else { + session_start(); + return "wrong credentials"; + } + } public function logout() { session_start(); @@ -68,90 +72,6 @@ class UserController { public function editProfile($user_id, $name, $username, $email) { return $this->userModel->editProfile($user_id, $name, $username, $email); } - - public function loginview() { - if (session_status() == PHP_SESSION_NONE) { - // If a session is not already started, start a new one - session_start(); - } - // Check if the user is already logged in, redirect to home if true - if (isset($_SESSION['user_id'])) { - header("Location: /home"); - ob_end_flush(); - exit(); - } - - include (__DIR__.'/../../Client/pages/login/login.php'); - } - - public function login() { - // Check if the required parameters are set in the POST request - if (isset($_POST['loginIdentifier']) && isset($_POST['loginPassword'])) { - $emailOrUsername = $_POST['loginIdentifier']; - $password = $_POST['loginPassword']; - - if (filter_var($emailOrUsername, FILTER_VALIDATE_EMAIL)) { - $user = $this->userModel->getUserByEmail($emailOrUsername); - } else { - $user = $this->userModel->getUserByUsername($emailOrUsername); - } - - if ($user !== false) { - if (password_verify($password, $user['user_hashedpass'])) { - session_start(); - $_SESSION["user_id"] = $user['user_id']; - header("Location: /home"); - ob_end_flush(); - exit(); - } else { - session_start(); - $_SESSION['message'] = "Wrong Password"; - header("Location: /login"); - ob_end_flush(); - exit(); - } - } else { - session_start(); - $_SESSION['message'] = "Wrong credentials"; - header("Location: /login"); - ob_end_flush(); - exit(); - } - } else { - // Handle missing parameters - session_start(); - $_SESSION['message'] = "Missing login parameters"; - header("Location: /login"); - ob_end_flush(); - exit(); - } - } - - public function registerview() { - include (__DIR__."/../../Client/pages/login/register.php"); - } - - public function register() { - $userName = $_POST['userName']; - $userUsername = $_POST['userUsername']; - $userEmail = $_POST['userEmail']; - $userPassword = $_POST['userPassword']; - $isAdmin = isset($_POST['isAdmin']) ? 1 : 0; - $response = $this->registerUser($userName,$userUsername,$userEmail,$userPassword,$isAdmin); - - $success = $response['success']; - if($success){ - session_start(); - $_SESSION['message'] = "You have successfully registered. Please log in"; - header("Location:login"); - ob_end_flush(); - } else { - session_start(); - $_SESSION['error_message'] = $response['message']; - header("Location:register"); - ob_end_flush(); - } - } public function handleRequest() { if (isset($_POST['userAction'])) { diff --git a/app/Models/Event.php b/app/Models/Event.php new file mode 100644 index 0000000..94ec0d3 --- /dev/null +++ b/app/Models/Event.php @@ -0,0 +1,216 @@ +<?php + +require_once(__DIR__ . '/../../db/connect.php'); +require_once(__DIR__ . '/../util.php'); + +class EventModel { + + public function createEvent($event_name, $stock, $event_price, $event_date, $event_location, $gambar, $vid) { + global $db; + $success = true; + + if ($gambar !== null && isset($gambar['name']) && isset($gambar['tmp_name'])) { + $imageFilePath = '../assets/images/' . $gambar['name']; + + // Move the uploaded file to the desired directory + if (move_uploaded_file($gambar['tmp_name'], $imageFilePath)) { + echo "File uploaded successfully"; + } else { + echo "Error moving file to destination"; + $imageFilePath = null; // Set to null if there's an error + } + } else { + echo "No image uploaded"; + $imageFilePath = null; // Set to null if no file is uploaded + } + + if ($vid !== null && isset($vid['name']) && isset($vid['tmp_name'])) { + $vidFilePath = '../assets/videos/' . $vid['name']; + + // Move the uploaded file to the desired directory + if (move_uploaded_file($vid['tmp_name'], $vidFilePath)) { + echo "File uploaded successfully"; + } else { + echo "Error moving file to destination"; + $vidFilePath = null; // Set to null if there's an error + } + } else { + echo "No video uploaded"; + $vidFilePath = null; // Set to null if no file is uploaded + } + + if ($imageFilePath === null || $vidFilePath === null) { + $success = false; + return $success; + } + + $stmt = $db->prepare("INSERT INTO events (event_name, event_stock, event_price, event_date, event_location, gambar, vid) VALUES (?, ?, ?, ?, ?, ?, ?)"); + + if ($stmt->execute([$event_name, $stock, $event_price, $event_date, $event_location, $imageFilePath, $vidFilePath])) { + echo "Event created successfully"; + return $success; + } else { + echo "Error creating event: " . print_r($stmt->errorInfo(), true); + $success = false; + return $success; + } + } + + public function updateEvent($event_id, $event_name, $event_price, $event_date, $event_location, $gambar, $vid) { + global $db; + $db->setAttribute(PDO::ATTR_AUTOCOMMIT, 1); + + echo "Updating Event with ID: $event_id, Name: $event_name, Price: $event_price, Date: $event_date, Location: $event_location"; + + if ($gambar !== null && isset($gambar['name']) && isset($gambar['tmp_name'])) { + $imageFilePath = '../assets/images/' . $gambar['name']; + + // Move the uploaded file to the desired directory + if (move_uploaded_file($gambar['tmp_name'], $imageFilePath)) { + echo "File uploaded successfully<br>"; + } else { + echo "Error moving file to destination<br>"; + $imageFilePath = null; // Set to null if there's an error + } + } else { + echo "No image uploaded<br>"; + $imageFilePath = null; // Set to null if no file is uploaded + } + + if ($vid !== null && isset($vid['name']) && isset($vid['tmp_name'])) { + $vidFilePath = '../assets/videos/' . $vid['name']; + + // Move the uploaded file to the desired directory + if (move_uploaded_file($vid['tmp_name'], $vidFilePath)) { + echo "File uploaded successfully<br>"; + } else { + echo "Error moving file to destination<br>"; + $vidFilePath = null; // Set to null if there's an error + } + } else { + echo "No video uploaded<br>"; + $vidFilePath = null; // Set to null if no file is uploaded + } + + // chek wheter image or video is null or not + if ($imageFilePath === null && $vidFilePath === null) { + $sql = "UPDATE events SET event_name = '$event_name', event_price = '$event_price', event_date = '$event_date', event_location = '$event_location' WHERE event_id = $event_id"; + } elseif ($imageFilePath === null) { + $sql = "UPDATE events SET event_name = '$event_name', event_price = '$event_price', event_date = '$event_date', event_location = '$event_location', vid = '$vidFilePath' WHERE event_id = $event_id"; + } elseif ($vidFilePath === null) { + $sql = "UPDATE events SET event_name = '$event_name', event_price = '$event_price', event_date = '$event_date', event_location = '$event_location', gambar = '$imageFilePath' WHERE event_id = $event_id"; + } else { + $sql = "UPDATE events SET event_name = '$event_name', event_price = '$event_price', event_date = '$event_date', event_location = '$event_location', gambar = '$imageFilePath', vid = '$vidFilePath' WHERE event_id = $event_id"; + } + + $rowCount = $db->exec($sql); + + if ($rowCount !== false) { + echo "Event updated successfully. Rows affected: $rowCount"; + } else { + echo "Error updating event: " . print_r($db->errorInfo(), true); + } + return "Event updated successfully"; + } + + + + public function deleteEvent($eventId) { + global $db; + + try { + // Delete associated pembelian records + $stmtPembelian = $db->prepare("DELETE FROM pembelian WHERE ticket_id IN (SELECT ticket_id FROM tickets WHERE event_id = ?)"); + $stmtPembelian->execute([$eventId]); + + // Delete associated tickets + $stmtTickets = $db->prepare("DELETE FROM tickets WHERE event_id = ?"); + $stmtTickets->execute([$eventId]); + + // Delete the event + $stmtEvent = $db->prepare("DELETE FROM events WHERE event_id = ?"); + $stmtEvent->execute([$eventId]); + + echo "Event, associated tickets, and pembelian records deleted successfully<br>"; + + return "Event, associated tickets, and pembelian records deleted successfully"; + } catch (PDOException $e) { + echo "Error: " . $e->getMessage() . "<br>"; + + return "Error: " . $e->getMessage(); + } + } + + public function getAllEvents() { + global $db; + $stmt = $db->prepare("SELECT * FROM events"); + $stmt->execute(); + return $stmt->fetchAll(PDO::FETCH_ASSOC); + } + + public function getEvent($eventId) { + global $db; + $stmt = $db->prepare("SELECT * FROM events WHERE event_id = ?"); + $stmt->execute([$eventId]); + return $stmt->fetch(PDO::FETCH_ASSOC); + } + + public function getLastEventId() { + global $db; + $stmt = $db->prepare("SELECT event_id FROM events ORDER BY event_id DESC LIMIT 1"); + $stmt->execute(); + return $stmt->fetch(PDO::FETCH_ASSOC)['event_id']; + } + + public function searchEvents($searchQuery, $sortKey, $minStock) { + global $db; + + try { + $sql = "SELECT * FROM events WHERE 1"; // Start with a true condition + + // Add search condition + if (!empty($searchQuery)) { + $sql .= " AND (LOWER(event_name) LIKE CONCAT('%', :query, '%') OR LOWER(event_location) LIKE CONCAT('%', :query, '%'))"; + } + + + // Add filter condition + if ($minStock !== null) { + $sql .= " AND event_stock >= :minStock"; + } + + // Add sort condition + if ($sortKey === 'name') { + $sql .= " ORDER BY event_name ASC"; + } elseif ($sortKey === 'location') { + $sql .= " ORDER BY event_location ASC"; + } + + $stmt = $db->prepare($sql); + + // Bind search query parameter + if (!empty($searchQuery)) { + $lowerSearchQuery = strtolower("%" . $searchQuery . "%"); + $stmt->bindParam(':query', $lowerSearchQuery, PDO::PARAM_STR); + } + + // Bind filter parameter + if ($minStock !== null) { + $stmt->bindParam(':minStock', $minStock, PDO::PARAM_INT); + } + + $stmt->execute(); + + return $stmt->fetchAll(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + throw new Exception("Error searching events: " . $e->getMessage()); + } + } + + + + +} +?> + + diff --git a/app/Models/Pembelian.php b/app/Models/Pembelian.php new file mode 100644 index 0000000..0fcf741 --- /dev/null +++ b/app/Models/Pembelian.php @@ -0,0 +1,75 @@ +<?php +// app/models/Pembelian.php + +require_once(__DIR__ . '/../../db/connect.php'); +require_once(__DIR__ . '/../util.php'); + +class PembelianModel { + public function createPembelian($ticketId, $userId, $createdTime) { + global $db; + + $stmt = $db->prepare("INSERT INTO pembelian (ticket_id, user_id, pembelian_created_time) VALUES (?, ?, ?)"); + if ($stmt->execute([$ticketId, $userId, $createdTime])) { + $stmt = $db->prepare("SELECT event_id FROM tickets WHERE ticket_id = ?"); + $stmt->execute([$ticketId]); + $result = $stmt->fetch(PDO::FETCH_ASSOC); + + if ($result) { + $eventId = $result['event_id']; + + // Decrement the event's stock by 1 + $stmt = $db->prepare("UPDATE events SET event_stock = event_stock - 1 WHERE event_id = ?"); + return $stmt->execute([$eventId]); + } + } + } + + public function getPembelian($pembelianId) { + global $db; + + $stmt = $db->prepare("SELECT * FROM pembelian WHERE pembelian_id = ?"); + $stmt->execute([$pembelianId]); + + return $stmt->fetch(PDO::FETCH_ASSOC); + } + + public function updatePembelian($pembelianId, $ticketId, $userId, $createdTime) { + global $db; + + $stmt = $db->prepare("UPDATE pembelian SET ticket_id = ?, user_id = ?, pembelian_created_time = ? WHERE pembelian_id = ?"); + $stmt->execute([$ticketId, $userId, $createdTime, $pembelianId]); + + return "Pembelian updated successfully"; + } + + public function deletePembelian($pembelianId) { + global $db; + + $stmt = $db->prepare("DELETE FROM pembelian WHERE pembelian_id = ?"); + $stmt->execute([$pembelianId]); + + return "Pembelian deleted successfully"; + } + + public function getAllPembelian(){ + global $db; + $stmt = $db->prepare("SELECT * FROM pembelian"); + $stmt->execute(); + return $stmt->fetchAll(PDO::FETCH_ASSOC); + } + + public function getAllPembelianWithDetails(){ + global $db; + $stmt = $db->prepare("SELECT * FROM pembelian JOIN tickets ON pembelian.ticket_id = tickets.ticket_id JOIN events ON tickets.event_id = events.event_id ORDER BY pembelian_created_time DESC"); + $stmt->execute(); + return $stmt->fetchAll(PDO::FETCH_ASSOC); + } + + public function getPembelianByUserId($userId){ + global $db; + $stmt = $db->prepare("SELECT * FROM pembelian JOIN tickets ON pembelian.ticket_id = tickets.ticket_id JOIN events ON tickets.event_id = events.event_id WHERE user_id = ? ORDER BY pembelian_created_time DESC"); + $stmt->execute([$userId]); + return $stmt->fetchAll(PDO::FETCH_ASSOC); + } +} +?> diff --git a/src/Server/Models/Subscription.php b/app/Models/Subscription.php similarity index 100% rename from src/Server/Models/Subscription.php rename to app/Models/Subscription.php diff --git a/src/Server/Models/Ticket.php b/app/Models/Ticket.php similarity index 66% rename from src/Server/Models/Ticket.php rename to app/Models/Ticket.php index 388049a..4060c6e 100644 --- a/src/Server/Models/Ticket.php +++ b/app/Models/Ticket.php @@ -1,47 +1,59 @@ <?php +// app/models/Ticket.php -namespace Server\Models; +require_once(__DIR__ . '/../../db/connect.php'); -use PDO; -class TicketModel extends Model { +class TicketModel { public function createTicket($name, $eventId) { - $stmt = $this->database->prepare("INSERT INTO tickets (ticket_name, event_id) VALUES (?, ?)"); + global $db; + + $stmt = $db->prepare("INSERT INTO tickets (ticket_name, event_id) VALUES (?, ?)"); $stmt->execute([$name, $eventId]); return "Ticket created successfully"; } public function getTicket($ticketId) { - $stmt = $this->database->prepare("SELECT * FROM tickets WHERE ticket_id = ?"); + global $db; + + $stmt = $db->prepare("SELECT * FROM tickets WHERE ticket_id = ?"); $stmt->execute([$ticketId]); return $stmt->fetch(PDO::FETCH_ASSOC); } public function updateTicket($ticketId, $name, $eventId) { - $stmt = $this->database->prepare("UPDATE tickets SET ticket_name = ?, event_id = ? WHERE ticket_id = ?"); + global $db; + + $stmt = $db->prepare("UPDATE tickets SET ticket_name = ?, event_id = ? WHERE ticket_id = ?"); $stmt->execute([$name, $eventId, $ticketId]); return "Ticket updated successfully"; } public function updateTicketByEventId($eventId, $name) { - $stmt = $this->database->prepare("UPDATE tickets SET ticket_name = ? WHERE event_id = ?"); + global $db; + + $stmt = $db->prepare("UPDATE tickets SET ticket_name = ? WHERE event_id = ?"); $stmt->execute([$name, $eventId]); return "Ticket updated successfully"; } public function deleteTicket($ticketId) { - $stmt = $this->database->prepare("DELETE FROM tickets WHERE ticket_id = ?"); + global $db; + + $stmt = $db->prepare("DELETE FROM tickets WHERE ticket_id = ?"); $stmt->execute([$ticketId]); return "Ticket deleted successfully"; } public function getSmallestAvailableTicket($eventId) { - $stmt = $this->database->prepare(" + global $db; + + $stmt = $db->prepare(" SELECT t.*, e.* FROM tickets t JOIN events e ON t.event_id = e.event_id @@ -61,3 +73,4 @@ class TicketModel extends Model { return $stmt->fetch(PDO::FETCH_ASSOC); } } +?> diff --git a/src/Server/Models/User.php b/app/Models/User.php similarity index 69% rename from src/Server/Models/User.php rename to app/Models/User.php index 818b24b..cb3410b 100644 --- a/src/Server/Models/User.php +++ b/app/Models/User.php @@ -1,21 +1,20 @@ <?php +// app/models/User.php -namespace Server\Models; +require_once(__DIR__ . '/../../db/connect.php'); -use PDO; -include (__DIR__."/Model.php"); - - -class UserModel extends Model { +class UserModel { public function createUser($name, $username, $email, $hashedPass, $isAdmin) { + global $db; + $response = [ 'success'=> true, 'message'=> '' ]; try { - $stmt = $this->database->prepare("INSERT INTO users (user_name, username, user_email, user_hashedPass, isAdmin) VALUES (?, ?, ?, ?, ?)"); + $stmt = $db->prepare("INSERT INTO users (user_name, username, user_email, user_hashedPass, isAdmin) VALUES (?, ?, ?, ?, ?)"); $stmt->execute([$name, $username, $email, $hashedPass, $isAdmin]); $response['message'] = "User created successfully"; return $response; @@ -37,7 +36,9 @@ class UserModel extends Model { // User.php public function getUser($userId) { - $stmt = $this->database->prepare("SELECT * FROM users WHERE user_ID = ?"); + global $db; + + $stmt = $db->prepare("SELECT * FROM users WHERE user_ID = ?"); $stmt->execute([$userId]); if ($stmt) { @@ -55,41 +56,54 @@ class UserModel extends Model { } public function getUserByEmail($email) { - $stmt = $this->database->prepare("SELECT * FROM users WHERE user_email = ?"); + global $db; + + $stmt = $db->prepare("SELECT * FROM users WHERE user_email = ?"); $stmt->execute([$email]); return $stmt->fetch(PDO::FETCH_ASSOC); } public function getUserByUsername($username){ - $stmt = $this->database->prepare("SELECT * FROM users WHERE username = ?"); + global $db; + + $stmt = $db->prepare("SELECT * FROM users WHERE username = ?"); $stmt->execute([$username]); return $stmt->fetch(PDO::FETCH_ASSOC); } public function updateUser($userId, $name, $username, $email, $hashedPass, $isAdmin) { - $stmt = $this->database->prepare("UPDATE users SET user_name = ?, username = ?, user_email = ?, user_hashedPass = ?, isAdmin = ? WHERE user_ID = ?"); + global $db; + + $stmt = $db->prepare("UPDATE users SET user_name = ?, username = ?, user_email = ?, user_hashedPass = ?, isAdmin = ? WHERE user_ID = ?"); $stmt->execute([$name, $username, $email, $hashedPass, $isAdmin, $userId]); return "User updated successfully"; } public function editProfile($userId, $name, $username, $email) { - $stmt = $this->database->prepare("UPDATE users SET user_name = ?, username = ?, user_email = ? WHERE user_id = ?"); + global $db; + + $stmt = $db->prepare("UPDATE users SET user_name = ?, username = ?, user_email = ? WHERE user_id = ?"); return $stmt->execute([$name, $username, $email, $userId]); } public function deleteUser($userId) { - $stmt = $this->database->prepare("DELETE FROM users WHERE user_ID = ?"); + global $db; + + $stmt = $db->prepare("DELETE FROM users WHERE user_ID = ?"); $stmt->execute([$userId]); return "User deleted successfully"; } public function getAllUsers() { - $stmt = $this->database->query("SELECT * FROM users"); + global $db; + + $stmt = $db->query("SELECT * FROM users"); return $stmt->fetchAll(PDO::FETCH_ASSOC); } + } ?> diff --git a/src/Client/pages/event/create.php b/app/Views/event/create.php similarity index 95% rename from src/Client/pages/event/create.php rename to app/Views/event/create.php index 75b6a10..b486caa 100644 --- a/src/Client/pages/event/create.php +++ b/app/Views/event/create.php @@ -1,8 +1,5 @@ <?php - if (session_status() == PHP_SESSION_NONE) { - // If a session is not already started, start a new one - session_start(); - } + session_start(); ob_start(); if (!isset($_SESSION["user_id"])) { echo "here"; diff --git a/src/Client/pages/event/update.php b/app/Views/event/update.php similarity index 97% rename from src/Client/pages/event/update.php rename to app/Views/event/update.php index 84f1251..3d63800 100644 --- a/src/Client/pages/event/update.php +++ b/app/Views/event/update.php @@ -1,8 +1,5 @@ <?php - if (session_status() == PHP_SESSION_NONE) { - // If a session is not already started, start a new one - session_start(); - } + session_start(); ob_start(); if (!isset($_SESSION["user_id"])) { echo "here"; diff --git a/src/Client/pages/history/history.php b/app/Views/history/history.php similarity index 96% rename from src/Client/pages/history/history.php rename to app/Views/history/history.php index 10b8f57..b2e0263 100644 --- a/src/Client/pages/history/history.php +++ b/app/Views/history/history.php @@ -1,8 +1,5 @@ <?php - if (session_status() == PHP_SESSION_NONE) { - // If a session is not already started, start a new one - session_start(); - } + session_start(); ob_start(); if (!isset($_SESSION["user_id"])) { echo "here"; diff --git a/src/Client/pages/home/home.php b/app/Views/home/home.php similarity index 78% rename from src/Client/pages/home/home.php rename to app/Views/home/home.php index 1cd9d38..701666b 100644 --- a/src/Client/pages/home/home.php +++ b/app/Views/home/home.php @@ -1,25 +1,22 @@ <?php - if (session_status() == PHP_SESSION_NONE) { - // If a session is not already started, start a new one - session_start(); - } + session_start(); ob_start(); if (!isset($_SESSION["user_id"])) { echo "here"; // User is not authenticated; redirect to login page - header("Location: login"); + header("Location: /app/Views/login/login.php"); ob_end_flush(); } - require_once (__DIR__.'/../../../Server/Controllers/PembelianController.php'); - require_once (__DIR__.'/../../../Server/Controllers/TicketController.php'); - require_once (__DIR__.'/../../../Server/Controllers/UserController.php'); - require_once (__DIR__.'/../../../Server/Controllers/EventController.php'); + require_once '../../Controllers/PembelianController.php'; + require_once '../../Controllers/TicketController.php'; + require_once '../../Controllers/UserController.php'; + require_once '../../Controllers/EventController.php'; $eventController = new EventController(); $pembelianController = new PembelianController(); $ticketController = new TicketController(); - $userController = new \Server\Controllers\UserController(); + $userController = new UserController(); // Handle search query $searchQuery = isset($_GET['search']) ? $_GET['search'] : ''; @@ -39,7 +36,7 @@ $currentPage = $paginationData['page']; $maxPage = $paginationData['maxpage']; - $isAdmin = $userController->getUser($_SESSION['user_id'])['isadmin']; + $isAdmin = $userController->getUser($_SESSION['user_id'])['isAdmin']; ?> <!DOCTYPE html> @@ -49,20 +46,20 @@ <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>HOME • TICKET KU</title> - <link rel="stylesheet" type="text/css" href="/../../global.css"> - <link rel="stylesheet" type="text/css" href="/../../form.css"> - <link rel="stylesheet" type="text/css" href="/../../footer.css"> - <link rel="stylesheet" type="text/css" href="/../../navbar.css"> - <link rel="stylesheet" type="text/css" href="/../../container.css"> - <link rel="stylesheet" type="text/css" href="/../../auth.css"> - <link rel="stylesheet" type="text/css" href="/../../dropdown.css"> - <link rel="stylesheet" type="text/css" href="/../../pagination.css"> - <link rel="stylesheet" type="text/css" href="/../../media.css"> + <link rel="stylesheet" type="text/css" href="/../../styles/global.css"> + <link rel="stylesheet" type="text/css" href="/../../styles/form.css"> + <link rel="stylesheet" type="text/css" href="/../../styles/footer.css"> + <link rel="stylesheet" type="text/css" href="/../../styles/navbar.css"> + <link rel="stylesheet" type="text/css" href="/../../styles/container.css"> + <link rel="stylesheet" type="text/css" href="/../../styles/auth.css"> + <link rel="stylesheet" type="text/css" href="/../../styles/dropdown.css"> + <link rel="stylesheet" type="text/css" href="/../../styles/pagination.css"> + <link rel="stylesheet" type="text/css" href="/../../styles/media.css"> </head> <body> <!-- Navbar --> - <?php include (__DIR__.'/../../components/navbar.php');?> + <?php include '../template/navbar.php';?> <div class="main-content"> <div class="column"> @@ -70,20 +67,19 @@ <button onclick="openCreateEventPage()" id="createEventBtn" class="admin">Create Event</button> <?php endif; ?> <div class="row"> - <input type="text" id="searchInput" placeholder="Search.." value="<?= isset($searchQuery) ? htmlspecialchars($searchQuery) : '' ?>" style="width:250%;"> + <input type="text" id="searchInput" placeholder="Search.." value="<?= htmlspecialchars($searchQuery)?>" style="width:250%;"> <select name="sort" id="sortSelect" class="styled-select"> <option value="" <?= empty($sortKey) ? 'selected' : '' ?>>No Sorting</option> <option value="name" <?= $sortKey === 'name' ? 'selected' : '' ?>>Sort by Name</option> <option value="location" <?= $sortKey === 'location' ? 'selected' : '' ?>>Sort by Location</option> </select> <!-- Change input type to "text" for minimum stock --> - <input type="text" id="minStockInput" name="min_stock" placeholder="Min Stock" value="<?= isset($minStock) ? htmlspecialchars($minStock) : 0 ?>" -"> + <input type="text" id="minStockInput" name="min_stock" placeholder="Min Stock" value="<?= htmlspecialchars($minStock) ?>"> <button type="submit" id="search-button">Search</button> </div> <?php foreach ($events as $event) : - include (__DIR__.'/../../components/event.php'); + include '../template/event.php'; endforeach;?> <div class="pagination"> @@ -116,7 +112,7 @@ </div> </div> - <?php include (__DIR__.'/../../components/footer.php');?> + <?php include '../template/footer.php';?> <script defer> function toggleMenu() { @@ -146,7 +142,7 @@ const sortKey = document.getElementById('sortSelect').value; // Construct the URL with search, min_stock, and sort parameters - const url = `/home?search=${encodeURIComponent(searchQuery)}&min_stock=${encodeURIComponent(minStock)}&sort=${encodeURIComponent(sortKey)}`; + const url = `/app/Views/home/home.php?search=${encodeURIComponent(searchQuery)}&min_stock=${encodeURIComponent(minStock)}&sort=${encodeURIComponent(sortKey)}`; // Redirect to the updated URL window.location.href = url; diff --git a/app/Views/login/login.php b/app/Views/login/login.php new file mode 100644 index 0000000..2ca035a --- /dev/null +++ b/app/Views/login/login.php @@ -0,0 +1,37 @@ +<?php + session_start(); +?> +<!DOCTYPE html> +<html lang="en"> + + <head> + <title>Login • TICKET KU</title> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <link rel="stylesheet" type="text/css" href="../../../styles/auth.css"> + </head> + + <body> + <div class="login-container"> + <h1>Login</h1> + <form id="loginForm" method="post" action="../../router.php"> + <!-- Aslinya email atau username bisa(?) --> + <label for="email">Email or Username</label> + <input type="text" id="identifier" name="loginIdentifier" required> + + <label for="password">Password</label> + <input type="password" id="password" name="loginPassword" required> + + <?php + // Check if there is an error message in the session + if (isset($_SESSION['message'])) { + echo '<p>' . $_SESSION['message'] . '</p>'; + unset($_SESSION['message']); // Remove the error message from the session + } + ?> + <button type="submit" name="userAction" value="login">Login</button> + </form> + <p>Don't have an account? <a href="register.php">Register</a></p> + </div> + </body> +</html> \ No newline at end of file diff --git a/src/Client/pages/login/register.php b/app/Views/login/register.php similarity index 81% rename from src/Client/pages/login/register.php rename to app/Views/login/register.php index 660b237..bdd3a09 100644 --- a/src/Client/pages/login/register.php +++ b/app/Views/login/register.php @@ -1,8 +1,5 @@ <?php - if (session_status() == PHP_SESSION_NONE) { - // If a session is not already started, start a new one - session_start(); - } + session_start(); ?> <!DOCTYPE html> <html lang="en"> @@ -11,13 +8,13 @@ <title>Register • TICKET KU</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <link rel="stylesheet" type="text/css" href="../../auth.css"> + <link rel="stylesheet" type="text/css" href="../../../styles/auth.css"> </head> <body> <div class="register-container"> <h1>Register</h1> - <form id="registerForm" method="post" action="register"> + <form id="registerForm" method="post" action="../../router.php"> <label for="userName">Name</label> <input type="text" id="userName" name="userName" required> @@ -44,7 +41,7 @@ <button type="submit" name="userAction" value="createUser">Register</button> </form> - <p>Already have an account? <a href="login">Login</a></p> + <p>Already have an account? <a href="login.php">Login</a></p> </div> </body> </html> \ No newline at end of file diff --git a/src/Client/pages/pembelian/pembelian.php b/app/Views/pembelian/pembelian.php similarity index 96% rename from src/Client/pages/pembelian/pembelian.php rename to app/Views/pembelian/pembelian.php index e8b2cfa..00d8ce4 100644 --- a/src/Client/pages/pembelian/pembelian.php +++ b/app/Views/pembelian/pembelian.php @@ -1,8 +1,5 @@ <?php - if (session_status() == PHP_SESSION_NONE) { - // If a session is not already started, start a new one - session_start(); - } + session_start(); ob_start(); if (!isset($_SESSION["user_id"])) { echo "here"; diff --git a/src/Client/pages/profile/edit_profile.php b/app/Views/profile/edit_profile.php similarity index 100% rename from src/Client/pages/profile/edit_profile.php rename to app/Views/profile/edit_profile.php diff --git a/src/Client/pages/profile/view_profile.php b/app/Views/profile/view_profile.php similarity index 95% rename from src/Client/pages/profile/view_profile.php rename to app/Views/profile/view_profile.php index 7c3c492..2eab3bc 100644 --- a/src/Client/pages/profile/view_profile.php +++ b/app/Views/profile/view_profile.php @@ -1,8 +1,5 @@ <?php - if (session_status() == PHP_SESSION_NONE) { - // If a session is not already started, start a new one - session_start(); - } + session_start(); ob_start(); if (!isset($_SESSION["user_id"])) { echo "here"; diff --git a/src/Client/components/event.php b/app/Views/template/event.php similarity index 100% rename from src/Client/components/event.php rename to app/Views/template/event.php diff --git a/src/Client/components/footer.php b/app/Views/template/footer.php similarity index 100% rename from src/Client/components/footer.php rename to app/Views/template/footer.php diff --git a/src/Client/components/history.php b/app/Views/template/history.php similarity index 100% rename from src/Client/components/history.php rename to app/Views/template/history.php diff --git a/src/Client/components/navbar.php b/app/Views/template/navbar.php similarity index 90% rename from src/Client/components/navbar.php rename to app/Views/template/navbar.php index d8b9f31..ec8dd2a 100644 --- a/src/Client/components/navbar.php +++ b/app/Views/template/navbar.php @@ -7,7 +7,7 @@ <li><a href="/app/Views/history/history.php">History</a></li> <!-- Logout Button --> <li> - <form method="post" action="/logout"> + <form method="post" action="/app/router.php"> <button type="submit" name="userAction" value="logout">Logout</button> </form> </li> diff --git a/app/router.php b/app/router.php new file mode 100644 index 0000000..7156e5c --- /dev/null +++ b/app/router.php @@ -0,0 +1,33 @@ +<?php + +require_once './Controllers/PembelianController.php'; +require_once './Controllers/TicketController.php'; +require_once './Controllers/UserController.php'; +require_once './Controllers/EventController.php'; + +$eventController = new EventController(); +$pembelianController = new PembelianController(); +$ticketController = new TicketController(); +$userController = new UserController(); + +if ($_SERVER["REQUEST_METHOD"] == "POST") { + if (isset($_POST["eventAction"])) { + $eventController->handleRequest(); + } elseif (isset($_POST["ticketAction"])) { + $ticketController->handleRequest(); + } elseif (isset($_POST["userAction"])) { + $userController->handleRequest(); + } elseif (isset($_POST["purchaseAction"])) { + $pembelianController->handleRequest(); + } + +} elseif ($_SERVER["REQUEST_METHOD"] == "GET") { + if (isset($_GET["eventAction"]) && isset($_GET["eventId"])) { + $eventController->handleRequest(); + } elseif (isset($_GET["ticketAction"])) { + $ticketController->handleRequest(); + } elseif (isset($_GET["userAction"])) { + $userController->handleRequest(); + } +} +?> \ No newline at end of file diff --git a/app/util.php b/app/util.php new file mode 100644 index 0000000..da3c6d5 --- /dev/null +++ b/app/util.php @@ -0,0 +1,13 @@ +<?php +function preprocess($str) { + return str_replace(' ', '%20', $str); +} + +function formatPrice($price) { + return number_format($price,0,',','.'); +} + +function isEmailValid($email) { + return filter_var($email, FILTER_VALIDATE_EMAIL); +} +?> \ No newline at end of file diff --git a/database/1-create-table-users.sql b/database/1-create-table-users.sql deleted file mode 100644 index b138fb0..0000000 --- a/database/1-create-table-users.sql +++ /dev/null @@ -1,8 +0,0 @@ -CREATE TABLE IF NOT EXISTS users ( - user_ID SERIAL PRIMARY KEY, - user_name VARCHAR(255), - username VARCHAR(255) UNIQUE, - user_email VARCHAR(255) UNIQUE, - user_hashedPass VARCHAR(255), - isAdmin BOOLEAN -); \ No newline at end of file diff --git a/database/2-create-table-events.sql b/database/2-create-table-events.sql deleted file mode 100644 index 80c7f26..0000000 --- a/database/2-create-table-events.sql +++ /dev/null @@ -1,10 +0,0 @@ -CREATE TABLE IF NOT EXISTS events ( - event_id SERIAL PRIMARY KEY, - event_name VARCHAR(255), - event_stock INT, - event_price INT, - event_date TIMESTAMP, - event_location VARCHAR(255), - gambar VARCHAR(255), - vid VARCHAR(255) -); \ No newline at end of file diff --git a/database/3-create-table-tickets.sql b/database/3-create-table-tickets.sql deleted file mode 100644 index 0de3886..0000000 --- a/database/3-create-table-tickets.sql +++ /dev/null @@ -1,6 +0,0 @@ -CREATE TABLE IF NOT EXISTS tickets ( - ticket_id SERIAL PRIMARY KEY, - ticket_name VARCHAR(255), - event_id INT, - FOREIGN KEY (event_id) REFERENCES events(event_id) ON DELETE SET NULL -); diff --git a/database/4-create-table-pembelian.sql b/database/4-create-table-pembelian.sql deleted file mode 100644 index 05e8eac..0000000 --- a/database/4-create-table-pembelian.sql +++ /dev/null @@ -1,8 +0,0 @@ -CREATE TABLE IF NOT EXISTS pembelian ( - pembelian_id SERIAL PRIMARY KEY, - ticket_id INT, - user_id INT, - pembelian_created_time TIMESTAMP, - FOREIGN KEY (ticket_id) REFERENCES tickets(ticket_id), - FOREIGN KEY (user_id) REFERENCES users(user_ID) ON DELETE SET NULL -); diff --git a/database/5-create-table-subscription.sql b/database/5-create-table-subscription.sql deleted file mode 100644 index 9f78283..0000000 --- a/database/5-create-table-subscription.sql +++ /dev/null @@ -1,8 +0,0 @@ -CREATE TABLE IF NOT EXISTS subscription ( - creator_id INT NOT NULL, - subscriber_id INT NOT NULL, - status VARCHAR(10) NOT NULL DEFAULT 'PENDING', - creator_name VARCHAR(255) NOT NULL, - PRIMARY KEY (creator_id, subscriber_id), - FOREIGN KEY (subscriber_id) REFERENCES users(user_ID) ON DELETE CASCADE -); diff --git a/database/6-seed.sql b/database/6-seed.sql deleted file mode 100644 index 36241df..0000000 --- a/database/6-seed.sql +++ /dev/null @@ -1,36 +0,0 @@ --- Generate and insert 100 dummy events with random data -DO $$ -DECLARE - i INT; -BEGIN - FOR i IN 1..100 LOOP - INSERT INTO events (event_name, event_stock, event_price, event_date, event_location, gambar, vid) - VALUES ( - 'Event ' || i, - FLOOR(RANDOM() * 10) + 1, - FLOOR(RANDOM() * 91) + 10, - NOW() + (i || ' days')::INTERVAL, - 'Location ' || i, - 'assets/images/' || (i % 16 + 1) || '.jpg', - 'assets/videos/video.mp4' - ); - - -- Generate and insert tickets corresponding to the event's event_stock - FOR j IN 1..(FLOOR(RANDOM() * 10) + 1) LOOP - INSERT INTO tickets (ticket_name, event_id) - VALUES ( - 'Ticket ' || j || ' for Event ' || i, - (SELECT MAX(event_id) FROM events) - ); - END LOOP; - END LOOP; -END $$; - --- Insert user data -INSERT INTO users (user_name, username, user_email, user_hashedPass, isAdmin) -VALUES - ('John Doe', 'john_doe', 'john@example.com', '$2y$10$8sA2N5Sx/1zMQv2yrTDAaOFlbGWECrrgB68axL.hBb78NhQdyAqWm', 'true'), - ('Jane Smith', 'jane_smith', 'jane@example.com', '$2y$10$8sA2N5Sx/1zMQv2yrTDAaOFlbGWECrrgB68axL.hBb78NhQdyAqWm', 'false'), - ('Admin User', 'admin_user', 'admin@example.com', '$2y$10$8sA2N5Sx/1zMQv2yrTDAaOFlbGWECrrgB68axL.hBb78NhQdyAqWm', 'true'), - ('Alice Johnson', 'alice', 'alice@example.com', '$2y$10$8sA2N5Sx/1zMQv2yrTDAaOFlbGWECrrgB68axL.hBb78NhQdyAqWm', 'false'), - ('Bob Williams', 'bob', 'bob@example.com', '$2y$10$8sA2N5Sx/1zMQv2yrTDAaOFlbGWECrrgB68axL.hBb78NhQdyAqWm', 'false'); diff --git a/db/connect.php b/db/connect.php new file mode 100644 index 0000000..7ab45ef --- /dev/null +++ b/db/connect.php @@ -0,0 +1,19 @@ +<?php + $host = 'db'; + $dbname = 'tubes1_WBD'; + $user = 'root'; + $pass = 'your_password'; + + try { + $db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); + + // Execute SQL statements from init.sql + $sqlInit = file_get_contents(__DIR__ . '/init.sql'); + $db->exec($sqlInit); + + // echo "Connected successfully and database initialized!<br/>"; + } catch (PDOException $e) { + // echo "Connection failed: " . $e->getMessage(); + } + +?> diff --git a/db/data.php b/db/data.php new file mode 100644 index 0000000..2b8c7e4 --- /dev/null +++ b/db/data.php @@ -0,0 +1,79 @@ +<?php +include 'connect.php'; + +// Make sure $db is defined and not null +if (isset($db)) { + try { + $db->beginTransaction(); + + // Insert events and tickets as before + $sqlEvent = <<<EOF + INSERT INTO events (event_name, event_stock, event_price, event_date, event_location, gambar, vid) VALUES + ('Music Concert', 2, 20, '2023-09-30 10:00:00', 'jakarta', 'assets/images/1.jpg', 'assets/videos/video.mp4'), + ('Art Exhibition', 2, 15, '2023-10-05 15:30:00', 'prancis', 'assets/images/2.png', 'assets/videos/video.mp4'), + ('Sports Tournament', 2, 40, '2023-11-12 18:45:00', 'italy', 'assets/images/3.jpg', 'assets/videos/video.mp4'), + ('Comedy Show', 2, 30, '2023-12-03 20:00:00', 'jakarta', 'assets/images/4.jpg', 'assets/videos/video.mp4'), + ('Tech Conference', 2, 60, '2024-01-18 14:15:00', 'ITB', 'assets/images/5.jpg', 'assets/videos/video.mp4'); + EOF; + + $sqlTicket = <<<EOF + INSERT INTO tickets (ticket_name, event_id) VALUES + ('General Admission', 1), + ('VIP Pass', 1), + ('Standard Ticket', 2), + ('Student Discount', 2), + ('Early Bird Special', 3), + ('Premium Access', 3), + ('Weekend Pass', 4), + ('Group Discount', 4), + ('Conference Pass', 5), + ('Exhibitor Pass', 5); + EOF; + + $db->exec($sqlEvent); + $db->exec($sqlTicket); + + // Dummy user data with hashed passwords + $userData = [ + ['John Doe', 'john_doe', 'john@example.com', password_hash('password_1', PASSWORD_DEFAULT), 1], + ['Jane Smith', 'jane_smith', 'jane@example.com', password_hash('password_2', PASSWORD_DEFAULT), 0], + ['Admin User', 'admin_user', 'admin@example.com', password_hash('password_3', PASSWORD_DEFAULT), 1], + ['Alice Johnson', 'alice', 'alice@example.com', password_hash('password_4', PASSWORD_DEFAULT), 0], + ['Bob Williams', 'bob', 'bob@example.com', password_hash('password_5', PASSWORD_DEFAULT), 0] + ]; + + $sqlUser = "INSERT INTO users (user_name, username, user_email, user_hashedPass, isAdmin) VALUES (?, ?, ?, ?, ?)"; + $stmt = $db->prepare($sqlUser); + + foreach ($userData as $user) { + $stmt->execute($user); + } + + $stmt->closeCursor(); + + // // Insert pembelian data + // $sqlPembelian = <<<EOF + // INSERT INTO pembelian (ticket_id, user_id, pembelian_created_time) VALUES + // (1, 1, '2023-10-01 12:30:00'), + // (3, 2, '2023-10-06 16:15:00'), + // (2, 3, '2023-11-15 20:00:00'), + // (5, 4, '2023-12-05 10:45:00'), + // (8, 5, '2024-01-20 08:30:00'); + // EOF; + + // $db->exec($sqlPembelian); + + // Commit the transaction + $db->commit(); + + echo "Successfully inserted dummy data.<br/>"; + } catch (PDOException $e) { + $db->rollBack(); + echo "Error: " . $e->getMessage(); + } + } else { + echo "Error: Database connection not established."; + } + + $db = null; +?> diff --git a/db/init.php b/db/init.php new file mode 100644 index 0000000..d5efdd7 --- /dev/null +++ b/db/init.php @@ -0,0 +1,26 @@ +<?php +include 'connect.php'; + +$dotenvContents = file_get_contents(__DIR__ . '/../.env'); +$dotenvLines = explode("\n", $dotenvContents); + +foreach ($dotenvLines as $line) { + // Skip empty lines and comments + if (!empty($line) && strpos($line, '=') !== false && strpos($line, '#') !== 0) { + list($name, $value) = explode('=', $line, 2); + $_ENV[$name] = $value; + putenv("$name=$value"); + } +} + +error_reporting(E_ALL); +ini_set('display_errors', 1); + + +include 'reset.php'; +include 'data.php'; + +$db = null; + +// echo "Database initialization successful!"; +?> diff --git a/db/init.sql b/db/init.sql new file mode 100644 index 0000000..0beaedf --- /dev/null +++ b/db/init.sql @@ -0,0 +1,48 @@ +CREATE DATABASE IF NOT EXISTS tubes1_WBD; + +USE tubes1_WBD; + +CREATE TABLE IF NOT EXISTS events ( + event_id INT AUTO_INCREMENT PRIMARY KEY, + event_name CHAR(255), + event_stock INT, + event_price INT, + event_date DATETIME, + event_location CHAR(255), + gambar VARCHAR(255), + vid VARCHAR(255) +); + +CREATE TABLE IF NOT EXISTS tickets ( + ticket_id INT AUTO_INCREMENT PRIMARY KEY, + ticket_name CHAR(255), + event_id INT, + FOREIGN KEY (event_id) REFERENCES events(event_id) ON DELETE SET NULL +); + +CREATE TABLE IF NOT EXISTS users ( + user_ID INT AUTO_INCREMENT PRIMARY KEY, + user_name CHAR(255), + username CHAR(255) UNIQUE, + user_email VARCHAR(255) UNIQUE, + user_hashedPass CHAR(255), + isAdmin BOOLEAN +); + +CREATE TABLE IF NOT EXISTS pembelian ( + pembelian_id INT AUTO_INCREMENT PRIMARY KEY, + ticket_id INT, + user_id INT, + pembelian_created_time DATETIME, + FOREIGN KEY (ticket_id) REFERENCES tickets(ticket_id), + FOREIGN KEY (user_id) REFERENCES users(user_ID) ON DELETE SET NULL +); + +CREATE TABLE IF NOT EXISTS subscription ( + creator_id int NOT NULL, + subscriber_id int NOT NULL, + status enum('PENDING','ACCEPTED','REJECTED') NOT NULL DEFAULT 'PENDING', + creator_name char(255) NOT NULL, + PRIMARY KEY (creator_id, subscriber_id), + FOREIGN KEY (subscriber_id) REFERENCES users(user_ID) ON DELETE CASCADE +); \ No newline at end of file diff --git a/db/reset.php b/db/reset.php new file mode 100644 index 0000000..1e98b7a --- /dev/null +++ b/db/reset.php @@ -0,0 +1,15 @@ +<?php + include 'connect.php'; + + try { + $db->exec("DROP TABLE IF EXISTS pembelian"); + $db->exec("DROP TABLE IF EXISTS tickets"); + $db->exec("DROP TABLE IF EXISTS events"); + $db->exec("DROP TABLE IF EXISTS users"); + + // echo "Successfully reset the database<br/>"; + } catch (PDOException $e) { + // echo "Error: " . $e->getMessage(); + } + $db = null; +?> \ No newline at end of file diff --git a/src/.htaccess b/src/.htaccess deleted file mode 100644 index 122631d..0000000 --- a/src/.htaccess +++ /dev/null @@ -1,13 +0,0 @@ -DirectoryIndex index.php - -RewriteEngine On - -RewriteBase / - -RewriteCond %{REQUEST_FILENAME} !-f -RewriteCond %{REQUEST_FILENAME} !-d - -RewriteRule ^(.*)$ index.php [QSA] - -php_value post_max_size 16M -php_value upload_max_filesize 16M \ No newline at end of file diff --git a/src/Client/pages/login/login.php b/src/Client/pages/login/login.php deleted file mode 100644 index 017eba7..0000000 --- a/src/Client/pages/login/login.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -if (session_status() == PHP_SESSION_NONE) { - // If a session is not already started, start a new one - session_start(); -} -?> -<!DOCTYPE html> -<html lang="en"> - -<head> - <title>Login • TICKET KU</title> - <meta charset="UTF-8"> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <link rel="stylesheet" type="text/css" href="../../auth.css"> -</head> - -<body> - <div class="login-container"> - <h1>Login</h1> - <form id="loginForm" method="post" action="login"> - <!-- Aslinya email atau username bisa(?) --> - <label for="email">Email or Username</label> - <input type="text" id="identifier" name="loginIdentifier" required> - - <label for="password">Password</label> - <input type="password" id="password" name="loginPassword" required> - - <?php - // Check if there is an error message in the session - if (isset($_SESSION['message'])) { - echo '<p>' . $_SESSION['message'] . '</p>'; - unset($_SESSION['message']); // Remove the error message from the session - } - ?> - <button type="submit" name="userAction" value="login">Login</button> - </form> - <p>Don't have an account? <a href="register">Register</a></p> - </div> -</body> -</html> diff --git a/src/Server/Controllers/HomeController.php b/src/Server/Controllers/HomeController.php deleted file mode 100644 index edb1b11..0000000 --- a/src/Server/Controllers/HomeController.php +++ /dev/null @@ -1,11 +0,0 @@ -<?php - -namespace Server\Controllers; - -class HomeController { - public function __construct(){} - public function home() - { - include (__DIR__.'/../../Client/pages/home/home.php'); - } -} \ No newline at end of file diff --git a/src/Server/Models/Event.php b/src/Server/Models/Event.php deleted file mode 100644 index 85a9021..0000000 --- a/src/Server/Models/Event.php +++ /dev/null @@ -1,176 +0,0 @@ -<?php - -namespace Server\Models; - -use PDO; - -class EventModel extends Model { - - public function createEvent($event_name, $stock, $event_price, $event_date, $event_location, $gambar, $vid) { - $success = true; - - if ($gambar !== null && isset($gambar['name']) && isset($gambar['tmp_name'])) { - $imageFilePath = '../assets/images/' . $gambar['name']; - - if (move_uploaded_file($gambar['tmp_name'], $imageFilePath)) { - echo "File uploaded successfully"; - } else { - echo "Error moving file to destination"; - $imageFilePath = null; // Set to null if there's an error - } - } else { - echo "No image uploaded"; - $imageFilePath = null; // Set to null if no file is uploaded - } - - if ($vid !== null && isset($vid['name']) && isset($vid['tmp_name'])) { - $vidFilePath = '../assets/videos/' . $vid['name']; - - if (move_uploaded_file($vid['tmp_name'], $vidFilePath)) { - echo "File uploaded successfully"; - } else { - echo "Error moving file to destination"; - $vidFilePath = null; // Set to null if there's an error - } - } else { - echo "No video uploaded"; - $vidFilePath = null; // Set to null if no file is uploaded - } - - if ($imageFilePath === null || $vidFilePath === null) { - $success = false; - return $success; - } - - $stmt = $this->database->prepare("INSERT INTO events (event_name, event_stock, event_price, event_date, event_location, gambar, vid) VALUES (?, ?, ?, ?, ?, ?, ?)"); - - if ($stmt->execute([$event_name, $stock, $event_price, $event_date, $event_location, $imageFilePath, $vidFilePath])) { - echo "Event created successfully"; - return $success; - } else { - echo "Error creating event: " . print_r($stmt->errorInfo(), true); - $success = false; - return $success; - } - } - - public function updateEvent($event_id, $event_name, $event_price, $event_date, $event_location, $gambar, $vid) { - $sql = "UPDATE events SET event_name = ?, event_price = ?, event_date = ?, event_location = ?"; - - if ($gambar !== null && isset($gambar['name']) && isset($gambar['tmp_name'])) { - $imageFilePath = '../assets/images/' . $gambar['name']; - - if (move_uploaded_file($gambar['tmp_name'], $imageFilePath)) { - echo "File uploaded successfully<br>"; - } else { - echo "Error moving file to destination<br>"; - $imageFilePath = null; // Set to null if there's an error - } - - $sql .= ", gambar = ?"; - } - - if ($vid !== null && isset($vid['name']) && isset($vid['tmp_name'])) { - $vidFilePath = '../assets/videos/' . $vid['name']; - - if (move_uploaded_file($vid['tmp_name'], $vidFilePath)) { - echo "File uploaded successfully<br>"; - } else { - echo "Error moving file to destination<br>"; - $vidFilePath = null; // Set to null if there's an error - } - - $sql .= ", vid = ?"; - } - - $sql .= " WHERE event_id = ?"; - - $stmt = $this->database->prepare($sql); - - $params = [$event_name, $event_price, $event_date, $event_location]; - - if ($imageFilePath !== null) { - $params[] = $imageFilePath; - } - - if ($vidFilePath !== null) { - $params[] = $vidFilePath; - } - - $params[] = $event_id; - - $rowCount = $stmt->execute($params); - - if ($rowCount !== false) { - echo "Event updated successfully. Rows affected: $rowCount"; - } else { - echo "Error updating event: " . print_r($stmt->errorInfo(), true); - } - return "Event updated successfully"; - } - - public function deleteEvent($eventId) { - try { - // Delete associated records or perform necessary cleanup - - $stmtEvent = $this->database->prepare("DELETE FROM events WHERE event_id = ?"); - $stmtEvent->execute([$eventId]); - - echo "Event deleted successfully<br>"; - - return "Event deleted successfully"; - } catch (PDOException $e) { - echo "Error: " . $e->getMessage() . "<br>"; - - return "Error: " . $e->getMessage(); - } - } - - public function getAllEvents() { - $stmt = $this->database->prepare("SELECT * FROM events"); - $stmt->execute(); - return $stmt->fetchAll(PDO::FETCH_ASSOC); - } - - public function getEvent($eventId) { - $stmt = $this->database->prepare("SELECT * FROM events WHERE event_id = ?"); - $stmt->execute([$eventId]); - return $stmt->fetch(PDO::FETCH_ASSOC); - } - - public function getLastEventId() { - $stmt = $this->database->prepare("SELECT event_id FROM events ORDER BY event_id DESC LIMIT 1"); - $stmt->execute(); - return $stmt->fetch(PDO::FETCH_ASSOC)['event_id']; - } - - public function searchEvents($searchQuery, $sortKey, $minStock) { - try { - if ($minStock == null) { - $minStock = 0; - } - - $stmt = "SELECT * FROM events - WHERE (LOWER(event_name) LIKE LOWER(?) OR LOWER(event_location) LIKE LOWER(?)) - AND event_stock >= ?"; - - if (!empty($sortKey)) { - $stmt .= " ORDER BY "; - - if ($sortKey === 'name') { - $stmt .= "event_name ASC"; - } elseif ($sortKey === 'location') { - $stmt .= "event_location ASC"; - } - } - - $query = $this->database->prepare($stmt); - $query->execute(array('%'.$searchQuery.'%', '%'.$searchQuery.'%', $minStock)); - - return $query->fetchAll(PDO::FETCH_ASSOC); - } catch (PDOException $e) { - throw new Exception("Error searching events: " . $e->getMessage()); - } - } - -} diff --git a/src/Server/Models/Model.php b/src/Server/Models/Model.php deleted file mode 100644 index fc2fe6b..0000000 --- a/src/Server/Models/Model.php +++ /dev/null @@ -1,22 +0,0 @@ -<?php - -namespace Server\Models; - -use PDO; - -class Model { - protected $database; - - public function __construct() - { - $dsn = "pgsql:host=ticketku-php-db;port=5433;dbname=ticketku;"; - $user = "postgres"; - $password = "postgres"; - try { - $this->database = new PDO($dsn, $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); - } catch (\PDOException $e) { - die($e->getMessage()); - } - } - -} diff --git a/src/Server/Models/Pembelian.php b/src/Server/Models/Pembelian.php deleted file mode 100644 index ed44a4b..0000000 --- a/src/Server/Models/Pembelian.php +++ /dev/null @@ -1,64 +0,0 @@ -<?php - -namespace Server\Models; - -use PDO; - -class PembelianModel extends Model { - public function createPembelian($ticketId, $userId, $createdTime) { - $stmt = $this->database->prepare("INSERT INTO pembelian (ticket_id, user_id, pembelian_created_time) VALUES (?, ?, ?)"); - - if ($stmt->execute([$ticketId, $userId, $createdTime])) { - $stmt = $this->database->prepare("SELECT event_id FROM tickets WHERE ticket_id = ?"); - $stmt->execute([$ticketId]); - $result = $stmt->fetch(PDO::FETCH_ASSOC); - - if ($result) { - $eventId = $result['event_id']; - - // Decrement the event's stock by 1 - $stmt = $this->database->prepare("UPDATE events SET event_stock = event_stock - 1 WHERE event_id = ?"); - return $stmt->execute([$eventId]); - } - } - } - - public function getPembelian($pembelianId) { - $stmt = $this->database->prepare("SELECT * FROM pembelian WHERE pembelian_id = ?"); - $stmt->execute([$pembelianId]); - - return $stmt->fetch(PDO::FETCH_ASSOC); - } - - public function updatePembelian($pembelianId, $ticketId, $userId, $createdTime) { - $stmt = $this->database->prepare("UPDATE pembelian SET ticket_id = ?, user_id = ?, pembelian_created_time = ? WHERE pembelian_id = ?"); - $stmt->execute([$ticketId, $userId, $createdTime, $pembelianId]); - - return "Pembelian updated successfully"; - } - - public function deletePembelian($pembelianId) { - $stmt = $this->database->prepare("DELETE FROM pembelian WHERE pembelian_id = ?"); - $stmt->execute([$pembelianId]); - - return "Pembelian deleted successfully"; - } - - public function getAllPembelian() { - $stmt = $this->database->prepare("SELECT * FROM pembelian"); - $stmt->execute(); - return $stmt->fetchAll(PDO::FETCH_ASSOC); - } - - public function getAllPembelianWithDetails() { - $stmt = $this->database->prepare("SELECT * FROM pembelian JOIN tickets ON pembelian.ticket_id = tickets.ticket_id JOIN events ON tickets.event_id = events.event_id ORDER BY pembelian_created_time DESC"); - $stmt->execute(); - return $stmt->fetchAll(PDO::FETCH_ASSOC); - } - - public function getPembelianByUserId($userId) { - $stmt = $this->database->prepare("SELECT * FROM pembelian JOIN tickets ON pembelian.ticket_id = tickets.ticket_id JOIN events ON tickets.event_id = events.event_id WHERE user_id = ? ORDER BY pembelian_created_time DESC"); - $stmt->execute([$userId]); - return $stmt->fetchAll(PDO::FETCH_ASSOC); - } -} diff --git a/src/Server/Router/Router.php b/src/Server/Router/Router.php deleted file mode 100644 index 7849f64..0000000 --- a/src/Server/Router/Router.php +++ /dev/null @@ -1,69 +0,0 @@ -<?php - -namespace Server\Router; - -class Router { - private array $handlers; - private const METHOD_GET = 'GET'; - private const METHOD_POST = 'POST'; - - public function get(string $path, $handler): void - { - $this->addHandler(self::METHOD_GET, $path, $handler); - } - - public function post(string $path, $handler): void - { - $this->addHandler(self::METHOD_POST, $path, $handler); - } - - private function addHandler(string $method, string $path, $handler): void - { - $this->handlers[$method.$path] = [ - 'path' => $path, - 'method' => $method, - 'handler' => $handler, - ]; - } - - public function run() - { - $requstUri = parse_url($_SERVER['REQUEST_URI']); - $requestPath = $requstUri['path']; - $method = $_SERVER['REQUEST_METHOD']; - - $callback = null; - foreach ($this->handlers as $handler) { - if($handler['path'] === $requestPath && $method === $handler['method']) { - $callback = $handler['handler']; - } - } - - if (is_string($callback)) { - $parts = explode('@', $callback); - if (is_array($parts)) { - $className = array_shift($parts); - $method = array_shift($parts); - - // Check if the class exists before creating an instance - if (class_exists($className)) { - $handler = new $className; - - // Check if the method exists before setting the callback - if (method_exists($handler, $method)) { - $callback = [$handler, $method]; - } - } - } - } - - if(!$callback) { - include 'Client/pages/Errors/NotFound.php'; - return; - } - - call_user_func_array($callback, [ - array_merge($_GET, $_POST) - ]); - } -} \ No newline at end of file diff --git a/src/Server/web.php b/src/Server/web.php deleted file mode 100644 index d3dbe64..0000000 --- a/src/Server/web.php +++ /dev/null @@ -1,55 +0,0 @@ -<?php - -declare(strict_types=1); - -include (__DIR__."/Router/Router.php"); -include (__DIR__."/Controllers/UserController.php"); -include (__DIR__."/Controllers/EventController.php"); -include (__DIR__."/Controllers/HomeController.php"); - -$router = new \Server\Router\Router(); - -function checkLoggedIn(): bool { - if (session_status() == PHP_SESSION_NONE) { - // If a session is not already started, start a new one - session_start(); - } - return isset($_SESSION['user_id']); -} - -$router->get('/', function() { - header('Location: /home'); - exit(); -}); - -// Routes for HomeController -$router->get('/home', [new \Server\Controllers\HomeController(),'home']); - -// Routes for UserController -$router->get('/register', [new \Server\Controllers\UserController(), 'registerview']); -$router->post('/register', [new \Server\Controllers\UserController(), 'register']); -$router->post('/register/search-email', [checkLoggedIn(), [new \Server\Controllers\UserController(), 'findEmail']]); -$router->post('/register/search-username', [checkLoggedIn(), [new \Server\Controllers\UserController(), 'findByUsername']]); -$router->get('/login', [new \Server\Controllers\UserController(), 'loginview']); -$router->post('/login', [new \Server\Controllers\UserController(), 'login']); -$router->post('/logout', function() { - // No need to checkLoggedIn() here, as users can access this even if not logged in - if (session_status() == PHP_SESSION_NONE) { - // If a session is not already started, start a new one - session_start(); - } - session_destroy(); - header('Location: /login'); - exit(); -}); -$router->post('/profile', [checkLoggedIn(), [new \Server\Controllers\UserController(), 'viewProfile']]); -$router->post('/profile/edit', [checkLoggedIn(), [new \Server\Controllers\UserController(), 'editProfile']]); - -// Routes for EventsController -// $router->get('/events', [checkLoggedIn(), [new \Server\Controllers\EventController(), 'eventList10view']]); -// $router->post('/events/create', [checkLoggedIn(), [new \Server\Controllers\EventController(), 'createEvent']]); -// $router->post('/events/update', [checkLoggedIn(), [new \Server\Controllers\EventController(), 'updateEvent']]); -// $router->post('/events/delete', [checkLoggedIn(), [new \Server\Controllers\EventController(), 'deleteEvent']]); -// $router->get('/events/search', [checkLoggedIn(), [new \Server\Controllers\EventController(), 'searchview']]); - -$router->run(); diff --git a/src/index.php b/src/index.php deleted file mode 100644 index f6f970c..0000000 --- a/src/index.php +++ /dev/null @@ -1,11 +0,0 @@ -<?php -declare(strict_types=1); - -if (session_status() == PHP_SESSION_NONE) { - // If a session is not already started, start a new one - session_start(); -} - -include 'Server/web.php'; - -?> diff --git a/src/Client/auth.css b/styles/auth.css similarity index 100% rename from src/Client/auth.css rename to styles/auth.css diff --git a/src/Client/container.css b/styles/container.css similarity index 100% rename from src/Client/container.css rename to styles/container.css diff --git a/src/Client/dropdown.css b/styles/dropdown.css similarity index 100% rename from src/Client/dropdown.css rename to styles/dropdown.css diff --git a/src/Client/footer.css b/styles/footer.css similarity index 100% rename from src/Client/footer.css rename to styles/footer.css diff --git a/src/Client/form.css b/styles/form.css similarity index 100% rename from src/Client/form.css rename to styles/form.css diff --git a/src/Client/global.css b/styles/global.css similarity index 100% rename from src/Client/global.css rename to styles/global.css diff --git a/src/Client/navbar.css b/styles/navbar.css similarity index 100% rename from src/Client/navbar.css rename to styles/navbar.css diff --git a/src/Client/pagination.css b/styles/pagination.css similarity index 100% rename from src/Client/pagination.css rename to styles/pagination.css -- GitLab