<?php

namespace App\Http\Controllers;

use App\Models\Record;
use App\Models\Dept;
use App\Models\Year;
use App\Models\Certificat;
use App\Models\Register;
use App\Models\Statment;
use App\Models\User;
use App\Http\Requests\StoreRecordRequest;
use App\Http\Requests\UpdateRecordRequest;
use Illuminate\Support\Facades\Notification;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Notifications\RecordCreate;
use App\Notifications\Recordpay;
use App\Notifications\RecordResult;
use Storage; 
use Image;

class RecordController extends Controller
{
    function __construct()
    { 

    $this->middleware('permission:عرض القيد', ['only' => ['index']]);
    $this->middleware('permission:اضافة القيد', ['only' => ['create','store']]);
    $this->middleware('permission:تعديل القيد', ['only' => ['edit','update']]);
    $this->middleware('permission:حذف القيد', ['only' => ['destroy']]);
    $this->middleware('permission:المالية', ['only' => ['processrecordpay']]);
    $this->middleware('permission:النتيجة', ['only' => ['processrecordresult']]);

    }
    
    public function index()
    {
        if(Auth::user()->user_type == 'stu')
        {
            $records = Record::where('user_id', Auth::user()->id)->get();

        }
        else
        {
            $records = Record::all();
        }

        return view('pages.Records.index',compact('records'));
    }

    
    public function create()
    {
        
        return view('pages.Records.create');
    }

   
    public function store(StoreRecordRequest $request)
    {
        if(Record::where('user_id',Auth::user()->id)->exists())
        {
           return redirect()->back()->withErrors('تم التقديم مسبقاً');
        }
        elseif(Certificat::where('user_id',Auth::user()->id)->exists())
        {
           return redirect()->back()->withErrors('تم التقديم لأستخراج الشهادة جامعية');
        }
        elseif(Register::where('user_id',Auth::user()->id)->exists())
        {
           return redirect()->back()->withErrors('تم التقديم لسجل اكاديمي مسبقاً');
        }
        elseif(Statment::where('user_id',Auth::user()->id)->exists())
        {
           return redirect()->back()->withErrors('تم التقديم لافادة تخرج مسبقاً');
        }
        

        try {
           
            $validated = $request->validated();
           
            $record = new Record; 
            $record->first_name = $request->first_name;
            $record->second_name = $request->second_name;
            $record->midell_name = $request->midell_name;
            $record->last_name = $request->last_name;
            $record->dept_id = Auth::user()->dept_id;
            $record->user_id = Auth::user()->id;
            $record->amount = '50000';
            $record->notification_number =$request->notification_number;
           
            if ($request->hasFile('bank')) {
                $image = $request->file('bank');
                $filename = time() . '.' . $image->getClientOriginalExtension();
                $location ='/home/eustedu/certificats.eust.edu.sd/images/record/' . $filename;
                Image::make($image)->resize(500, 600)->save($location);
                $record->image = $filename;
            } 
           
            $record->save();

            $user = User::where('id',Auth::user()->id)->first();
            Notification::send($user, new \App\Notifications\RecordCreate);

            toastr()->success(trans('messages.success'));
            return redirect()->route('records.index');
         }
    
            catch (\Exception $e){
            return redirect()->back()->withErrors(['error' => $e->getMessage()]);
             }
    }

    public function show($id)
    {
        
        $record = Record::find(decrypt($id));
        return view('pages.Records.show',compact('record'));
    }

   
    public function edit($id)
    {
        $record = Record::find(decrypt($id));
        $depts =  Dept::all();
       
        return view('pages.Records.edit',compact('record','depts'));
    }

    public function update(UpdateRecordRequest $request, Record $record)
    {
        try {
           
            $record->first_name = $request->first_name;
            $record->second_name = $request->second_name;
            $record->midell_name = $request->midell_name;
            $record->last_name = $request->last_name;
          //  $record->dept_id = Auth::user()->dept_id;
            $record->notification_number =$request->notification_number;
               
            if ($request->hasFile('bank')) {
                Storage::delete($record->image);
                $image = $request->file('bank');
                $filename = time() . '.' . $image->getClientOriginalExtension();
                $location ='/home/eustedu/certificats.eust.edu.sd/images/record/' . $filename;
                Image::make($image)->resize(500, 600)->save($location);
                $record->image = $filename;
            } 
            
            $record->save();
                
            toastr()->success(trans('messages.Update')); 
            return redirect()->route('records.index');
            }
            catch (\Exception $e){
                return redirect()->back()->withErrors(['error' => $e->getMessage()]);
                }
    }

    
    public function destroy(Request $request)
    {
        try {
            
            $record = Record::where('id',$request->id)->first();
             $record->delete();
             toastr()->error(trans('messages.Delete'));
            return redirect()->route('records.index');
        }

        catch (\Exception $e){
        return redirect()->back()->withErrors(['error' => $e->getMessage()]);
        }

    }

    public function processrecordpay(Request $request)
{ 
        $validatedData = $request->validate([
            'rdio' => 'required',
        ],[

            'rdio.required' =>'يرجي تحديد الحالة المالية لشهادة القيد',
        
        ]);
    
       try {
            $record = Record::where('id',$request->id)->first();
            $record->update([
            'f_status' => $request->rdio,
            'f_note' => $request->note,
                ]);
            }
            
            catch (\Exception $e){
            return redirect()->back()->withErrors(['error' => $e->getMessage()]);
            }

            $user = User::where('id',$record->user_id)->first();
            Notification::send($user, new \App\Notifications\Recordpay);

            toastr()->success(trans('messages.success'));
            return redirect('/records');

}

public function processrecordresult(Request $request)
{
   
        $validatedData = $request->validate([
            'rdio' => 'required',
        ],[

            'rdio.required' =>'يرجي تحديد الحالة الأكاديمية لشهادة القيد',
          
        ]);
    
       try {
            $record = Record::where('id',$request->id)->first();
            $record->update([
            'r_status' => $request->rdio,
            'r_note' => $request->note,
                ]);
            }
            
            catch (\Exception $e){
            return redirect()->back()->withErrors(['error' => $e->getMessage()]);
            }

            $user = User::where('id',$record->user_id)->first();
            Notification::send($user, new \App\Notifications\RecordResult);

            toastr()->success(trans('messages.success'));
            return redirect('/records');

}
    public function ArchiveRecord() 
    {
        $records = Record::onlyTrashed()->get();
        return view('pages.Records.ArchiveRecord',compact('records'));
       
    }
    
     public function RestoRrecord(Request $request) 
    {
       $id=$request->id;
        $Record = Record::withTrashed()->where('id', $id)->restore();
      
        toastr()->success(trans('messages.success'));
        return redirect()->back();
    }
    
     public function CommentRrecord(Request $request)
        {
            try {
                    $record = Record::where('id',$request->id)->first();
                    $record->update([
                    'comments' => $request->comments,
                        ]);
                    }
                    
                    catch (\Exception $e){
                    return redirect()->back()->withErrors(['error' => $e->getMessage()]);
                    }

                    // $user = User::where('id',$record->user_id)->first();
                    // Notification::send($user, new \App\Notifications\RecordResult);

                    toastr()->success(trans('messages.success'));
                    return redirect('/records');

        }


}//end of controller
