<?php

namespace Server\Controllers;

use Server\Library\Controllers\ApiController;
use Server\Database\Models\Trader;

class TradersController extends ApiController
{

    public function __construct()
    {
        parent::__construct();
        $this->model = new Trader;
        $this->searchBy = "name";
    }

    public function createRules($body)
    {
        $name = $body['name'] ?? '';
        // $email = $body['email'] ?? '';
        // $description = $body['description'] ?? '';

        return [
            'name' => [$name, 'required'],
            // 'email' => [$email, 'required|email'],
            // 'description' => [$description, 'required'],
        ];
    }

    public function createBody($body)
    {
        return $this->filter($body, ['name', 'email', 'description', 'win_rate', 'profit_share','type','price']);
    }

    public function updatePhoto($request, $response)
    {
        $id = $request->getAttribute('attr');
        $photo = $_FILES['photo']['name'] ?? '';

        $rules = [
            'trader id' => [$id, 'required'],
            'photo' => [$photo, 'required|imageformat'],
        ];

        $this->validator->validate($rules);

        $errors = $this->validator->errors()->all();

        if ($errors) {
            $this->data['errors'] = $errors;
            $response->getBody()->write(json_encode($this->data));
            return $response->withHeader('Content-Type', 'application/json');
        }

        $image_name = time() . $photo;
        $trader = $this->model->where('id', $id)->first();

        if (!$trader) {
            $this->data['errors'] = ['trader not found'];
            $response->getBody()->write(json_encode($this->data));
            return $response->withHeader('Content-Type', 'application/json');
        }

        try {
            $uploaded = move_uploaded_file($_FILES['photo']['tmp_name'], IMAGE_DIR . $image_name);
            if ($uploaded) {
                $trader->update(['photo' => $image_name]);
                $this->data['message'] = "photo updated";
                $response->getBody()->write(json_encode($this->data));
                return $response->withHeader('Content-Type', 'application/json');
            }
            return $response->withJson(['errors' => ['update failed']]);
        } catch (\Exception $e) {
            $errors = [$e->getMessage()];
            $this->data['errors'] = $errors;
            $response->getBody()->write(json_encode($this->data));
            return $response->withHeader('Content-Type', 'application/json');
        }

        return $response->withHeader('Content-Type', 'application/json');
    }
}