<?php

namespace Models;

class DiscountModel
{
    private \PDO $pdo;

    public function __construct()
    {
        if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof \PDO) {
            $this->pdo = $GLOBALS['pdo'];
            return;
        }

        throw new \RuntimeException('Global PDO connection not initialized');
    }

    public function getAll(): array
    {
        $stmt = $this->pdo->query('SELECT discount_id, discount_value, discount_code FROM "discount" ORDER BY discount_id');
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    public function findByCode(string $code): ?array
    {
        $stmt = $this->pdo->prepare('SELECT discount_id, discount_value, discount_code FROM "discount" WHERE discount_code = :code LIMIT 1');
        $stmt->execute(['code' => $code]);
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
        return $row ?: null;
    }

    public function create(int $discountValue, string $discountCode): array
    {
        $stmt = $this->pdo->prepare('INSERT INTO "discount" (discount_value, discount_code) VALUES (:value, :code) RETURNING discount_id');
        $stmt->execute([
            'value' => $discountValue,
            'code' => $discountCode,
        ]);
        $id = (int)$stmt->fetchColumn();

        return [
            'discount_id' => $id,
            'discount_value' => $discountValue,
            'discount_code' => $discountCode,
        ];
    }

    public function delete(int $discountId): bool
    {
        $stmt = $this->pdo->prepare('DELETE FROM "discount" WHERE discount_id = :id');
        $stmt->execute(['id' => $discountId]);
        return $stmt->rowCount() > 0;
    }
}
