DiscountModel.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace Models;
  3. class DiscountModel
  4. {
  5. private \PDO $pdo;
  6. public function __construct()
  7. {
  8. if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof \PDO) {
  9. $this->pdo = $GLOBALS['pdo'];
  10. return;
  11. }
  12. throw new \RuntimeException('Global PDO connection not initialized');
  13. }
  14. public function getAll(): array
  15. {
  16. $stmt = $this->pdo->query('SELECT discount_id, discount_value, discount_code FROM "discount" ORDER BY discount_id');
  17. return $stmt->fetchAll(\PDO::FETCH_ASSOC);
  18. }
  19. public function findByCode(string $code): ?array
  20. {
  21. $stmt = $this->pdo->prepare('SELECT discount_id, discount_value, discount_code FROM "discount" WHERE discount_code = :code LIMIT 1');
  22. $stmt->execute(['code' => $code]);
  23. $row = $stmt->fetch(\PDO::FETCH_ASSOC);
  24. return $row ?: null;
  25. }
  26. public function create(int $discountValue, string $discountCode): array
  27. {
  28. $stmt = $this->pdo->prepare('INSERT INTO "discount" (discount_value, discount_code) VALUES (:value, :code) RETURNING discount_id');
  29. $stmt->execute([
  30. 'value' => $discountValue,
  31. 'code' => $discountCode,
  32. ]);
  33. $id = (int)$stmt->fetchColumn();
  34. return [
  35. 'discount_id' => $id,
  36. 'discount_value' => $discountValue,
  37. 'discount_code' => $discountCode,
  38. ];
  39. }
  40. public function delete(int $discountId): bool
  41. {
  42. $stmt = $this->pdo->prepare('DELETE FROM "discount" WHERE discount_id = :id');
  43. $stmt->execute(['id' => $discountId]);
  44. return $stmt->rowCount() > 0;
  45. }
  46. }