<?php

class BudgetUploadController extends BaseController
{

    /**
     * Constructor
     */
    public function __construct()
    {
        // Establish Filters
        $this->beforeFilter('auth');
        $this->beforeFilter('csrf', array('only' => array('createOperation')));
        $this->beforeFilter('hasRole:' . Role::ROLE_BUDGET_ACCOUNTANT);

        if (Auth::check()) {
            $this->user = Auth::user();
            $this->projects = $this->user->budgetProjects;
        }
        $this->projectPrefix = 'budget';
        parent::__construct();
    }

    public function index()
    {
        $input = Input::all();

        if ($this->user->budgetProjects()->first() == null) {
            return Redirect::to('/');
        }
        if (Input::has('projectId')) {
            Session::put('work_projectId', $input['projectId']);
            return Redirect::to('budget/upload');
        }

        return $this->setupLayout('budget.upload.index')
            ->with('user', $this->user)
            ->with('budgetUploads', $this->workProject->budgetUploads()->withTrashed()->orderBy('created_at', 'DESC')->take(25)->get())
            ->with('workProject', $this->workProject);
    }

    public function delete()
    {
        $input = Input::all();

        if (!isset($input['uploadId'])) {
            $response = array('status' => 'fail');
            return Response::json($response);
        }

        $budgetUpload = BudgetUpload::find($input['uploadId']);
        if ($budgetUpload == null || !is_numeric($input['uploadId'])) {
            $response = array('status' => 'fail', 'message' => 'Загрузка не найдена');
            return Response::json($response);
        }

        $budgetCostsRequests = BudgetCostsRequests::whereBudgetUploadId($budgetUpload->id)
            ->get();
        if ($budgetCostsRequests) {
            foreach ($budgetCostsRequests as $budgetCostsRequest) {
                $budgetCostsRequest->status = BudgetCostsRequests::STATUS_APPROVED;
                $budgetCostsRequest->accountant_comment = null;
                $budgetCostsRequest->paid_at = null;
                $budgetCostsRequest->budget_upload_id = 0;
                $budgetCostsRequest->save();
            }
        }

        $budgetUpload->operations()->delete();
        $budgetUpload->delete();

        $response = array(
            'status' => 'success',
            'message' => 'Загрузка успешно отменена',
            'history' => $this->setupLayout('budget.upload.uploads')->with('budgetUploads', BudgetUpload::withTrashed()->whereProjectId($this->workProject->id)->orderBy('created_at', 'DESC')->take(10)->get())->render(),
        );
        return Response::json($response);
    }

    public function restore()
    {
        $input = Input::all();

        if (!isset($input['uploadId'])) {
            $response = array('status' => 'fail');
            return Response::json($response);
        }

//		$budgetUpload = BudgetUpload::withTrashed()->whereProjectId($this->workProject->id)->find($input['uploadId']);
//		if ($budgetUpload == null || !is_numeric($input['uploadId'])) {
//			$response = array('status' => 'fail', 'message' => 'Загрузка не найдена');
//			return Response::json($response);
//		}
//
//		$budgetUpload->restore();
//		$budgetUpload->operations()->restore();
//		$path								 = public_path() . '/budgetfiles/' . $this->workProject->id . '/';
//		$response						 = $this->loadBudgetFile($path, $budgetUpload->filename, $budgetUpload->id);
//		if ($response['status'] == 'success') {
//			$response['history'] = $this->setupLayout('budget.upload.uploads')->with('budgetUploads', BudgetUpload::withTrashed()->whereProjectId($this->workProject->id)->orderBy('created_at', 'DESC')->take(10)->get())->render();
//		}
//		else {
//			$budgetUpload->delete();
//		}

        $response = array(
            'status' => 'success',
            'message' => 'Загрузка успешно восстановлена',
            'history' => $this->setupLayout('budget.upload.uploads')->with('budgetUploads', BudgetUpload::withTrashed()->whereProjectId($this->workProject->id)->orderBy('created_at', 'DESC')->take(10)->get())->render(),
        );
        return Response::json($response);
    }

    public function uploadFile()
    {
        if (!$this->workProject) {
            $response = array(
                'status' => 'fail',
                'message' => 'Проект не найден'
            );
            return Response::json($response);
        }

        $valid_exts = array('txt');
        $max_size = 5 * 1024 * 1024;
        $path = public_path() . '/budgetfiles/' . $this->workProject->id . '/';
        $file = Input::file('file');
        $ext = ($file->getClientOriginalExtension()) ? $file->getClientOriginalExtension() : 'txt';
        $size = $file->getClientSize();
        $name = date("YmdHis") . "." . $ext;

        if (in_array($ext, $valid_exts) && $size < $max_size) {
            if ($file->move($path, $name)) {
                $response = $this->loadBudgetFile($path, $name);
                $response['history'] = $this->setupLayout('budget.upload.uploads')->with('budgetUploads', BudgetUpload::withTrashed()->whereProjectId($this->workProject->id)->orderBy('created_at', 'DESC')->take(10)->get())->render();
                return Response::json($response);
            }
        }

        $response = array(
            'status' => 'fail',
            'message' => 'Некорректный файл'
        );
        return Response::json($response);
    }

