<?php

namespace Romanah\Gokbakja\Components;

use Cms\Classes\ComponentBase;
use Romanah\Gokbakja\Models\Product as ProductModel;
use Romanah\Gokbakja\Models\Production as ProductionModel;
use Romanah\Gokbakja\Models\PivotProduction as PivotProductionModel;
use Redirect;
use Flash;

class Production extends ComponentBase
{


    public function componentDetails()
    {
        return [
            'name'        => 'Production',
            'description' => 'productions settings'
        ];
    }


    public function onCreateProduction()
    {
        $user = \Auth::user();

        $data = post();

        $createProduction = new ProductionModel();

        $createProduction->all_amount = $data["all_amount"];
        $createProduction->note = $data["note"];
        $createProduction->user_id = $user->id;
        $createProduction->save();

        $products = ProductModel::where("report", "simple")->get();

        for ($x = 0; $x < count($products); $x++) {
            $fieldName = "product_".$products[$x]->code;

            $createPivotProduction = new PivotProductionModel();
            $createPivotProduction->production_id = $createProduction->id;
            $createPivotProduction->product_id = $products[$x]->id;
            $createPivotProduction->amount_percentage = $data[$fieldName];
            $createPivotProduction->product_name = $products[$x]->name;
            $createPivotProduction->product_code = $products[$x]->code;
            $createPivotProduction->amount = ($data[$fieldName] / 100) * ($createProduction->all_amount);
            $createPivotProduction->save();
        }

        if ($createProduction && $createPivotProduction) {
            Flash::success("Hasabat Ustunlikli Goşuldy");
            return Redirect::refresh();
        }

    }

    public function onUpdateProduction()
    {
        $user = \Auth::user();
        $data = post();

        $updateResult = ActionModel::where('id', $data["id"])
            ->update(array(
                'product_id' => $data["product_id"],
                'amount' => $data["quantity"],
                'stock_id' => $data["stock_id"],
                'note' => $data["note"],
                'transport_no' => $data["transport_no"],
                'driver' => $data["driver"],
                'user_id' => $user->id,
            ));
        // $createResult = DollorModel::create([]);

        // dd($data);
        if ($updateResult) {
            Flash::success("Action Ustunlikli Uytgedildi");
            return Redirect::refresh();
        }
    }


    public function onGetProduction()
    {
        $id = post('id');
        return ActionModel::where('id', $id)->first();
    }

    // public function onDeleteProduction()
    // {
    //     $id = post('id');

    //     $item = ActionModel::Find($id);
    //     $item->delete();

    //     if ($item) {
    //         Flash::success("Action Ustunlikli Pozuldy");
    //         return Redirect::refresh();
    //     }
    // }


}
