<?php

namespace Server\Controllers;

use Carbon\Carbon;
use Server\Database\Models\Trade;
use Server\Library\Services\Sender;
use Server\Library\Services\Renderer;
use Server\Controllers\Filters\TradesFilter;
use Server\Library\Controllers\SolidController;
use Server\Controllers\Validators\TradesValidator;

class TradesController extends SolidController
{

    public function __construct()
    {
        $this->model = new Trade;
        $this->sender = new Sender;
        $this->renderer = new Renderer;
        $this->filter = new TradesFilter;
        $this->validator = new TradesValidator(new Trade);
    } 

    public function sample($request, $response)
    {
        
        $trades =  $this->model->where('user_id', 1)->where('created_at', '>=', Carbon::now()->startOfDay())->get();

        $trades = json_decode(json_encode($trades), true);

        $data = $this->renderer->render('trades.html', ['trades' => $trades]);

        $response->getBody()->write($data);

        return $response;
    }

    public function summary($request, $response)
    {
        $body = $request->getParsedBody();

        $email = $body['email'] ?? '';
        $user_id = $body['user_id'] ?? '';

        $rules = ['user id' => [$user_id, 'required']];

        $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');
        }

        $trades =  $this->model->where('user_id', $user_id)->where('created_at', '>=', Carbon::now()->startOfDay())->get();

        $trades = json_decode(json_encode($trades), true);

        $data = $this->renderer->render('trades.html', ['trades' => $trades]);

        $sent = $this->sender->sendEmail([$email], $data, "Trade Summary");

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

        $this->data['message'] = "Summary Sent";
        $response->getBody()->write(json_encode($this->data));
        return $response->withHeader('Content-Type', 'application/json');
    }



}