    protected function loadBudgetFile($path, $name, $budgetUploadId = null)
    {
        $contents = iconv('CP1251', 'UTF-8', File::get($path . $name));

        $matches = array();
        $reg = "#СекцияРасчСчет(.*?)РасчСчет=(\d+)(\r?\n)(.*?)КонецРасчСчет#is";
        preg_match_all($reg, $contents, $matches);
        if (!$matches[2][0]) {
            $response = array('status' => 'fail', 'message' => 'Расчетный счет не найден');
            return $response;
        }
        $workBudgetAccount = BudgetAccount::whereProjectId($this->workProject->id)->whereCurrentAccount($matches[2][0])->whereNoupload(0)->first();
        if (!$workBudgetAccount) {
            $response = array('status' => 'fail', 'message' => 'Расчетный счет не относится к проекту');
            return $response;
        }

        $reg = "#НачальныйОстаток=(.*?)(\r?\n)КонечныйОстаток=(.*?)(\r?\n)#is";
        preg_match_all($reg, $contents, $matches);
        $accountStartAmount = $matches[1][0];
        $budgetAccountStartAmount = $workBudgetAccount->getSum();
        $accountEndAmount = $matches[3][0];
        $operationsAddCount = 0;
        $operationsProcessCount = 0;
        $operationsErrorsLog = '';
        $notWrittenOffOperation = ''; // расходные операции без ДатаСписано=

//		if ($accountStartAmount != $workBudgetAccount->getSum()) {
//			$response = array('status' => 'fail', 'message' => 'Сумма в бюджете не совпадает с начальной суммой на Р/С в выгрузке.<br/>В выгрузке ' . $accountStartAmount . 'р.<br/>В бюджете ' . $workBudgetAccount->getSum() . 'р.');
//			return $response;
//		}

        $budgetUpload = false;
        $fileType = 1;

//        $reg = "#СекцияДокумент(.*?)Номер=(.*?)(\r?\n)(.*?)Сумма=(.*?)(\r?\n)(.*?)(ДатаСписано=(.*?)(\r?\n)(.*?))*Плательщик1=(.*?)(\r?\n)(.*?)ПлательщикРасчСчет=(.*?)(\r?\n)(.*?)Получатель1=(.*?)(\r?\n)(.*?)ПолучательРасчСчет=(.*?)(\r?\n)(.*?)НазначениеПлатежа=(.*?)(\r?\n)(.*?)КонецДокумента#is";
        $reg = "#СекцияДокумент(.*?)КонецДокумента#is";
        preg_match_all($reg, $contents, $matches);
//        print_r($matches);die();
//        if (!$matches[1] || !is_array($matches[1])) {
//            $fileType = 2;
//            $reg = "#СекцияДокумент(.*?)Номер=(.*?)(\r?\n)(.*?)Сумма=(.*?)(\r?\n)(.*?)(ДатаСписано=(.*?)(\r?\n)(.*?))*ПлательщикРасчСчет=(.*?)(\r?\n)(.*?)ПолучательРасчСчет=(.*?)(\r?\n)(.*?)НазначениеПлатежа=(.*?)(\r?\n)(.*?)Плательщик1=(.*?)(\r?\n)(.*?)Получатель1=(.*?)(\r?\n)(.*?)КонецДокумента#is";
//            preg_match_all($reg, $contents, $matches);
//        }
        if ($matches[1] && is_array($matches[1])) {
            if ($budgetUploadId) {
                $budgetUpload = BudgetUpload::find($budgetUploadId);
                if (!$budgetUpload) {
                    $response = array('status' => 'fail', 'message' => 'Загрузка не найдена');
                    return $response;
                }
            } else {
                $budgetUpload = BudgetUpload::create(array(
                    'date' => DB::raw('DATE(NOW())'),
                    'filename' => $name
                ));
                $budgetUpload->user()->associate($this->user);
                $budgetUpload->project()->associate($this->workProject);
                $budgetUpload->budgetAccount()->associate($workBudgetAccount);
                $budgetUpload->save();
            }
            //--> Для заявок на расход
            /*$matchesCR = array();
            $regCR = "#СекцияДокумент(.*?)Номер=(.*?)(\r?\n)(.*?)Сумма=(.*?)(\r?\n)(.*?)(ДатаСписано=(.*?)(\r?\n)(.*?))*ПолучательРасчСчет=(.*?)(\r?\n)(.*?)leadstat\#(\d{1,})(.*?)КонецДокумента#is";

            preg_match_all($regCR, $contents, $matchesCR);

            foreach ($matchesCR[1] as $key => $value) {
                $orderNumber             = $matchesCR[2][$key];
                $orderAmount             = $matchesCR[5][$key];
                $orderDate               = $matchesCR[9][$key];
                $currentAccountRecipient = $matchesCR[12][$key];
                $requestId               = $matchesCR[15][$key];

                $costsRequest = BudgetCostsRequests::find($requestId);
                $budgetAccountRecipient	 = BudgetAccount::whereProjectId($this->workProject->id)->whereCurrentAccount($currentAccountRecipient)->first();

                if( $costsRequest || !$budgetAccountRecipient ){
                    if( ($costsRequest->status == BudgetCostsRequests::STATUS_APPROVED) && ($costsRequest->requested_amount/100 == $orderAmount) ){
                        $costsRequest->status               = BudgetCostsRequests::STATUS_PAID;
                        $costsRequest->accountant_id        = $this->user->id;
                        $costsRequest->payment_order_number = $orderNumber;
                      $costsRequest->paid_at              = $costsRequest->getDbDate($orderDate);
                        $costsRequest->budget_upload_id     = $budgetUpload->id;
                        $costsRequest->save();
                    }
                    else if( ($costsRequest->requested_amount != $orderAmount) || ($costsRequest->status != BudgetCostsRequests::STATUS_APPROVED) || ($this->workProject->id == $costsRequest->id) ){
                        $costsRequest->accountant_id      = $this->user->id;
                        $costsRequest->accountant_comment = 'Ошибка оплаты. Необходима проверка и проставление отметки об оплате вручную при не обходимости. П/п №'
                                                                    .$orderNumber.', сумма - '.$orderAmount.', дата - '.$orderDate.', id выгрузки - '.$budgetUpload;
                        $costsRequest->save();
                    }
                }
            }*/

            //<--

            foreach ($matches[1] as $key => $value) {
                $operationsProcessCount++;
                $operationAdded = false;

                $number = false;
                $amount = false;
                $dateOut = false;
                $namePayer = false; // Плательщик1=
                $currentAccountPayer = false;
                $dateIn = false;
                $nameRecipient = false;
                $currentAccountRecipient = false;
                $comment = false;

//        $reg = "#СекцияДокумент(.*?)Номер=(.*?)(\r?\n)(.*?)Сумма=(.*?)(\r?\n)(.*?)(ДатаСписано=(.*?)(\r?\n)(.*?))*Плательщик1=(.*?)(\r?\n)(.*?)ПлательщикРасчСчет=(.*?)(\r?\n)(.*?)Получатель1=(.*?)(\r?\n)(.*?)ПолучательРасчСчет=(.*?)(\r?\n)(.*?)НазначениеПлатежа=(.*?)(\r?\n)(.*?)КонецДокумента#is";

                $reg2 = "#Номер=(.*?)(\r?\n)#is";
                preg_match_all($reg2, $value, $matches2);
                if ($matches2 && isset($matches2[1][0]) && $matches2[1][0] != '') {
                    $number = $matches2[1][0];
                }
                $reg2 = "#Сумма=(.*?)(\r?\n)#is";
                preg_match_all($reg2, $value, $matches2);
                if ($matches2 && isset($matches2[1][0]) && $matches2[1][0] != '') {
                    $amount = $matches2[1][0];
                }
                $reg2 = "#ДатаСписано=(.*?)(\r?\n)#is";
                preg_match_all($reg2, $value, $matches2);
                if ($matches2 && isset($matches2[1][0]) && $matches2[1][0] != '') {
                    $dateOut = $matches2[1][0];
                    $dateOut = explode('.', $dateOut);
                    $dateOut = "{$dateOut[2]}-{$dateOut[1]}-{$dateOut[0]}";
                }
                $reg2 = "#(Плательщик|Плательщик1)=(.*?)(\r?\n)#is";
                preg_match_all($reg2, $value, $matches2);
                if ($matches2 && isset($matches2[1][0]) && $matches2[1][0] != '') {
                    $namePayer = $matches2[1][0];
                }
                $reg2 = "#ПлательщикРасчСчет=(.*?)(\r?\n)#is";
                preg_match_all($reg2, $value, $matches2);
                if ($matches2 && isset($matches2[1][0]) && $matches2[1][0] != '') {
                    $currentAccountPayer = $matches2[1][0];
                }
                $reg2 = "#(Получатель|Получатель1)=(.*?)(\r?\n)#is";
                preg_match_all($reg2, $value, $matches2);
                if ($matches2 && isset($matches2[1][0]) && $matches2[1][0] != '') {
                    $nameRecipient = $matches2[1][0];
                }
                $reg2 = "#ПолучательРасчСчет=(.*?)(\r?\n)#is";
                preg_match_all($reg2, $value, $matches2);
                if ($matches2 && isset($matches2[1][0]) && $matches2[1][0] != '') {
                    $currentAccountRecipient = $matches2[1][0];
                }
                $reg2 = "#НазначениеПлатежа=(.*?)(\r?\n)#is";
                preg_match_all($reg2, $value, $matches2);
                if ($matches2 && isset($matches2[1][0]) && $matches2[1][0] != '') {
                    $comment = $matches2[1][0];
                }
                $reg2 = "#ДатаПоступило=(.*?)(\r?\n)#is";
                preg_match_all($reg2, $value, $matches2);
                if ($matches2 && isset($matches2[1][0]) && $matches2[1][0] != '') {
                    $dateIn = explode('.', $matches2[1][0]);
                    $dateIn = "{$dateIn[2]}-{$dateIn[1]}-{$dateIn[0]}";
                } else {
                    $dateIn = '';
                }
//                $number = $matches[2][$key];
//                $amount = $matches[5][$key];
//                $dateOut = $matches[9][$key];
//                $namePayer = $matches[12][$key]; // Плательщик1=
//                $currentAccountPayer = $matches[15][$key];
//                $dateIn = $matches[17][$key];
//                $nameRecipient = $matches[18][$key];
//                $currentAccountRecipient = $matches[21][$key];
//                $comment = $matches[24][$key];
//                if ($fileType == 2) {
//                    $namePayer = $matches[21][$key]; // Плательщик1=
//                    $currentAccountPayer = $matches[12][$key];
//                    $dateIn = $matches[7][$key];
//                    $nameRecipient = $matches[24][$key];
//                    $currentAccountRecipient = $matches[15][$key];
//                    $comment = $matches[18][$key];
//                }
//                if ($dateOut) {
//                    $dateOut = explode('.', $dateOut);
//                    $dateOut = "{$dateOut[2]}-{$dateOut[1]}-{$dateOut[0]}";
//                }
//                if ($dateIn) {
//                    $reg2 = "#ДатаПоступило=(.*?)(\r?\n)#is";
//                    preg_match_all($reg2, $dateIn, $matches2);
//                    if ($matches2 && isset($matches2[1][0]) && $matches2[1][0] != '') {
//                        $dateIn = explode('.', $matches2[1][0]);
//                        $dateIn = "{$dateIn[2]}-{$dateIn[1]}-{$dateIn[0]}";
//                    } else {
//                        $dateIn = '';
//                    }
//                }

                if ($namePayer) {
                    $namePayer = mb_strtolower($namePayer);
                    $matchesAcc = array();
                    $regAcc1 = "#р/с(\s*)(\d{1,})(.*?)#is";
                    preg_match_all($regAcc1, $namePayer, $matchesAcc);

                    if ($matchesAcc && isset($matchesAcc[2][0]) && $matchesAcc[2][0] != '') {
                        $currentAccountPayer = $matchesAcc[2][0];
                    } else if (!$currentAccountPayer) {
                        $regAcc2 = "#р/с(\s*)'(.*)'#is";
                        preg_match_all($regAcc2, $namePayer, $matchesAcc);

                        if ($matchesAcc && isset($matchesAcc[2][0]) && $matchesAcc[2][0] != '') {
                            $currentAccountPayer = $matchesAcc[2][0];
                        }
                    } else {
                        $regAcc3 = "#сч.N(\s*)(\d{1,})(.*?)#is";
                        preg_match_all($regAcc3, $namePayer, $matchesAcc);

                        if ($matchesAcc && isset($matchesAcc[2][0]) && $matchesAcc[2][0] != '') {
                            $currentAccountPayer = $matchesAcc[2][0];
                        }
                    }
                }

                $budgetAccountPayer = BudgetAccount::whereProjectId($this->workProject->id)->whereCurrentAccount($currentAccountPayer)->first();
                $budgetAccountRecipient = BudgetAccount::whereProjectId($this->workProject->id)->whereCurrentAccount($currentAccountRecipient)->first();

                $reg = "/З(.*?)плата сотрудникам/";
                //если это МДМ Молчановой и Перечисление за ЗП то делаем расход
                if ($currentAccountRecipient == '40817810238000001702' && preg_match($reg, $comment)) {
                    $budgetPartnerRecipient = BudgetPartner::whereProjectId($this->workProject->id)->whereCurrentAccount($currentAccountRecipient)->first();
                    if (!$budgetPartnerRecipient) {
                        $budgetPartnerRecipient = BudgetPartner::create(array(
                            'name' => $nameRecipient,
                            'current_account' => e($currentAccountRecipient)
                        ));
                        $budgetPartnerRecipient->project()->associate($this->workProject);
                        $budgetPartnerRecipient->save();
                    }
                    $budget_cost_id = 0;
                    if ($budgetPartnerRecipient->cost) {
                        $budget_cost_id = $budgetPartnerRecipient->cost->id;
                    }
                    if (!$budget_cost_id) {
                        foreach (BudgetCost::whereProjectId($this->workProject->id)->get() as $cost) {
                            foreach (preg_split('(\r?\n)', $cost->template) as $reg) {
                                try {
                                    $reg = trim($reg);
                                    $reg = str_replace('\\', '\\\\', $reg);
                                    if (!$budget_cost_id && $reg && $reg != '' && (preg_match($reg, $comment) || preg_match($reg, $nameRecipient))) {
                                        $budget_cost_id = $cost->id;
                                        $budgetPartnerRecipient->cost()->associate($cost);
                                        $budgetPartnerRecipient->save();
                                    }
                                } catch (Exception $e) {

                                }
                            }
                        }
                    }
                    if ($dateOut) {
                        $budgetOperation = BudgetOperation::create(array(
                            'isuploaded' => 1,
                            'date' => $dateOut,
                            'bank_id' => $number,
                            'type' => BudgetOperation::TYPE_OUTCOMING,
                            'budget_cost_id' => $budget_cost_id,
                            'budget_partner_id' => $budgetPartnerRecipient->id,
                            'budget_in_account_id' => 0,
                            'budget_out_account_id' => $budgetAccountPayer->id,
                            'comment' => $comment,
                        ));
                        $budgetOperation->user()->associate($this->user);
                        $budgetOperation->project()->associate($this->workProject);
                        $budgetOperation->budgetUpload()->associate($budgetUpload);
                        $budgetOperation->amount = $amount;
                        $budgetOperation->save();
                        $operationsAddCount++;
                        $operationAdded = true;
                    } else {
                        $notWrittenOffOperation .= 'Операция №' . $number . ' на сумму ' . $amount . ' не может быть загружена, т.к еще нет подтверждения банка о ее проведении (ЗП МДМ). <br>';
                    }
                } //если р/с плательщика наш, а р/с получателя не наш, то это операция или расходная или выдачи денег в банке
                elseif ($budgetAccountPayer && !$budgetAccountRecipient) {
                    $budgetOperation = BudgetOperation::whereProjectId($this->workProject->id)->whereBankId($number)->whereAmount($amount * 100)->whereDate($dateOut)->first();
                    if (!$budgetOperation) {
                        //если это выдача наличных, то это перевод
                        $reg = "/Выдачи со счетов индивидуальных предпринимателей/";
                        if ($comment == 'Выдано по чеку' || $nameRecipient == 'Денежные средства в специализированной кассе' || preg_match($reg, $comment)) {
                            $budgetAccountRecipient = BudgetAccount::whereProjectId($this->workProject->id)->whereIscache(1)->first();
                            if ($budgetAccountRecipient) {
                                if ($dateOut) {
                                    $budgetOperation = BudgetOperation::create(array(
                                        'isuploaded' => 1,
                                        'date' => $dateOut,
                                        'bank_id' => $number,
                                        'type' => BudgetOperation::TYPE_EXCHANGE,
                                        'budget_cost_id' => 0,
                                        'budget_partner_id' => 0,
                                        'budget_in_account_id' => $budgetAccountRecipient->id,
                                        'budget_out_account_id' => $budgetAccountPayer->id,
                                        'comment' => $comment,
                                    ));
                                    $budgetOperation->user()->associate($this->user);
                                    $budgetOperation->project()->associate($this->workProject);
                                    $budgetOperation->budgetUpload()->associate($budgetUpload);
                                    $budgetOperation->amount = $amount;
                                    $budgetOperation->save();
                                    $operationsAddCount++;
                                    $operationAdded = true;
                                } else {
                                    $notWrittenOffOperation .= 'Операция №' . $number . ' на сумму ' . $amount . ' не может быть загружена, т.к еще нет подтверждения банка о ее проведении (Выдача наличных). <br>';
                                }
                            }
                        } //если это не перевод то расход
                        elseif (!$budgetAccountRecipient) {
                            $budgetPartnerRecipient = BudgetPartner::whereProjectId($this->workProject->id)->whereCurrentAccount($currentAccountRecipient)->first();
                            if (!$budgetPartnerRecipient) {
                                $budgetPartnerRecipient = BudgetPartner::create(array(
                                    'name' => $nameRecipient,
                                    'current_account' => e($currentAccountRecipient)
                                ));
                                $budgetPartnerRecipient->project()->associate($this->workProject);
                                $budgetPartnerRecipient->save();
                            }
                            $budget_cost_id = 0;
                            if ($budgetPartnerRecipient->cost) {
                                $budget_cost_id = $budgetPartnerRecipient->cost->id;
                            }
                            if (!$budget_cost_id) {
                                foreach (BudgetCost::whereProjectId($this->workProject->id)->get() as $cost) {
                                    foreach (preg_split('(\r?\n)', $cost->template) as $reg) {
                                        try {
                                            $reg = trim($reg);
                                            $reg = str_replace('\\', '\\\\', $reg);
                                            if (!$budget_cost_id && $reg && $reg != '' && (preg_match($reg, $comment) || preg_match($reg, $nameRecipient))) {
                                                $budget_cost_id = $cost->id;
                                                $budgetPartnerRecipient->cost()->associate($cost);
                                                $budgetPartnerRecipient->save();
                                            }
                                        } catch (Exception $e) {

                                        }
                                    }
                                }
                            }
                            if ($dateOut) {
                                $budgetOperation = BudgetOperation::create(array(
                                    'isuploaded' => 1,
                                    'date' => $dateOut,
                                    'bank_id' => $number,
                                    'type' => BudgetOperation::TYPE_OUTCOMING,
                                    'budget_cost_id' => $budget_cost_id,
                                    'budget_partner_id' => $budgetPartnerRecipient->id,
                                    'budget_in_account_id' => 0,
                                    'budget_out_account_id' => $budgetAccountPayer->id,
                                    'comment' => $comment,
                                ));
                                $budgetOperation->user()->associate($this->user);
                                $budgetOperation->project()->associate($this->workProject);
                                $budgetOperation->budgetUpload()->associate($budgetUpload);
                                $budgetOperation->amount = $amount;
                                $budgetOperation->save();
                                $operationsAddCount++;
                                $operationAdded = true;
                            } else {
                                $notWrittenOffOperation .= 'Операция №' . $number . ' на сумму ' . $amount . ' не может быть загружена, т.к еще нет подтверждения банка о ее проведении (Перевод 1). <br>';
                            }

                            // Заявки на расход - отметка об оплате
                            $costsRequest = BudgetCostsRequests::wherePaymentOrderNumber($number)
                                ->whereRequestedAmount($amount * 100)
                                ->whereStatus(BudgetCostsRequests::STATUS_APPROVED)
                                ->whereProjectId($this->workProject->id)
                                ->first();

                            if ($costsRequest && $dateOut) {
                                $costsRequest->budget_upload_id = $budgetUpload->id;
                                $costsRequest->status = BudgetCostsRequests::STATUS_PAID;
                                $costsRequest->paid_at = $dateOut;

                                $costsRequest->save();
                            } elseif ($costsRequest && !$dateOut) {
                                $costsRequest->budget_upload_id = $budgetUpload->id;
                                $costsRequest->paid_at = null;
                                $costsRequest->save();
                            }
                        }
                    }
                } //если р/с плательщика не наш, а р/с получателя наш, то это операция приходная
                elseif (!$budgetAccountPayer && $budgetAccountRecipient) {
                    $budgetOperation = BudgetOperation::whereProjectId($this->workProject->id)->whereBankId($number)->whereAmount($amount * 100)->whereDate($dateIn)->first();
                    if (!$budgetOperation) {
                        $budgetPartnerPayer = BudgetPartner::whereProjectId($this->workProject->id)->whereCurrentAccount($currentAccountPayer)->first();
                        if (!$budgetPartnerPayer) {
                            $budgetPartnerPayer = BudgetPartner::create(array(
                                'name' => $namePayer,
                                'current_account' => e($currentAccountPayer)
                            ));
                            $budgetPartnerPayer->project()->associate($this->workProject);
                            $budgetPartnerPayer->save();
                        }
                        $budgetOperation = BudgetOperation::create(array(
                            'isuploaded' => 1,
                            'date' => $dateIn,
                            'bank_id' => $number,
                            'type' => BudgetOperation::TYPE_INCOMING,
                            'budget_cost_id' => 0,
                            'budget_partner_id' => $budgetPartnerPayer->id,
                            'budget_in_account_id' => $budgetAccountRecipient->id,
                            'budget_out_account_id' => 0,
                            'comment' => $comment,
                        ));
                        $budgetOperation->user()->associate($this->user);
                        $budgetOperation->project()->associate($this->workProject);
                        $budgetOperation->budgetUpload()->associate($budgetUpload);
                        $budgetOperation->amount = $amount;
                        $budgetOperation->save();
                        $operationsAddCount++;
                        $operationAdded = true;
                    }
                } //если р/с плательщика наш и р/с получателя наш, то это операция перевода
                elseif ($budgetAccountPayer && $budgetAccountRecipient) {
                    $date = $dateOut;
                    if (!$date) {
                        $date = $dateIn;
                    }
                    if ($date) {
                        $budgetOperation = BudgetOperation::whereProjectId($this->workProject->id)->whereBankId($number)->whereAmount($amount * 100)->whereDate($date)->first();
                        if (!$budgetOperation) {
                            $budgetOperation = BudgetOperation::create(array(
                                'isuploaded' => 1,
                                'date' => $date,
                                'bank_id' => $number,
                                'type' => BudgetOperation::TYPE_EXCHANGE,
                                'budget_cost_id' => 0,
                                'budget_partner_id' => 0,
                                'budget_in_account_id' => $budgetAccountRecipient->id,
                                'budget_out_account_id' => $budgetAccountPayer->id,
                                'comment' => $comment,
                            ));
                            $budgetOperation->user()->associate($this->user);
                            $budgetOperation->project()->associate($this->workProject);
                            $budgetOperation->budgetUpload()->associate($budgetUpload);
                            $budgetOperation->amount = $amount;
                            $budgetOperation->save();
                            $operationsAddCount++;
                            $operationAdded = true;
                            if ($budgetAccountPayer->isrobokassa) {
                                $reg = "#комис.Банка '(.*?)'#is";
                                preg_match_all($reg, $comment, $matches2);
                                $tax = (float)$matches2[1][0];
                                if (!$tax) {
                                    $reg = "#комис.Банка ''(.*?)''#is";
                                    preg_match_all($reg, $comment, $matches2);
                                    $tax = (float)$matches2[1][0];
                                    if (!$tax) {
                                        $reg = "#комис.Банка \"(.*?)\"#is";
                                        preg_match_all($reg, $comment, $matches2);
                                        $tax = (float)$matches2[1][0];
                                    }
                                }
                                $parentId = $budgetOperation->id;

                                if ($tax) {
                                    $budgetPartnerRecipient = BudgetPartner::whereProjectId($this->workProject->id)->whereCurrentAccount($currentAccountRecipient)->first();
                                    if (!$budgetPartnerRecipient) {
                                        $budgetPartnerRecipient = BudgetPartner::create(array(
                                            'name' => $nameRecipient,
                                            'current_account' => e($currentAccountRecipient)
                                        ));
                                        $budgetPartnerRecipient->project()->associate($this->workProject);
                                        $budgetPartnerRecipient->save();
                                    }

                                    $budgetOperation = BudgetOperation::create(array(
                                        'isuploaded' => 1,
                                        'date' => $date,
                                        'bank_id' => $number,
                                        'type' => BudgetOperation::TYPE_OUTCOMING,
                                        'budget_cost_id' => $budgetAccountPayer->cost->id,
                                        'budget_partner_id' => $budgetPartnerRecipient->id,
                                        'budget_in_account_id' => 0,
                                        'budget_out_account_id' => $budgetAccountPayer->id,
                                        'parent_id' => $parentId
                                    ));
                                    $budgetOperation->user()->associate($this->user);
                                    $budgetOperation->project()->associate($this->workProject);
                                    $budgetOperation->budgetUpload()->associate($budgetUpload);
                                    $budgetOperation->amount = $tax;
                                    $budgetOperation->save();
                                }
                            }
                        }
                    } else {
                        $notWrittenOffOperation .= 'Операция №' . $number . ' на сумму ' . $amount . ' не может быть загружена, т.к еще нет подтверждения банка о ее проведении (Перевод 2). <br>';
                    }
                }
                if (!$operationAdded) {
                    $operationsErrorsLog .= "Пропуск операции №{$number} на сумму {$amount}<br/>";
                }
            }
        }

        if ($operationsErrorsLog != '') {
            $operationsErrorsLog = '<br/>' . $operationsErrorsLog;
        }
        if ($accountStartAmount != $budgetAccountStartAmount && $accountEndAmount != $workBudgetAccount->getSum()) {
            $response = array(
                'status' => 'fail',
                'message' => 'Файл не загружен. Сумма в бюджете не совпадает с начальной суммой на Р/С в выгрузке.<br/>В выгрузке ' . $accountStartAmount . 'р.<br/>В бюджете ' . $budgetAccountStartAmount . 'р.' . $operationsErrorsLog . '<br>' . $notWrittenOffOperation,
                'stat' => $this->setupLayout('budget.upload.stat')
                    ->with('operationAddСount', $operationsAddCount)
                    ->with('operationProcessСount', $operationsProcessCount)
                    ->with('accountStartAmount', $accountStartAmount)
                    ->with('accountEndAmount', $accountEndAmount)
                    ->with('budgetAccountAmount', $workBudgetAccount->getSum())
                    ->render()
            );
            if ($budgetUpload) {
                $budgetUpload->operations()->forceDelete();
                $budgetUpload->delete();
            }
            return $response;
        } elseif ($accountEndAmount != $workBudgetAccount->getSum()) {
            $response = array(
                'status' => 'fail',
                'message' => 'Файл не загружен. Конечные суммы не совпадают.' . $operationsErrorsLog . '<br>' . $notWrittenOffOperation,
                'stat' => $this->setupLayout('budget.upload.stat')
                    ->with('operationAddСount', $operationsAddCount)
                    ->with('operationProcessСount', $operationsProcessCount)
                    ->with('accountStartAmount', $accountStartAmount)
                    ->with('accountEndAmount', $accountEndAmount)
                    ->with('budgetAccountAmount', $workBudgetAccount->getSum())
                    ->render()
            );
            if ($budgetUpload) {
                $budgetUpload->operations()->forceDelete();
                $budgetUpload->delete();
            }
            return $response;
        }
        $response = array(
            'namePayer' => $namePayer,
            'currentAccountPayer' => $currentAccountPayer,
            'match' => $matchesAcc,
            'status' => 'success',
            'message' => 'Файл успешно загружен',
            'stat' => $this->setupLayout('budget.upload.stat')
                ->with('operationAddСount', $operationsAddCount)
                ->with('operationProcessСount', $operationsProcessCount)
                ->with('accountStartAmount', $accountStartAmount)
                ->with('accountEndAmount', $accountEndAmount)
                ->with('budgetAccountAmount', $workBudgetAccount->getSum())
                ->render()
        );
        return $response;
    }

