<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use DB;
use App\NOC;
use App\TransferPropertyHistory;
use Illuminate\Support\Facades\Auth;


class TransferProperty extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'transfer_type','unit_detail','property_id', 'owner_id', 'transfer_customer_id', 'transfer_date',
        'transfer_note', 'amount_paid', 'surcharge', 'old_client_id', 'new_client_id', 'transfer_charges'
    ];
    const normal_transfer = 1;
    const gift_transfer = 2;

    const family_transfer = 3;
    
    const death_transfer = 4;

    const transfer_approved = 1;
    const transfer_pending = 0;
    const transfered = 2;

    const document_checklist_approved = 1;
    const document_checklist_pending = 0;


    public function property()
    {
        return $this->belongsTo('\App\CustomerProperty', 'property_id');
    }

    public function  owner()
    {
        return $this->belongsTo('\App\Customer', 'owner_id');
    }

    public function  transfer()
    {
        return $this->belongsTo('\App\Customer', 'transfer_customer_id');
    }

    public function  transferhistory()
    {
        return $this->hasMany('\App\TransferPropertyHistory', 'transfer_prop_id');
        
    }
    public function  transferDocument()
    {
        return $this->hasMany('\App\TransferPropertyDocuments', 'transfer_property_id');
        
    }

    public function insertNewTransfer($request)
    {

        DB::beginTransaction();

        try {
            
                    /*
                   Create a customer id by getting existing customer or create new one
                    */
            $nominee_id = null;
            if ($request->customer_id) {

                $customer = Customer::where('id', $request->customer_id)->first();

                if ($request->nominee_name_n) {

                    $nominee = CustomerNominee::create(['customer_id' => $customer->id, 'nominee_name' => $request->nominee_name_n, 'nominee_so_do_wo' => $request->nominee_so_do_wo_n, 'nominee_cnic' => $request->nominee_cnic_n, 'nominee_passport_no' => $request->nominee_passport_no_n, 'nominee_phone_number' => $request->nominee_phone_number_n, 'nominee_res_number' => $request->nominee_res_number_n, 'nominee_mobile_number' => $request->nominee_mobile_number_n, 'nominee_relation' => $request->nominee_relation_n, 'nominee_email' => $request->nominee_email_n, 'nominee_cnic_flag' => $request->nominee_cnic_flag_n]);
                    $nominee_id = $nominee->id;
                }
            } else {
                $customer = Customer::create(['father_name' => $request->father_name, 'name' => $request->name, 'email' => $request->email, 'mailing_address' => $request->mailing_address, 'permanent_address' => $request->permanent_address, 'dob' => $request->dob, 'occupation' => $request->occupation, 'cnic' => $request->cnic, 'passport_no' => $request->passport_no, 'res_number' => $request->res_number, 'phone_number' => $request->phone_number, 'mobile_number' => $request->mobile_number, 'nominee_name' => $request->nominee_name, 'nominee_so_do_wo' => $request->nominee_so_do_wo, 'nominee_cnic' => $request->nominee_cnic, 'nominee_passport_no' => $request->nominee_passport_no, 'nominee_phone_number' => $request->nominee_phone_number, 'nominee_res_number' => $request->nominee_res_number, 'nominee_mobile_number' => $request->nominee_mobile_number, 'nominee_relation' => $request->nominee_relation, 'nominee_email' => $request->nominee_email, 'father_type' => $request->father_type, 'cnic_flag' => $request->cnic_flag, 'nominee_cnic_flag' => $request->nominee_cnic_flag, 'nominee_father_type' => $request->nominee_father_type, 'password' => bcrypt($request->password)]);

                if ($request->nominee_name_1) {
                    for ($i = 0; $i < count($request->nominee_name_1); $i++)
                        CustomerNominee::create(['customer_id' => $customer->id, 'nominee_name' => $request->nominee_name_1[$i], 'nominee_so_do_wo' => $request->nominee_so_do_wo_1[$i], 'nominee_cnic' => $request->nominee_cnic_1[$i], 'nominee_passport_no' => $request->nominee_passport_no_1[$i], 'nominee_phone_number' => $request->nominee_phone_number_1[$i], 'nominee_res_number' => $request->nominee_res_number_1[$i], 'nominee_mobile_number' => $request->nominee_mobile_number_1[$i], 'nominee_relation' => $request->nominee_relation_1[$i], 'nominee_email' => $request->nominee_email_1[$i]]);
                }


                if ($request->hasfile('file')) {
                    $file = $request->file('file');

                    $name = $customer->id . '-' . $file->getClientOriginalName();
                    $file->move(public_path() . '/uploads/', $name);

                    Customer::where('id', $customer->id)->update(['img_url' => $name, 'updated_at' => date('Y-m-d H:i:s')]);
                }
                if ($request->hasfile('photos')) {

                    foreach ($request->photos as $photo) {

                        $name = $customer->id . '-' . $photo->getClientOriginalName();

                        $photo->move(public_path() . '/uploads/', $name);

                        CustomerDocument::create(['customer_id' => $customer->id, 'url' => $name]);
                    }
                }
            }

            $noc = NOC::where('id', $request->property_id)->first();
           $customer_property_id= $noc->unitNumber->customer_property->id;

            $owner = CustomerProperty::where('id', $customer_property_id)->first();
            
           
            $received = CustomerStatement::where('customer_property_id',  $customer_property_id)->sum('received');

             $unit_detail = $this->getUnitDetail($owner);

            $transfer_id = TransferProperty::create(['transfer_type'=> $noc->transfer_type,'property_id' => $customer_property_id, 'owner_id' => $owner->customer->id, 'transfer_customer_id' => $customer->id, 'transfer_date' => $request->transfer_date, 'transfer_note' => $request->transfer_note, 'amount_paid' => $received, 'transfer_charges' => $request->transfer_charges, 'old_client_id' => $request->old_client_id,'unit_detail' => $unit_detail]);
            // $transferhistory= new TransferPropertyHistory();
            // $result=  $transferhistory->makeTransferHistory($request,$transfer_id->id);
         
        //   if($result == false){
        // throw exception
        // throw new Exception("Something Went wrong");
        //   }

            // CustomerProperty::where('id', $request->property_id)->update(['customer_id' => $customer->id, 'membership_no' => '', 'status' => CustomerProperty::pending]);



            // CustomerStatement::where('customer_property_id', $request->property_id)->update(['customer_id' => $customer->id]);

            // $receipt = Receipt::create(['customer_id' => $customer->id, 'customer_property_id' => $owner->id, 'payment_head' => Receipt::transfer_fee, 'payment_mode' => $request->payment_mode, 'bank_name' => $request->bank_name, 'cheque_number' => $request->cheque_number, 'cheque_title' => $request->cheque_title, 'amount' => $request->amount, 'receipt_no' => $request->receipt_no, 'receipt_date' => $request->receipt_date, 'company_account' => $request->company_account, 'adjustment_type' => $request->adjustment_type, 'adjustment_detail' => $request->adjustment_detail, 'inventory_id' => $owner->inventory_id]);

            // if ($request->payment_mode != Receipt::cash && $request->payment_mode != Receipt::adjustment) {
            //     $cBank = CompanyBank::where('id', $request->company_account)->first();
            //     if ($cBank) {
            //         CompanyBank::where('id', $request->company_account)->update(['amount' => $cBank->amount + $request->amount]);
            //         //make transation
            //         CompanyBankTransaction::create(['receipt_id' => $receipt->id, 'company_account' => $request->company_account]);
            //     }
            // }
            // if ($request->payment_mode == Receipt::adjustment) {
            //     CustomerAdjustment::create(['receipt_id' => $receipt->id, 'type' => $request->adjustment_type, 'description' => $request->adjustment_detail, 'merge_amount' => $request->amount]);
            // }

            // //update customer record
            // $customer = Customer::where('id', $customer->id)->first();
            // Customer::where('id', $customer->id)->update(['total_paid_amount' => $customer->total_paid_amount + $request->amount]);

           
          
            // $noc->status = 3;
            // $noc->save();
        } catch (\Exception $e) {
            DB::rollback();
            return false;
        }
        DB::commit();

        $property = CustomerProperty::with('inventory', 'customer')->where('id', $owner->id)->first();


        return $property;
    }
    public function insertNewTransferOLD($request)
    {

        DB::beginTransaction();

        try {
            
                    /*
                   Create a customer id by getting existing customer or create new one
                    */
            $nominee_id = null;
            if ($request->customer_id) {

                $customer = Customer::where('id', $request->customer_id)->first();

                if ($request->nominee_name_n) {

                    $nominee = CustomerNominee::create(['customer_id' => $customer->id, 'nominee_name' => $request->nominee_name_n, 'nominee_so_do_wo' => $request->nominee_so_do_wo_n, 'nominee_cnic' => $request->nominee_cnic_n, 'nominee_passport_no' => $request->nominee_passport_no_n, 'nominee_phone_number' => $request->nominee_phone_number_n, 'nominee_res_number' => $request->nominee_res_number_n, 'nominee_mobile_number' => $request->nominee_mobile_number_n, 'nominee_relation' => $request->nominee_relation_n, 'nominee_email' => $request->nominee_email_n, 'nominee_cnic_flag' => $request->nominee_cnic_flag_n]);
                    $nominee_id = $nominee->id;
                }
            } else {
                $customer = Customer::create(['father_name' => $request->father_name, 'name' => $request->name, 'email' => $request->email, 'mailing_address' => $request->mailing_address, 'permanent_address' => $request->permanent_address, 'dob' => $request->dob, 'occupation' => $request->occupation, 'cnic' => $request->cnic, 'passport_no' => $request->passport_no, 'res_number' => $request->res_number, 'phone_number' => $request->phone_number, 'mobile_number' => $request->mobile_number, 'nominee_name' => $request->nominee_name, 'nominee_so_do_wo' => $request->nominee_so_do_wo, 'nominee_cnic' => $request->nominee_cnic, 'nominee_passport_no' => $request->nominee_passport_no, 'nominee_phone_number' => $request->nominee_phone_number, 'nominee_res_number' => $request->nominee_res_number, 'nominee_mobile_number' => $request->nominee_mobile_number, 'nominee_relation' => $request->nominee_relation, 'nominee_email' => $request->nominee_email, 'father_type' => $request->father_type, 'cnic_flag' => $request->cnic_flag, 'nominee_cnic_flag' => $request->nominee_cnic_flag, 'nominee_father_type' => $request->nominee_father_type, 'password' => bcrypt($request->password)]);

                if ($request->nominee_name_1) {
                    for ($i = 0; $i < count($request->nominee_name_1); $i++)
                        CustomerNominee::create(['customer_id' => $customer->id, 'nominee_name' => $request->nominee_name_1[$i], 'nominee_so_do_wo' => $request->nominee_so_do_wo_1[$i], 'nominee_cnic' => $request->nominee_cnic_1[$i], 'nominee_passport_no' => $request->nominee_passport_no_1[$i], 'nominee_phone_number' => $request->nominee_phone_number_1[$i], 'nominee_res_number' => $request->nominee_res_number_1[$i], 'nominee_mobile_number' => $request->nominee_mobile_number_1[$i], 'nominee_relation' => $request->nominee_relation_1[$i], 'nominee_email' => $request->nominee_email_1[$i]]);
                }


                if ($request->hasfile('file')) {
                    $file = $request->file('file');

                    $name = $customer->id . '-' . $file->getClientOriginalName();
                    $file->move(public_path() . '/uploads/', $name);

                    Customer::where('id', $customer->id)->update(['img_url' => $name, 'updated_at' => date('Y-m-d H:i:s')]);
                }
                if ($request->hasfile('photos')) {

                    foreach ($request->photos as $photo) {

                        $name = $customer->id . '-' . $photo->getClientOriginalName();

                        $photo->move(public_path() . '/uploads/', $name);

                        CustomerDocument::create(['customer_id' => $customer->id, 'url' => $name]);
                    }
                }
            }



            $owner = CustomerProperty::where('id', $request->property_id)->first();
            $noc = NOC::where('customer_id', $owner->customer->id)->where('unit_number_id', $owner->inventory->id)->first();

            $received = CustomerStatement::where('customer_property_id', $request->property_id)->sum('received');

             $unit_detail = $this->getUnitDetail($owner);

            $transfer_id = TransferProperty::create(['transfer_type'=> $noc->transfer_type,'property_id' => $request->property_id, 'owner_id' => $owner->customer->id, 'transfer_customer_id' => $customer->id, 'transfer_date' => $request->transfer_date, 'transfer_note' => $request->transfer_note, 'amount_paid' => $received, 'transfer_charges' => $request->transfer_charges, 'old_client_id' => $request->old_client_id,'unit_detail' => $unit_detail]);
            $transferhistory= new TransferPropertyHistory();
            $result=  $transferhistory->makeTransferHistory($request,$transfer_id->id);
         
          if($result == false){
        // throw exception
        // throw new Exception("Something Went wrong");
          }

            CustomerProperty::where('id', $request->property_id)->update(['customer_id' => $customer->id, 'membership_no' => '', 'status' => CustomerProperty::pending]);



            CustomerStatement::where('customer_property_id', $request->property_id)->update(['customer_id' => $customer->id]);

            $receipt = Receipt::create(['customer_id' => $customer->id, 'customer_property_id' => $owner->id, 'payment_head' => Receipt::transfer_fee, 'payment_mode' => $request->payment_mode, 'bank_name' => $request->bank_name, 'cheque_number' => $request->cheque_number, 'cheque_title' => $request->cheque_title, 'amount' => $request->amount, 'receipt_no' => $request->receipt_no, 'receipt_date' => $request->receipt_date, 'company_account' => $request->company_account, 'adjustment_type' => $request->adjustment_type, 'adjustment_detail' => $request->adjustment_detail, 'inventory_id' => $owner->inventory_id]);

            if ($request->payment_mode != Receipt::cash && $request->payment_mode != Receipt::adjustment) {
                $cBank = CompanyBank::where('id', $request->company_account)->first();
                if ($cBank) {
                    CompanyBank::where('id', $request->company_account)->update(['amount' => $cBank->amount + $request->amount]);
                    //make transation
                    CompanyBankTransaction::create(['receipt_id' => $receipt->id, 'company_account' => $request->company_account]);
                }
            }
            if ($request->payment_mode == Receipt::adjustment) {
                CustomerAdjustment::create(['receipt_id' => $receipt->id, 'type' => $request->adjustment_type, 'description' => $request->adjustment_detail, 'merge_amount' => $request->amount]);
            }

            //update customer record
            $customer = Customer::where('id', $customer->id)->first();
            Customer::where('id', $customer->id)->update(['total_paid_amount' => $customer->total_paid_amount + $request->amount]);

           
          
            $noc->status = 3;
            $noc->save();
        } catch (\Exception $e) {
            DB::rollback();
            return false;
        }
        DB::commit();

        $property = CustomerProperty::with('inventory', 'customer')->where('id', $owner->id)->first();


        return $property;
    }


    public function approveReceipt(){
        
    }


    public function getUnitDetail(CustomerProperty $owner)
    {

        $floor_street = '';
        if ($owner->inventory->floor) {
            $floor_street = $owner->inventory->floor->name;
        }
        $block = $owner->inventory->floor?$owner->inventory->floor->unitBlock ? $owner->inventory->floor->unitBlock->name : '':'';
        $category = '';
        foreach ($owner->inventory->categories as $c) {
            $category =  $category . ' ' . $c->category->name . '' . $c->category->percent;
        }
        $size = $owner->inventory->size ? $owner->inventory->size->name : '';
        $total_price =  $owner->inventory->total_price;
        $net_pay = $owner->net_pay;
        $unit_plot_no = $owner->inventory ? $owner->inventory->unit_number : '';
        $unit_type = $owner->inventory->type->name;
        $area =    $owner->inventory->area;
        $discount = number_format($owner->discount);
        $category_cost = number_format($owner->inventory->extra_amount);
        $booking_type = '';
        if ($owner->booking_type == \App\CustomerProperty::normal) {
            $booking_type = 'Installment';
        } elseif ($owner->booking_type == \App\CustomerProperty::full_payment) {
            $booking_type = 'Full Payment';
        }
        $booking_date = date('d-m-Y', strtotime($owner->original_boooking_date));
        $schedule_start_date = '';
        if ($owner->schedule_start_date) {
            $schedule_start_date = date('d-m-Y', strtotime($owner->schedule_start_date));
        }
        $unit_array = array(
            'floor_street' => $floor_street,
            'unit_plot_no' => $unit_plot_no,
            'block' => $block,
            'unit_type' => $unit_type,
            'category' => $category,
            'area' => $area,
            'size' => $size,
            'discount' => $discount,
            'total_price' => $total_price,
            'category_cost' => $category_cost,
            'net_amt' => $net_pay,
            'booking_type' => $booking_type,
            'booking_date' => $booking_date,
            'schedule_start_date' => $schedule_start_date
        );
        // $out = array_values($unit_array);
        // return json_encode($unit_array);
        return serialize($unit_array);
        // unserialize($data);
    }
  
}
