<?php

class LoanCustomerController extends \BaseController {


    /**
     * Path for Store upload
     * @var string
     */
    private $path = "uploads/customers/";

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		return View::make('loan_customers.index');
	}


	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
        $loanCustomer = new LoanCustomer;
		return View::make('customers.new_customer', ['loanCustomer' => $loanCustomer]);
	}


	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
        $data = Input::except(['_token', 'submit']);
        $validator = Validator::make(Input::all(), LoanCustomer::$rules);
        if ($validator->fails()) return Redirect::back()
                        ->withMessage('messages.fail-to-create')
                        ->with('messageType', 'danger')
                        ->withErrors($validator->messages())
                        ->withInput();
        if (!empty($data['dob'])) {
            $data['dob']  = Carbon\Carbon::createFromFormat("d/m/Y", $data['dob']);
        } else {
            $data['dob'] = null;
        }
        if (!empty($data['date_of_stay'])) {
            $data['date_of_stay'] = Carbon\Carbon::createFromFormat("d/m/Y", $data['date_of_stay']);
        } else {
            $data['date_of_stay'] = null;
        }
        $path = $this->path;
        DB::beginTransaction();
        try {
            if (Input::hasFile('photo')) {
                // $data['photo'] = Helper::uploadFile(Input::file('photo'), $path);
                $file = Input::file('photo');
                $filename = $file->getClientOriginalName();
                $file->move($this->path, $filename);
                $image = Image::make(sprintf($this->path.'%s', $filename))->fit(600, 360)->save();
                $data['photo']  = $this->path.$filename;

            } else {
                if(!empty(Input::get("image_name"))) {
                    $destinationPath = public_path() . DIRECTORY_SEPARATOR . $path;
                    $imageName = uniqid().".jpg";
                    saveImage(Input::get("image_name"),$destinationPath,$imageName);
                    $data['photo'] =  $path . $imageName;
                }
                else {
                    $data['photo'] = 'uploads/none.jpg';
                }
            }
            $company = new Company;
            $company->hired_date = null;
            $garantor = new Garantor;
            $customer = LoanCustomer::create($data);
            $existCustomer = LoanCustomer::find($customer->id);
            $existCustomer->company()->save($company);
            $existCustomer->garantor()->save($garantor);
            DB::commit();
            return Redirect::route('loan_customers.show', $customer->id)
                ->withMessage('messages.success-to-create')
                ->with('messageType', 'success');

        } catch (Exception $e) {
            DB::rollback();
            return dd($e->getMessage());
            return Redirect::back()
                ->withInput()
                ->withMessage('messages.success-to-create')
                ->with('messageType', 'success');
        }

	}

	/**
    * Get Customers
    * @return [Json] [For Datatable]
    */
    public function getCustomers() {
        $loanCustomers = DB::table('loan_customers')->select('loan_customers.*');
        return Datatables::of($loanCustomers)
        ->editColumn('gender', function ($loanCustomer) {
            return trans('customers.gender.'. $loanCustomer->gender);
        })
        ->editColumn('action',
        '
        @if(UserRole::has("detail_customer"))
        <a href="{{ Route("loan_customers.show",$id) }}" class="btn btn-xs btn-default"><i class="fa fa-th-list"></i> {{Trans("dashboard.others.show")}}</a>
        <a href="{{ Route("customers.printCustomer",$id) }}" class="btn btn-xs btn-default" target="_blank"><i class="fa fa-print"></i> {{Trans("dashboard.others.print")}}</a>
        @endif
        @if(UserRole::has("delete_customer"))
        <a href="#" class="btn btn-xs btn-danger" data-toggle="modal" data-target="#myModal{{$id}}"><i class="fa fa-trash"></i> {{Trans("dashboard.crud.remove")}}</a>
        @endif

        <div class="modal fade modal-delete" id="myModal{{$id}}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog modal-primary" role="document">
        <div class="modal-content">
        <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">{{Trans("dashboard.crud.remove")}}</h4>
        </div>
        <div class="modal-body">
        {{Trans("messages.delete-confirm", array("attribute" => $full_name_kh))}}?
        </div>
        <div class="modal-footer">
        <button type="button" class="btn btn-outline pull-left" data-dismiss="modal">{{Trans("dashboard.others.no")}}</button>
        {{ Form::open(array("action" => array("loan_customers.destroy",$id),"method"=>"DELETE"))}}
        {{ Form::hidden("_method", "DELETE") }}
        <button type="submit" class="btn btn-outline btn-ajax-delete" data-url="{{ route("loan_customers.destroy", $id)}}">{{Trans("dashboard.others.yes")}}</button>
        {{ Form::close() }}
        </div>
        </div>
        </div>
        '
        )
        ->make(true);
    }


	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
        $loanCustomer = LoanCustomer::find($id);
        $installments = Installment::whereIn('status', ['pendding', 'proccessing'])->where('customer_id', $id)->count();
		return View::make('customers.customer', [
            'loanCustomer' => $loanCustomer,
            'installments'  =>  $installments
        ]);
	}


	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//
	}


    public function loadCustomer($id)
    {
        $loanCustomer = LoanCustomer::find($id);
        return View::make('loan_customers.inc.customer', [
            'loanCustomer' => $loanCustomer
        ]);
    }

    public function loadCompany($id)
    {
        $loanCustomer = LoanCustomer::find($id);
        return View::make('loan_customers.inc.company', [
            'loanCustomer' => $loanCustomer
        ]);
    }
    public function loadGarantor($id)
    {
        $loanCustomer = LoanCustomer::find($id);
        return View::make('loan_customers.inc.garantor', [
            'loanCustomer' => $loanCustomer
        ]);
    }

    public function loadEMILoan($id) 
    {
        $loanCustomer = LoanCustomer::find($id);
        $installments = Installment::emiInstallment($id)->get();
        return View::make("loan_customers.inc.emi_loan",[
            'loanCustomer'  =>  $loanCustomer,
            'installments'  =>  $installments
        ]);
    }

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		$data = Input::except(['_token', 'submit']);
        $loanCustomer = LoanCustomer::find($id);
        $rules = [
           'full_name_kh' => 'required',
           'full_name_en' => 'required',
           'tel' => 'required|unique:loan_customers,tel,'.$loanCustomer->id,
           'id_card_no' => 'required|unique:loan_customers,id_card_no,'.$loanCustomer->id
        ];
        $validator = Validator::make(Input::all(), $rules);
        if ($validator->fails()) {
            return Response::json([
                'success'   =>  false,
                'errors'    =>  $validator->getMessageBag()->toArray()
            ], 400);
        }
        
        if (!empty($data['dob'])) {
            $data['dob']  = Carbon\Carbon::createFromFormat("d/m/Y", $data['dob']);
        } else {
            $data['dob'] = null;
        }
        if (!empty($data['date_of_stay'])) {
            $data['date_of_stay'] = Carbon\Carbon::createFromFormat("d/m/Y", $data['date_of_stay']);
        } else {
            $data['date_of_stay'] = null;
        }
        $path = $this->path;
        DB::beginTransaction();
        try {
            if (Input::hasFile('photo')) {
                // $data['photo'] = Helper::uploadFile(Input::file('photo'), $path);
                $file = Input::file('photo');
                $filename = $file->getClientOriginalName();
                $file->move($this->path, $filename);
                $image = Image::make(sprintf($this->path.'%s', $filename))->fit(600, 360)->save();
                $data['photo']  = $this->path.$filename;
            } else {
                if(!empty(Input::get("image_name"))) {
                    $destinationPath = public_path() . DIRECTORY_SEPARATOR . $path;
                    $imageName = uniqid().".jpg";
                    saveImage(Input::get("image_name"),$destinationPath,$imageName);
                    $data['photo'] = $path . $imageName;
                } else {
                    $data['photo'] = $loanCustomer->photo;
                }
            }
            if ($loanCustomer->update($data)) {
                DB::commit();
                return ['error' => false, 'message' => trans('messages.success-to-update')];
            } else {
                DB::rollback();
                return ['error' => false, 'message' => trans('messages')];
            }
            

        } catch (Exception $e) {
            DB::rollback();
            return ['error' => false, 'message' => 'success'];
        }
	}


	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		$installments = Installment::where('customer_id', $id)->get();
        if (count($installments) > 0) return ['error' => true, 'message'  => trans('messages.not_allow_to_delete')];
        DB::beginTransaction();
        try {
            $loanCustomer = LoanCustomer::find($id);
            $company = Company::find($id);
            $garantor = Garantor::find($id);
            if ($loanCustomer->delete() && $company->delete() && $garantor->delete()) {
                DB::commit();
                return ['error' => false, 'message'  => trans('messages.success-to-delete')];
            } else {
                DB::rollback();
                return ['error' => true, 'message'  => trans('messages.fail-to-delete')];
            }
            
        } catch (Exception $e) {
            DB::rollback();
            return ['error' => true, 'message'  => trans('messages.fail-to-delete')];
        }
	}

    public function updateCompany($id)
    {
        $data = Input::except(['_token', 'submit']);
        $company = Company::find($id);
        $rules = [
           'name_kh' => 'required',
           'name_en' => 'required',
           'company_tel' => 'required|unique:companies,company_tel,'.$company->id,
           'id_of_company' => 'required|unique:companies,id_of_company,'.$company->id
        ];
        $validator = Validator::make(Input::all(), $rules);
        if ($validator->fails()) {
            return Response::json([
                'success'   =>  false,
                'errors'    =>  $validator->getMessageBag()->toArray()
            ], 400);
        }
        if (!empty($data['hired_date'])) {
            $data['hired_date']  = Carbon\Carbon::createFromFormat("d/m/Y", $data['hired_date']);
        } else {
            $data['hired_date'] = null;
        }
        if ($company->update($data)) return ['error' => false, 'message' => trans('messages.success-to-update')];
        return ['error' => true, 'message' => trans('messages.fail-to-update')];

    }

    public function updateGarantor($id)
    {
        $data = Input::except(['_token', 'submit']);
        $garantor = Garantor::find($id);
        $rules = [
           'g_full_name_kh' => 'required',
           'g_full_name_en' => 'required',
           'g_tel' => 'required|unique:garantors,g_tel,'.$garantor->id,
           'g_id_card_no' => 'required|unique:garantors,g_id_card_no,'.$garantor->id
        ];
        $validator = Validator::make(Input::all(), $rules);
        if ($validator->fails()) {
            return Response::json([
                'success'   =>  false,
                'errors'    =>  $validator->getMessageBag()->toArray()
            ], 400);
        }
        if ($validator->fails()) return ['error' => true, 'message' => "Something Wromg!"]; 
        if ($garantor->update($data)) return ['error' => false, 'message' => trans('messages.success-to-update')];
        return ['error' => true, 'message' => trans('messages.fail-to-update')];
    }

    public function loadInstallment($id)
    {
        $installments = Installment::where("loan_type", "normal")
                                    ->where('customer_id', $id)
                                    ->get();
        return View::make('loan_customers.inc.table_installment', [
            'installments' => $installments
        ]);
    }

    public function loadInstallmentForm()
    {
        $installment = new Installment;
        return View::make('loan_customers.inc.form_ajax', [
            'installment' => $installment
        ]);
    }
}
