Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

creating cart crud #55

Merged
merged 1 commit into from
Feb 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions controllers/CartController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php

namespace app\controllers;
use app\core\Application;
use app\core\Controller;
use app\core\Request;
use app\core\Response;
use app\models\cart;

class CartController extends Controller {

// add product to the cart
public function addToCartController (Request $request, Response $response) {
$user_id = Application::$app->session->get('customer');

if (!$user_id) {
Application::$app->response->redirect('/customer-login');
}

$product_id = $request->getBody()['product_id'];
$quantity = $request->getBody()['quantity'] ?? 1;

if (!$product_id) {
Application::$app->session->setFlash('error','no id getting ');
}

$cart = new Cart();
if ($cart->addToCart($user_id, $product_id, $quantity)) {
Application::$app->session->setFlash('success','Product add to cart');
// http_response_code(200); // Set HTTP status code
// header('Content-Type: application/json'); // Set response header
// echo json_encode(['message' => 'Product added to cart']);
Application::$app->response->redirect('/market-place-home');

} else {
Application::$app->session->setFlash('error','Prodcut add to cart fail');
// http_response_code(400); // Set HTTP status code
// header('Content-Type: application/json'); // Set response header
// echo json_encode(['message' => 'Failed to add product to cart']);
Application::$app->response->redirect('/market-place-home');
}
}

//function to retrive products
public function viewCart() {
if (!Application::$app->session->get('customer')) {
Application::$app->response->redirect('/customer-login');
}

$user_id = Application::$app->session->get('customer');
$cart = new Cart();
$cartItems = $cart->getCartItems($user_id);

if(empty($cartItems)){
Application::$app->session->setFlash('error','Cart is empty');
Application::$app->response->redirect('/market-place-home');
}

$this->setLayout('auth');
return $this->render('service-centre/view-cart', ['cartItems'=> $cartItems]);

}

//function to remove cart items
public function removeItemsFromCart(Request $request, Response $response) {
if (!Application::$app->session->get('customer')) {
Application::$app->session->setFlash('error','Please login first');
Application::$app->response->redirect('/customer-login');
}
$user_id = Application::$app->session->get('customer');
$product_id = $request->getBody()['product_id'];

if (!$product_id) {
Application::$app->session->setFlash('error','Select item to remove');
}
$cart = new Cart();
if ($cart->removeCartItem($user_id, $product_id)) {
Application::$app->response->redirect('/view-cart');
Application::$app->session->setFlash('success','Product remove successfully');
} else {
Application::$app->session->setFlash('error','Product remove failed, try again');
}
}

}
21 changes: 20 additions & 1 deletion controllers/ProductController.php
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,27 @@ public function delete(Request $request){
}


}
public function filterProductByCategory(Request $request, Response $response) {
//get category by the params

$category = $_GET['category'] ?? 'all';

if ($category === 'all') {
$products = (new Product())->getAllProducts();
} else {
$products = (new Product())->getProductsByCategory($category);
}



if ($products) {
$this->setLayout('auth');
return $this->render('service-centre/market-place-home', [
'products'=> $products,
]);
}
}

}

?>
6 changes: 6 additions & 0 deletions controllers/ServiceCentreController.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,12 @@ public function serviceCenterMessages()
return $this->render('/service-centre/service-center-messages');
}

public function cart()
{
$this->setLayout('auth');
return $this->render('/service-centre/view-cart');
}

