<?php

namespace App\Http\Controllers;

use App\ChinaBankSlip;
use App\Booking;
use App\Notifications\UploadPo;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Validator;
use Illuminate\Support\Facades\Notification;

class ChinaBankSlipController extends Controller
{

    public function store(Request $request, $id)
    {      
        $booking = Booking::where('id',$id)->firstOrFail();
        
        if (!$booking) {
            return response()->json(['message'=>'Access denied'], 403);
        }

        // TODO : put this after check file exist 
        // validate file format 
        $validator = Validator::make($request->all(), [
            'file'   => 'mimes:jpg,jpeg,bmp,png,xls,xlsx,doc,docx,pdf'
        ]);

        if($validator->fails()){
            return response()->json(['message'=>'Incorrect format'],400);
        }

        $validator = Validator::make($request->all(), [
            'china_bank_slips'   => 'max:10000'
        ]);
        
        if($validator->fails()){
            return response()->json(['message'=>'Image too large, upload files up to 3 MB'], 400);
        }

        if($bankslip_file = $request->file('file')){
            $filename = $bankslip_file->getClientOriginalName();
            $ext = $bankslip_file->getClientOriginalExtension();
            $unique_name = 'cnbank_slip_' . md5($filename. time()); // probably not a good idea 
            $unique_image_path = $unique_name. '.' .$ext;
    
            // Upload Image
            $upload_path = Storage::disk('public')->putFileAs(
                'china_bank_slip', $bankslip_file, $unique_image_path
            ); 


        } else {
            return response()->json(['message'=>'file not found'],200);
        }
   
        $china_bankslip = new ChinaBankSlip;
        $china_bankslip->booking_id = $booking->id;
        $china_bankslip->china_bank_slip_path = $upload_path;
        $china_bankslip->save();

        return response()->json(['message'=>'success'], 201);
    }

    public function update(Request $request, $id){
        $booking = Booking::where('id',$id)->first();
        $china_bankslip = $booking->chinaBankSlip()->first();

        // TODO: first or fail 
        if(!$china_bankslip){
            return response()->json(["message"=> "China bankslip not found. Please upload first."],400);
		}
		
        $china_bankslip->actual_transfer_amount = $request->input('actual_transfer_amount');
        $china_bankslip->date = $request->input('date');
        $china_bankslip->details = $request->input('details');
        $china_bankslip->save();

        // update booking status 
		$booking->status = 5;
		$booking->admin_status = 6; 
		$booking->save();

        Notification::send([$booking->user], new UploadPo($booking));

        return response()->json(["message"=> "Success"],200);
    }

}
