<?php

namespace App\Models;

class BarberStore
{
    private string $filePath;

    public function __construct(?string $filePath = null)
    {
        $this->filePath = $filePath ?? WRITEPATH . 'barber-data.json';
    }

    public function loadData(): array
    {
        if (!file_exists($this->filePath)) {
            return ['services' => $this->defaultServices(), 'transactions' => []];
        }

        $json = file_get_contents($this->filePath);
        $data = json_decode($json, true);

        return is_array($data) ? $data : ['services' => $this->defaultServices(), 'transactions' => []];
    }

    public function saveServices(array $services): void
    {
        $data = $this->loadData();
        $data['services'] = $services;
        $this->write($data);
    }

    public function addTransaction(array $transaction): void
    {
        $data = $this->loadData();
        $data['transactions'][] = $transaction;
        $this->write($data);
    }

    private function write(array $data): void
    {
        $dir = dirname($this->filePath);
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }

        file_put_contents($this->filePath, json_encode($data, JSON_PRETTY_PRINT));
    }

    private function defaultServices(): array
    {
        return [
            ['id' => 'cut', 'name' => 'Potong Rambut', 'price' => 60000],
            ['id' => 'beard', 'name' => 'Cukur Jenggot', 'price' => 35000],
            ['id' => 'wash', 'name' => 'Hair Wash', 'price' => 25000],
            ['id' => 'color', 'name' => 'Coloring', 'price' => 150000],
            ['id' => 'cream', 'name' => 'Cream Bath', 'price' => 40000],
        ];
    }
}
