<?php

namespace App\Http\Controllers;

use App\Http\Requests\Order\StoreOrderRequest;
use App\Jobs\GenerateInstallationPack;
use App\Models\Dictionary\Area;
use App\Models\Dictionary\District;
use App\Models\File;
use App\Models\MafOrder;
use App\Models\ObjectType;
use App\Models\Order;
use App\Models\OrderStatus;
use App\Models\ProductSKU;
use App\Models\Role;
use App\Models\User;
use App\Services\FileService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class OrderController extends Controller
{
    protected array $data = [
        'active'    => 'orders',
        'title'     => 'Заказы',
        'id'        => 'orders',
        'header'    => [
            'id'                        => 'ID',
            'name'                      => 'Название',
            'user_id'                   => 'Менеджер',
            'district_id'               => 'Округ',
            'area_id'                   => 'Район',
            'object_address'            => 'Адрес объекта',
            'object_type_id'            => 'Тип объекта',
            'comment'                   => 'Комментарий',
            'installation_date'         => 'Дата выхода на монтаж',
            'ready_date'                => 'Дата готовности площадки',
            'brigadier_id'              => 'Бригадир',
            'order_status_id'           => 'Статус',
            'tg_group_name'             => 'Имя группы в ТГ',
            'tg_group_link'             => 'Ссылка на группу в ТГ',
            'products_with_count'       => 'МАФы',
            'ready_to_mount'            => 'Все МАФы на складе',
        ],
        'searchFields' => [
            'name',
            'comment',
            'object_address',
            'tg_group_name',
            'tg_group_link',
        ],
    ];

    public function __construct()
    {
        $this->data['districts'] = District::query()->get()->pluck('name', 'id');
        $this->data['areas'] = Area::query()->get()->pluck('name', 'id');
        $this->data['objectTypes'] = ObjectType::query()->get()->pluck('name', 'id');
        $this->data['orderStatuses'] =OrderStatus::query()->get()->pluck('name', 'id');
        $this->data['brigadiers'] = User::query()->where('role', Role::BRIGADIER)->get()->pluck('name', 'id');
        $this->data['users'] = User::query()->whereIn('role', [Role::MANAGER, Role::ADMIN])->get()->pluck('name', 'id');
    }


    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $model = new Order;
        // fill filters
        $this->createFilters($model, 'user_id', 'district_id', 'area_id', 'object_type_id', 'brigadier_id', 'order_status_id', 'ready_to_mount');
        $this->createDateFilters($model, 'installation_date', 'ready_date');
        $this->data['ranges'] = [];

        $q = $model::query();

        $this->acceptFilters($q, $request);
        $this->acceptSearch($q, $request);
        $this->setSortAndOrderBy($model, $request);

        $q->orderBy($this->data['sortBy'], $this->data['orderBy']);
        $this->data['orders'] = $q->paginate(session('per_page', config('pagination.per_page')))->withQueryString();

        foreach ($this->data['orders'] as $order) {
            $order->recalculateReadyToMount();
        }

        return view('orders.index', $this->data);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('orders.edit', $this->data);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreOrderRequest $request)
    {
        $data = $request->validated();

        $products = $request->validated('products');
        $quantities = $request->validated('quantity');

        unset($data['products']);

        if(isset($data['id'])) {
            $order = Order::query()->where('id', $data['id'])->first();
            $order->update($data);
            $order->refresh();
        } else {
            $data['order_status_id'] = Order::STATUS_NEW;
            $order = Order::query()->create($data);
        }

        // меняем список товаров заказа только если статус новый
        if($products && $quantities && ($order->order_status_id == 1)) {
            // remove from products_sku
            ProductSKU::query()->where('order_id', $order->id)->delete();
            foreach ($products as $key => $product) {
                for($i = 0; $i < $quantities[$key]; $i++) {
                    ProductSKU::query()->create([
                        'order_id' => $order->id,
                        'product_id' => $product,
                        'status' => 'требуется'
                    ]);
                }
            }
        }

        $order->refresh();
        $order->autoChangeStatus();

        return redirect()->route('order.show', $order);
    }

    /**
     * Display the specified resource.
     */
    public function show(Order $order)
    {
        $this->data['order'] = $order;
        return view('orders.show', $this->data);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Order $order)
    {
        $this->data['order'] = $order;
        return view('orders.edit', $this->data);
    }

    /**
     * Привязка товаров к заказу
     * @param Order $order
     * @return RedirectResponse
     */
    public function getMafToOrder(Order $order)
    {
        foreach ($order->products_sku as $product_sku) {
            // dont connect maf to order if already connected
            if($product_sku->maf_order) {
                continue;
            }

            $mafOrder = MafOrder::query()
                ->where('product_id', $product_sku->product_id)
                ->where('in_stock', '>' , 0)
                ->orderBy('created_at')
                ->first();
            $product_sku->update(['maf_order_id' => $mafOrder->id, 'status' => 'отгружен']);
            $mafOrder->decrement('in_stock');
            unset($mafOrder, $product_sku);
        }
        $order->autoChangeStatus();
        return redirect()->route('order.show', $order);
    }

    /**
     * @param Order $order
     * @return RedirectResponse
     */
    public function destroy(Order $order)
    {
        Order::query()->where('id', $order->id)->delete();
        ProductSKU::query()->where('order_id', $order->id)->delete();
        return redirect()->route('order.index');
    }

    public function revertMaf(Order $order)
    {
        foreach ($order->products_sku as $maf) {
            MafOrder::query()->where('id', $maf->maf_order_id)->increment('in_stock');
            $maf->update(['maf_order_id' => null, 'status' => 'требуется']);
        }

        return redirect()->route('order.show', $order);
    }

    public function moveMaf(Request $request)
    {
        $data = $request->validate([
            'new_order_id' => 'required',
            'ids' => 'required|json',
        ]);

        $ids = json_decode($data['ids'], true);
        $updated = [];
        foreach ($ids as $mafId) {
            $maf = ProductSKU::query()
                ->where('id', $mafId)
                ->first();
            if($maf) {
                $comment = $maf->comment . "\n" . date('Y-m-d H:i') . ' Перенесено с площадки: ' . $maf->order->common_name;
                $maf->update(['order_id' => $data['new_order_id'], 'comment' => $comment]);
                $updated[] = $maf;
            }
        }
        return response()->json(['success' => true]);
    }

    public function search(Request $request): array
    {
        $ret = [];
        $s = $request->get('s');
        $searchFields = $this->data['searchFields'];
        $result = Order::query();
        if($s) {
            $result->where(function ($query) use ($searchFields, $s) {
                foreach ($searchFields as $searchField) {
                    $query->orWhere($searchField, 'LIKE', '%' . $s . '%');
                }
            });
        }

        $result->orderBy('object_address');
        foreach ($result->get() as $p) {
            $ret[$p->id] = $p->common_name;
        }
        return $ret;
    }

    public function uploadPhoto(Request $request, Order $order, FileService $fileService)
    {
        $data = $request->validate([
            'photo.*' => 'mimes:jpeg,jpg,png|max:8192',
        ]);
        $f = [];
        foreach ($data['photo'] as $photo) {
            $f[] = $fileService->saveUploadedFile( 'orders/' . $order->id . '/photo', $photo);
        }
        $order->photos()->syncWithoutDetaching($f);

        return redirect()->route('order.show', $order);
    }

    public function deletePhoto(Order $order, File $file, FileService $fileService)
    {
        $order->photos()->detach($file);
        Storage::disk('public')->delete($file->path);
        $file->delete();
        return redirect()->route('order.show', $order);
    }

    public function uploadDocument(Request $request, Order $order, FileService $fileService)
    {
        $data = $request->validate([
            'document.*' => 'file',
        ]);
        $f = [];
        foreach ($data['document'] as $document) {
            $f[] = $fileService->saveUploadedFile( 'orders/' . $order->id . '/document', $document);
        }
        $order->documents()->syncWithoutDetaching($f);

        return redirect()->route('order.show', $order);
    }

    public function deleteDocument(Order $order, File $file)
    {
        $order->documents()->detach($file);
        Storage::disk('public')->delete($file->path);
        $file->delete();
        return redirect()->route('order.show', $order);
    }

    public function uploadStatement(Request $request, Order $order, FileService $fileService)
    {
        $data = $request->validate([
            'statement.*' => 'file',
        ]);
        $f = [];
        foreach ($data['statement'] as $statement) {
            $f[] = $fileService->saveUploadedFile( 'orders/' . $order->id . '/statement', $statement);
        }
        $order->statements()->syncWithoutDetaching($f);

        return redirect()->route('order.show', $order);
    }

    public function deleteStatement(Order $order, File $file)
    {
        $order->statements()->detach($file);
        Storage::disk('public')->delete($file->path);
        $file->delete();
        return redirect()->route('order.show', $order);
    }

    public function generateInstallationPack(Order $order)
    {
        GenerateInstallationPack::dispatch($order);
        return redirect()->route('order.show', $order)->with(['success' => 'Задача генерации документов создана!']);
    }

}
