Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
82.10% covered (warning)
82.10%
133 / 162
58.33% covered (warning)
58.33%
7 / 12
CRAP
0.00% covered (danger)
0.00%
0 / 1
OrderController
81.76% covered (warning)
81.76%
130 / 159
58.33% covered (warning)
58.33%
7 / 12
36.83
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getOrders
19.05% covered (danger)
19.05%
4 / 21
0.00% covered (danger)
0.00%
0 / 1
7.77
 updatePaymentStatus
40.00% covered (danger)
40.00%
2 / 5
0.00% covered (danger)
0.00%
0 / 1
2.86
 deleteOrder
40.00% covered (danger)
40.00%
2 / 5
0.00% covered (danger)
0.00%
0 / 1
2.86
 getAllOrders
82.35% covered (warning)
82.35%
14 / 17
0.00% covered (danger)
0.00%
0 / 1
3.05
 createOrder
100.00% covered (success)
100.00%
59 / 59
100.00% covered (success)
100.00%
1 / 1
8
 getCartItems
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 clearCart
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getUserOrders
85.00% covered (warning)
85.00%
17 / 20
0.00% covered (danger)
0.00%
0 / 1
3.03
 getAllProducts
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
3
 getAllUsers
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
3
 handleDatabaseError
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2namespace Controllers;
3
4require_once __DIR__ . '/../Models/Order.php';
5require_once __DIR__ . '/../Models/Product.php';
6require_once __DIR__ . '/../Models/User.php';
7use Models\Order;
8use Models\Product;
9use Models\User;
10
11class OrderController {
12    private $conn;
13
14    public function __construct($conn) {
15        $this->conn = $conn;
16    }
17
18    public function getOrders($userId) {
19        try {
20            $stmt = $this->conn->prepare("SELECT * FROM orders WHERE user_id = ?");
21            $stmt->execute([$userId]);
22            $orders = [];
23            foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
24                $order = new Order();
25                $order->setId($row['id']);
26                $order->setUserId($row['user_id']);
27                $order->setName($row['name']);
28                $order->setNumber($row['number']);
29                $order->setEmail($row['email']);
30                $order->setMethod($row['method']);
31                $order->setAddress($row['address']);
32                $order->setTotalProducts($row['total_products']);
33                $order->setTotalPrice($row['total_price']);
34                $order->setPaymentStatus($row['payment_status']);
35                $order->setPlacedOn($row['placed_on']);
36                $orders[] = $order;
37            }
38            return $orders;
39        } catch (\Exception $e) {
40            $this->handleDatabaseError($e);
41            return [];
42        }
43    }
44
45    public function updatePaymentStatus($orderId, $status) {
46        try {
47            $stmt = $this->conn->prepare("UPDATE orders SET payment_status = ? WHERE id = ?");
48            return $stmt->execute([$status, $orderId]);
49        } catch (\Exception $e) {
50            error_log("Error al actualizar estado: " . $e->getMessage());
51            return false;
52        }
53    }
54
55    public function deleteOrder($orderId) {
56        try {
57            $stmt = $this->conn->prepare("DELETE FROM orders WHERE id = ?");
58            return $stmt->execute([$orderId]);
59        } catch (\Exception $e) {
60            error_log("Error al eliminar orden: " . $e->getMessage());
61            return false;
62        }
63    }
64
65    public function getAllOrders() {
66        try {
67            $stmt = $this->conn->prepare("SELECT * FROM `orders`");
68            $stmt->execute();
69            $orders = [];
70            foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
71                $order = new Order();
72                $order->setUserId($row['user_id']);
73                $order->setName($row['name']);
74                $order->setEmail($row['email']);
75                $order->setMethod($row['method']);
76                $order->setAddress($row['address']);
77                $order->setTotalProducts($row['total_products']);
78                $order->setTotalPrice($row['total_price']);
79                $orders[] = $order;
80            }
81            return $orders;
82        } catch (\Exception $e) {
83            $this->handleDatabaseError($e);
84            return [];
85        }
86    }
87
88    public function createOrder($userData, $userId) {
89        try {
90            $order = new Order();
91            $order->setUserId($userId);
92            $order->setName($userData['name']);
93            $order->setNumber($userData['number']);
94            $order->setEmail($userData['email']);
95            $order->setMethod($userData['method']);
96            
97            // Obtener productos del carrito
98            $cartItems = $this->getCartItems($userId);
99            if(empty($cartItems)) {
100                return ['success' => false, 'message' => 'El carrito está vacío'];
101            }
102
103            // Validar productos antes de procesar
104            foreach($cartItems as $item) {
105                if(empty($item['name'])) {
106                    return ['success' => false, 'message' => 'Error: nombre de producto inválido'];
107                }
108                if($item['price'] < 0) {
109                    return ['success' => false, 'message' => 'Error: precio inválido'];
110                }
111            }
112
113            // Calcular total y preparar lista de productos
114            $cartTotal = 0;
115            $products = [];
116            foreach($cartItems as $item) {
117                $products[] = $item['name'] . ' (' . $item['quantity'] . ')';
118                $cartTotal += ($item['price'] * $item['quantity']);
119            }
120            $totalProducts = implode(', ', $products);
121
122            // Formatear y establecer dirección
123            $address = 'flat no. ' . $userData['flat'] . ', ' . 
124                      $userData['street'] . ', ' . 
125                      $userData['city'] . ', ' . 
126                      $userData['country'] . ' - ' . 
127                      $userData['pin_code'];
128            
129            // Establecer valores adicionales en el objeto Order
130            $order->setAddress($address);
131            $order->setTotalProducts($totalProducts);
132            $order->setTotalPrice($cartTotal);
133            
134            // Verificar si la orden ya existe
135            $stmt = $this->conn->prepare("SELECT * FROM orders WHERE 
136                name = ? AND number = ? AND email = ? AND 
137                method = ? AND address = ? AND 
138                total_products = ? AND total_price = ?");
139            
140            $stmt->execute([
141                $order->getName(),
142                $order->getNumber(),
143                $order->getEmail(),
144                $order->getMethod(),
145                $order->getAddress(),
146                $order->getTotalProducts(),
147                $order->getTotalPrice()
148            ]);
149
150            if($stmt->rowCount() > 0) {
151                return ['success' => false, 'message' => '¡Pedido ya realizado!'];
152            }
153
154            // Insertar nueva orden
155            $stmt = $this->conn->prepare("INSERT INTO orders 
156                (user_id, name, number, email, method, address, 
157                total_products, total_price, placed_on) 
158                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
159
160            $stmt->execute([
161                $order->getUserId(),
162                $order->getName(),
163                $order->getNumber(),
164                $order->getEmail(),
165                $order->getMethod(),
166                $order->getAddress(),
167                $order->getTotalProducts(),
168                $order->getTotalPrice(),
169                date('d-M-Y')
170            ]);
171
172            // Limpiar carrito
173            $this->clearCart($userId);
174
175            return ['success' => true, 'message' => '¡Pedido realizado con éxito!'];
176        } catch (\Exception $e) {
177            error_log("Error al crear orden: " . $e->getMessage());
178            return ['success' => false, 'message' => 'Error al procesar el pedido'];
179        }
180    }
181
182    private function getCartItems($userId) {
183        $stmt = $this->conn->prepare("SELECT * FROM cart WHERE user_id = ?");
184        $stmt->execute([$userId]);
185        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
186    }
187
188    private function clearCart($userId) {
189        $stmt = $this->conn->prepare("DELETE FROM cart WHERE user_id = ?");
190        $stmt->execute([$userId]);
191    }
192
193    public function getUserOrders($userId) {
194        try {
195            $stmt = $this->conn->prepare("SELECT * FROM orders WHERE user_id = ?");
196            $stmt->execute([$userId]);
197            $orders = [];
198            foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
199                $order = new Order();
200                $order->setUserId($row['user_id']);
201                $order->setName($row['name']);
202                $order->setNumber($row['number']);
203                $order->setEmail($row['email']);
204                $order->setMethod($row['method']);
205                $order->setAddress($row['address']);
206                $order->setTotalProducts($row['total_products']);
207                $order->setTotalPrice($row['total_price']);
208                $order->setPaymentStatus($row['payment_status']);
209                $order->setPlacedOn($row['placed_on']);
210                $orders[] = $order;
211            }
212            return $orders;
213        } catch (\Exception $e) {
214            error_log("Error al obtener órdenes del usuario: " . $e->getMessage());
215            return [];
216        }
217    }
218
219    public function getAllProducts() {
220        try {
221            $stmt = $this->conn->query("SELECT * FROM `products`");
222            $products = [];
223            foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
224                $product = new Product();
225                $product->setName($row['name']);
226                $product->setPrice($row['price']);
227                $product->setImage($row['image']);
228                $products[] = $product;
229            }
230            return $products;
231        } catch (\Exception $e) {
232            $this->handleDatabaseError($e);
233            return [];
234        }
235    }
236
237    public function getAllUsers() {
238        try {
239            $stmt = $this->conn->prepare("SELECT * FROM `users`");
240            $stmt->execute();
241            $users = [];
242            foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
243                $user = new User();
244                $user->setName($row['name']);
245                $user->setEmail($row['email']);
246                $user->setUserType($row['user_type']);
247                $users[] = $user;
248            }
249            return $users;
250        } catch (\Exception $e) {
251            $this->handleDatabaseError($e);
252            return [];
253        }
254    }
255
256    private function handleDatabaseError(\Exception $e) {
257        error_log("Error en la base de datos: " . $e->getMessage());
258    }
259}