    public function robokassa()
    {
        $input = Input::all();

        if ($this->user->budgetProjects()->first() == null) {
            return Redirect::to('/');
        }
        if (Input::has('projectId')) {
            Session::put('work_projectId', $input['projectId']);
            return Redirect::to('budget/robokassa/upload');
        }

        return $this->setupLayout('budget.robokassa.index')
            ->with('user', $this->user)
            ->with('workProject', $this->workProject);
    }

    public function robokassaUploadFile()
    {
        if (!$this->workProject) {
            $response = array(
                'status' => 'fail',
                'message' => 'Проект не найден'
            );
            return Response::json($response);
        }

        $valid_exts = array('csv', 'xlsx');
        $max_size = 5 * 1024 * 1024;
        $path = public_path() . '/budgetfiles/' . $this->workProject->id . '/';
        $file = Input::file('file');
        $ext = ($file->getClientOriginalExtension()) ? $file->getClientOriginalExtension() : 'csv';
        $size = $file->getClientSize();
        $name = 'robokassa' . date("YmdHis") . "." . $ext;

        if (in_array($ext, $valid_exts) && $size < $max_size) {
            if ($file->move($path, $name)) {
                $response = $this->robokassaLoadBudgetFile($path, $name);
                return Response::json($response);
            }
        }

        $response = array(
            'status' => 'fail',
            'message' => 'Некорректный файл'
        );
        return Response::json($response);
    }