public function viewServiceCenterProfile($id)
{

Expand Down
7 changes: 7 additions & 0 deletions core/DbModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ abstract public function attributes(): array;
abstract public function primaryKey(): string;


// protected Database $db;

// public function __construct(){
// $this->db = Application::$app->db;
// }


public function save()
{

Expand Down
27 changes: 25 additions & 2 deletions models/Product.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class Product extends DbModel
public string $description = '';
public float $price;
public string $media = '';
public string $category;
public ?string $created_at = null;
public ?string $updated_at = null;

Expand All @@ -21,7 +22,7 @@ public function tableName(): string

public function attributes(): array
{
return ['ser_cen_id', 'description', 'price', 'media'];
return ['ser_cen_id', 'description', 'price', 'media', 'category'];
}
public function primaryKey(): string
{
Expand Down Expand Up @@ -101,7 +102,7 @@ public function editProduct(): bool
{
$sql = "
UPDATE product
SET description = :description, price = :price, media = CASE WHEN :media = '' THEN media ELSE :media END, updated_at = NOW()
SET description = :description, price = :price, category = :category, media = CASE WHEN :media = '' THEN media ELSE :media END, updated_at = NOW()
WHERE product_id = :product_id AND ser_cen_id = :ser_cen_id
";

Expand All @@ -111,6 +112,7 @@ public function editProduct(): bool
$stmt->bindValue(':media', $this->media);
$stmt->bindValue(':product_id', $this->product_id);
$stmt->bindValue(':ser_cen_id', $this->ser_cen_id);
$stmt->bindValue(':category', $this->category);

// Debugging: Check SQL and parameters
// var_dump([
Expand Down Expand Up @@ -163,6 +165,27 @@ public function updateRules(): array

];
}

public function getProductsByCategory(string $category) {
try {

$sql = 'SELECT p.*, s.name AS seller_name
FROM product p
JOIN service_center s ON p.ser_cen_id = s.ser_cen_id
WHERE p.category = :category
ORDER BY p.created_at DESC';

$stmt = self::prepare($sql);
$stmt->bindValue(':category', $category);
$stmt->execute();

return $stmt->fetchAll(\PDO::FETCH_ASSOC);

} catch (\Exception $e) {
error_log($e->getMessage());
return [];
}
}
}

?>
121 changes: 121 additions & 0 deletions models/cart.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
<?php

namespace app\models;
use app\core\DbModel;
use app\core\Application;

class Cart extends DbModel
{
public int $id;
public int $cart_id;
public int $user_id;
public int $product_id;
public int $quantity;
public ?string $created_at = null;
public ?string $updated_at = null;

public function tableName(): string {
return 'cart_items';
}

public function attributes(): array {
return ['cart_id','product_id','quantity'];
}

public function primaryKey(): string {
return 'id';
}

// add a product to cart
public function addToCart(int $user_id, int $product_id, int $quantity) {
//get the cart_id for the user
$sql = 'SELECT cart_id FROM customer WHERE cus_id = :cus_id';
$stmt = self::prepare($sql);
$stmt->bindValue(':cus_id', $user_id);
$stmt->execute();
$cart = $stmt->fetchColumn();

//if user does not have an cart, then create a one
if (!$cart) {
// $this->db->query("INSERT INTO cart (user_id) VALUES (?)", [$user_id]);
// $cart = $this->db->lastInsertId();
// $this->db->query("UPDATE customer SET cart_id = ? WHERE cus_id = ?", [$cart, $user_id]);
$stmt = Application::$app->db->pdo->prepare("INSERT INTO cart (user_id) VALUES (?)");
$stmt->execute([$user_id]);

// Get last inserted cart_id
$cart = Application::$app->db->pdo->lastInsertId();

// Update customer table with the cart_id
$stmt = Application::$app->db->pdo->prepare("UPDATE customer SET cart_id = ? WHERE cus_id = ?");
$stmt->execute([$cart, $user_id]);
}
// $existing = $this->db->query("SELECT id FROM cart_items WHERE cart_id = ? AND product_id = ?", [$cart, $product_id])->fetchColumn();
// Check if the product is already in the cart
$stmt = Application::$app->db->pdo->prepare("SELECT id FROM cart_items WHERE cart_id = ? AND product_id = ?");
$stmt->execute([$cart, $product_id]);
$existing = $stmt->fetchColumn();

if ($existing) {
// $this->db->query("UPDATE cart_items SET quantity = quantity + ? WHERE id = ?", [$quantity, $existing]);
// Update quantity if product exists in cart
$stmt = Application::$app->db->pdo->prepare("UPDATE cart_items SET quantity = quantity + ? WHERE id = ?");
$stmt->execute([$quantity, $existing]);
} else {
// $this->db->query("INSERT INTO cart_items (cart_id, product_id, quantity) VALUES (?, ?, ?)", [$cart, $product_id, $quantity]);
// Insert new product into cart_items
$stmt = Application::$app->db->pdo->prepare("INSERT INTO cart_items (cart_id, product_id, quantity) VALUES (?, ?, ?)");
$stmt->execute([$cart, $product_id, $quantity]);
}

return true;

}

//get all items for a specific user
public function getCartItems(int $user_id) {
$db = Application::$app->db->pdo;
$stmt = $db->prepare("
SELECT ci.id, ci.product_id, ci.quantity, p.description, p.price, p.media
FROM cart_items ci
JOIN cart c ON ci.cart_id = c.id
JOIN product p ON ci.product_id = p.product_id
WHERE c.user_id = ?
");
$stmt->execute([$user_id]);
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}

//model to remove items from the cart
public function removeCartItem(int $user_id, int $product_id) {
$db = Application::$app->db->pdo;

$stmt = $db->prepare("SELECT id FROM cart WHERE user_id = ?");
$stmt->execute([$user_id]);
$cart = $stmt->fetch(\PDO::FETCH_ASSOC);

if (!$cart) {
return false;
}

$cart_id = $cart['id'];

$stmt = $db->prepare("DELETE FROM cart_items WHERE cart_id = ? AND product_id = ?");
return $stmt->execute([$cart_id, $product_id]);
}

public function rules(): array
{
return [

];
}

public function updateRules(): array
{
return [

];
}

}
27 changes: 27 additions & 0 deletions public/css/service-center/add-products.css
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,33 @@ table tr:hover {
background-color: #e9ecef;
}

.category-select {
width: 100%;
max-width: 300px;
padding: 10px;
font-size: 14px;
border: 2px solid #ccc;
border-radius: 5px;
background-color: #fff;
color: #333;
cursor: pointer;
outline: none;
transition: border-color 0.3s ease-in-out;
}

.category-select:focus {
border-color: #007bff;
}

option {
font-size: 14px;
padding: 10px;
}

.category-select:hover {
border-color: #0056b3;
}

/* Responsive Table */
@media (max-width: 768px) {
table {
Expand Down
Loading