<?php

declare(strict_types=1);

namespace App\Models;

use Core\Database;

final class DealModel
{
    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.*, u.name AS created_by_name,
                    (SELECT COUNT(*) FROM deal_items di WHERE di.deal_id = d.id) AS item_count
               FROM deals d
               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 deals");
    }

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

    public function getDealItems(int $dealId): array
    {
        return $this->db->fetchAll(
            "SELECT di.*, mi.name AS item_name, mi.base_price, mi.item_image
               FROM deal_items di
               JOIN menu_items mi ON mi.id = di.menu_item_id
              WHERE di.deal_id = ?
              ORDER BY di.id ASC",
            [$dealId]
        );
    }

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

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

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

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

    public function saveDealItems(int $dealId, array $itemIds, array $quantities): void
    {
        $this->db->query("DELETE FROM deal_items WHERE deal_id = ?", [$dealId]);

        foreach ($itemIds as $i => $itemId) {
            if (!(int)$itemId) continue;
            $this->db->insert('deal_items', [
                'deal_id'      => $dealId,
                'menu_item_id' => (int)$itemId,
                'quantity'     => max(1, (int)($quantities[$i] ?? 1)),
            ]);
        }
    }
}
