<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\BaseModel;

/** Covers both service_types (appointment durations/prices) and service_plans (recurring billing plans) — kept in one model since they're always managed together on the Services admin page. */
final class ServiceModel extends BaseModel
{
    protected string $table = 'service_types';
    protected array $fillable = ['business_line_id', 'name', 'default_duration_minutes', 'default_price', 'currency', 'is_active'];
    protected bool $timestamps = false;
    protected bool $softDeletes = false;
    protected bool $auditStamps = false;

    public function allWithBusinessLine(): array
    {
        return $this->db->query(
            'SELECT st.*, bl.name AS business_line_name FROM service_types st
             LEFT JOIN business_lines bl ON bl.id = st.business_line_id
             ORDER BY bl.name, st.name'
        )->fetchAll();
    }

    public function plans(): array
    {
        return $this->db->query(
            'SELECT sp.*, bl.name AS business_line_name FROM service_plans sp
             LEFT JOIN business_lines bl ON bl.id = sp.business_line_id
             WHERE sp.is_active = 1
             ORDER BY bl.name, sp.name'
        )->fetchAll();
    }

    public function insertPlan(array $data): int
    {
        $stmt = $this->db->prepare(
            'INSERT INTO service_plans (business_line_id, name, billing_frequency, base_price, currency, is_active, created_at, updated_at)
             VALUES (:business_line_id, :name, :billing_frequency, :base_price, :currency, 1, NOW(), NOW())'
        );
        $stmt->execute([
            'business_line_id' => $data['business_line_id'],
            'name' => $data['name'],
            'billing_frequency' => $data['billing_frequency'],
            'base_price' => $data['base_price'],
            'currency' => $data['currency'] ?? 'CAD',
        ]);

        return (int) $this->db->lastInsertId();
    }

    public function updatePlan(int $id, array $data): bool
    {
        $stmt = $this->db->prepare(
            'UPDATE service_plans SET business_line_id = :bl, name = :name, billing_frequency = :freq,
             base_price = :price, updated_at = NOW() WHERE id = :id'
        );

        return $stmt->execute([
            'bl' => $data['business_line_id'], 'name' => $data['name'], 'freq' => $data['billing_frequency'],
            'price' => $data['base_price'], 'id' => $id,
        ]);
    }

    public function deletePlan(int $id): bool
    {
        return $this->db->prepare('UPDATE service_plans SET is_active = 0 WHERE id = :id')->execute(['id' => $id]);
    }
}