    protected function robokassaLoadBudgetFile($path, $name)
    {
        $workBudgetAccount = BudgetAccount::whereProjectId($this->workProject->id)->whereIsrobokassa(1)->first();
        if (!$workBudgetAccount) {
            $response = array('status' => 'fail', 'message' => 'В проекте не найден расчетный счет робокассы');
            return $response;
        }

        $operationsAddCount = 0;
        $operationsProcessCount = 0;

        $contents = iconv('CP1251', 'UTF-8', File::get($path . $name));
        $reg = "#(.*?);(.*?);(.*?);(.*?) (.*?);(.*?);(.*?)(\r?\n)#is";
        preg_match_all($reg, $contents, $matches);
        if ($matches[1] && is_array($matches[1])) {
            foreach ($matches[1] as $key => $value) {
                $status = trim($matches[1][$key]);
                if ($status != 'Состояние') {
                    $operationsProcessCount++;
                    if ($status == 'Выполнена') {
                        $number = trim($matches[2][$key]);
                        $amount = trim($matches[4][$key]);
                        $dateIn = trim($matches[6][$key]);
                        $comment = trim($matches[6][$key]);
                        $dateIn = explode(' ', $dateIn);
                        $dateIn = explode('.', $dateIn[0]);
                        $dateIn = "{$dateIn[2]}-{$dateIn[1]}-{$dateIn[0]}";

                        $budgetOperation = BudgetOperation::whereProjectId($this->workProject->id)->whereBankId($number)->whereAmount($amount * 100)->whereDate($dateIn)->first();
                        if (!$budgetOperation) {
                            $budgetPartnerPayer = BudgetPartner::whereProjectId($this->workProject->id)->orderBy('name')->first();
                            if ($budgetPartnerPayer) {
                                $budgetOperation = BudgetOperation::create(array(
                                    'isuploaded' => 1,
                                    'date' => $dateIn,
                                    'bank_id' => $number,
                                    'type' => BudgetOperation::TYPE_INCOMING,
                                    'amount' => $amount,
                                    'budget_cost_id' => 0,
                                    'budget_partner_id' => $budgetPartnerPayer->id,
                                    'budget_in_account_id' => $workBudgetAccount->id,
                                    'budget_out_account_id' => 0,
                                    'comment' => $comment,
                                ));
                                $budgetOperation->user()->associate($this->user);
                                $budgetOperation->project()->associate($this->workProject);
                                $budgetOperation->save();
                                $operationsAddCount++;
                                $operationAdded = true;
                            }
                        }
                    }
                }
            }
        }

        $response = array(
            'status' => 'success',
            'message' => 'Файл успешно загружен',
            'stat' => $this->setupLayout('budget.robokassa.stat')
                ->with('operationAddСount', $operationsAddCount)
                ->with('operationProcessСount', $operationsProcessCount)
                ->with('budgetAccountAmount', $workBudgetAccount->getSum())
                ->render()
        );
        return $response;
    }

}
