<?php

declare(strict_types=1);

namespace App\Models;

use Core\Database;

final class DiscountModel
{
    private Database $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    public function all(int $page = 1, int $perPage = ITEMS_PER_PAGE): array
    {
        $offset = ($page - 1) * $perPage;

        return $this->db->fetchAll(
            "SELECT d.*,
                    CASE
                        WHEN d.applies_to = 'item'     THEN mi.name
                        WHEN d.applies_to = 'category' THEN c.name
                        ELSE 'All Orders'
                    END AS target_label,
                    u.name AS created_by_name
               FROM discount_offers d
               LEFT JOIN menu_items mi ON mi.id = d.target_id AND d.applies_to = 'item'
               LEFT JOIN categories  c ON c.id  = d.target_id AND d.applies_to = 'category'
               LEFT JOIN users u       ON u.id  = d.created_by
              ORDER BY d.created_at DESC
              LIMIT ? OFFSET ?",
            [$perPage, $offset]
        );
    }

    public function count(): int
    {
        return (int) $this->db->fetchValue("SELECT COUNT(*) FROM discount_offers");
    }

    public function find(int $id): ?array
    {
        return $this->db->fetchOne("SELECT * FROM discount_offers WHERE id = ?", [$id]);
    }

    public function create(array $data): int
    {
        return $this->db->insert('discount_offers', $data);
    }

    public function update(int $id, array $data): void
    {
        $this->db->update('discount_offers', $data, ['id' => $id]);
    }

    public function delete(int $id): void
    {
        $this->db->delete('discount_offers', ['id' => $id]);
    }

    public function toggle(int $id): bool
    {
        $current = (int) $this->db->fetchValue(
            "SELECT is_active FROM discount_offers WHERE id = ?", [$id]
        );
        $this->db->update('discount_offers', ['is_active' => $current ? 0 : 1], ['id' => $id]);
        return !$current;
    }
}
