<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Market;
use Illuminate\Http\Request;

class MarketController extends Controller
{
    public function index()
    {
        $markets = Market::latest()->get();

        return view('admin.markets.index', compact('markets'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'symbol' => ['required', 'string', 'max:20', 'unique:markets,symbol'],
            'price' => ['required', 'numeric', 'min:0'],
            'change_24h' => ['nullable', 'numeric'],
            'type' => ['required', 'in:crypto,commodity,metal,forex'],
            'volatility' => ['nullable', 'numeric', 'min:0'],
            'tv_symbol' => ['nullable', 'string', 'max:64'],
        ]);

        Market::create($data);

        return back()->with('success', 'Market added.');
    }

    public function update(Request $request, Market $market)
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'symbol' => ['required', 'string', 'max:20', 'unique:markets,symbol,'.$market->id],
            'price' => ['required', 'numeric', 'min:0'],
            'change_24h' => ['nullable', 'numeric'],
            'type' => ['required', 'in:crypto,commodity,metal,forex'],
            'volatility' => ['nullable', 'numeric', 'min:0'],
            'tv_symbol' => ['nullable', 'string', 'max:64'],
        ]);

        $market->update($data);

        return back()->with('success', 'Market updated.');
    }

    public function destroy(Market $market)
    {
        $market->delete();

        return back()->with('success', 'Market deleted.');
    }

    public function applyWave(Request $request)
    {
        $data = $request->validate([
            'market_id' => ['required', 'exists:markets,id'],
            'direction' => ['required', 'in:up,down'],
            'percent' => ['required', 'numeric', 'min:0.01', 'max:100'],
        ]);

        $market = Market::findOrFail($data['market_id']);
        $multiplier = 1 + ($data['direction'] === 'up' ? 1 : -1) * ($data['percent'] / 100);
        $market->price = round((float) $market->price * $multiplier, 8);
        $market->change_24h = $data['direction'] === 'up' ? abs($data['percent']) : -abs($data['percent']);
        $market->save();

        return back()->with('success', 'Price wave applied to '.$market->symbol.'.');
    }
}
