<?php

namespace App\Http\Controllers;

use App\Models\Province;
use App\Models\SetadProvince;
use App\Models\ResearchDev;
use Hekmatinasser\Verta\Facades\Verta;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Models\RandDMembers;
use App\Models\NewRandD;
use Illuminate\Support\Facades\DB;
use Webpatser\Uuid\Uuid;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use App\Models\RandDVoting;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\URL;
use App\Models\RandDVotingPaperAnswer;

class NewRandDCtrl extends Controller
{
    public function homepage()
    {
        $allrecords = NewRandD::where('project_status', '1')->orderBy('created_at', 'DESC')->get();
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $allrecords
        ], 200);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if (auth()->user()) {
            auth()->user()->addActivityComplete(1059);
        }
        $allrecords = NewRandD::all();



        if (Auth::user()->can('member-RandD')) {
            foreach ($allrecords as $item) {
                $this->addItemPermissions(false, false, true, true, true, $item);
            }
        } else {
            if (Auth::user()->can('staff-RandD')) {
                foreach ($allrecords as $item) {
                    $this->addItemPermissions(true, true, false, true, true, $item);
                }
            } else {
                // permission for ostani users
                if (Auth::user()->province_id) {
                    foreach ($allrecords as $item) {
                        if ($item->province_id == Auth::user()->province_id) {
                            $this->addItemPermissions(true, true, false, true, false, $item);
                        } else {
                            $this->addItemPermissions(false, false, false, true, false, $item);
                        }
                    }
                } else {
                    // permission for setadi users
                    foreach ($allrecords as $item) {
                        if ($item->province_id == Auth::user()->setad_id) {
                            $this->addItemPermissions(true, true, false, true, false, $item);
                        } else {
                            $this->addItemPermissions(false, false, false, true, false, $item);
                        }
                    }
                }
            }
        }



       

        //// status for voting project
        foreach ($allrecords as $item) {
            //// admin
            if (Auth::check() && Auth::check() && Auth::user()->can('staff-RandD')) {
                
                /// aya proje rad shode ya na
                if ($item->project_status == 3) {
                    $item->setAttribute('canReject', false);
                    $item->setAttribute('startVote', false);
                    $item->setAttribute('isStartVote', false);
                    $item->setAttribute('resultVote', true);
                }else {
                    ///// check mikone ke betune start kone ya na
                    if (!RandDVoting::where('status', '2')->first() && !RandDVoting::where('project_id', $item->id)->first()) {
                        $item->setAttribute('startVote', true);
                        $item->setAttribute('canReject', true);
                    } else {
                        $item->setAttribute('startVote', false);
                    }
    
                    if (RandDVoting::where('project_id', $item->id)->where('status', '2')->first()) {
                        $item->setAttribute('isStartVote', true);
                    } else {
                        $item->setAttribute('isStartVote', false);
                    }
    
    
                    if (RandDVoting::where('project_id', $item->id)->where('status', '4')->first()) {
                        $item->setAttribute('resultVote', true);
                    } else {
                        $item->setAttribute('resultVote', false);
                    }
                }


            } elseif (Auth::check() && Auth::user()->can('member-RandD')) {
                $item->setAttribute('isStartVote', false);
                $item->setAttribute('startVote', false);
                $item->setAttribute('canReject', false);


                if (RandDVoting::where('project_id', $item->id)->where('status', '2')->first()) {
                    $item->setAttribute('Voting', true);
                    $getVote = RandDVoting::where('project_id', $item->id)->where('status', '2')->first();
                    if (! RandDVotingPaperAnswer::where('vote_id', $getVote->id)->where('user_id', Auth::user()->id)->first()) {
                        $url = URL::to('/randd/voting') . '/'. $getVote->id;
                        $item->setAttribute('urlVoting', $url);

                        $item->setAttribute('allowVoting', true);
                    } else {
                        $item->setAttribute('allowVoting', false);
                    }
                } else {
                    
                    $item->setAttribute('Voting', false);
                    $item->setAttribute('allowVoting', false);
                }
                if (RandDVoting::where('project_id', $item->id)->where('status', '4')->first()) {
                    $item->setAttribute('resultVote', true);
                } else {
                    $item->setAttribute('resultVote', false);
                }
            } else {
                $item->setAttribute('canReject', false);
                $item->setAttribute('Voting', false);
                $item->setAttribute('allowVoting', false);
                $item->setAttribute('isStartVote', false);
                $item->setAttribute('startVote', false);
                if (RandDVoting::where('project_id', $item->id)->where('status', '4')->first()) {
                    $item->setAttribute('resultVote', true);
                } else {
                    $item->setAttribute('resultVote', false);
                }
            }
        }
        
        foreach ($allrecords as $item) {
            switch ($item->project_status) {
                case '1':
                    $item->setAttribute('project_status_fa', 'در حال بررسی');
                    break;
                case '2':
                    $item->setAttribute('project_status_fa', 'خاتمه یافته');
                    break;
                case '3':
                    $item->setAttribute('project_status_fa', 'رد شده');
                    break;
                default:
                    break;
            }
        }

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $allrecords,
        ], 200);
    }

    //// add permission array to all rows in data
    public function addItemPermissions($isCud, $reqFin, $isVoting, $votingResult, $votingUserResult, $item)
    {
        $item->perm = [
            'isCUD' => $isCud,
            'requestFinish' => $reqFin,
            'isVoting' => $isVoting,
            'votingResult' => $votingResult,
            'votingUsersResult' => $votingUserResult,
        ];
    }

    public function store(Request $request)
    {
        
        // Set automatic province persian name in table
        if ($request->province_id > 49) {
            $prov_item = SetadProvince::find($request->province_id);
            $province_fa = $prov_item->name_fa;
        } else {
            $prov_item = Province::find($request->province_id);
            $province_fa = $prov_item->name_fa;
            if ($request->province_id < 10) {
            }
        }
        // Make Unique Code
        $uuid = Str::uuid();

        // Upload Final report 1
        if ($request->has('proj_rfp_file')) {
            $file = $request->file('proj_rfp_file');
            $destinationPath = 'storage/rand/rfp_file/' . now()->year . '/' . now()->month . '/';
            $filename = $uuid . '-one.' . $file->getClientOriginalExtension();
            $file->move($destinationPath, $filename);
        }

        switch ($request->domain_id) {
            case "1":
                $domain_fa = 'راهداری';
                break;
            case "2":
                $domain_fa = 'حمل و نقل';
                break;
            case "3":
                $domain_fa = 'فناوری و سیستم هوشمند';
                break;
            case "4":
                $domain_fa = 'منابع انسانی';
                break;
            case "5":
                $domain_fa = 'روستایی';
                break;
        }

        // Store Data
        $create = NewRandD::create([
            'title' => $request->title,
            'province_id' => $request->province_id,
            'province_fa' => $province_fa,
            'domain_id' => $request->domain_id,
            'domain_fa' => $domain_fa,
            'project_amount' => $request->project_amount,
            'credit_status' => $request->credit_status,
            'rfp_file' => $destinationPath . $filename,
            'unique_code' => $uuid,
            'fname_creator' => $request->fname_creator,
            'lname_creator' => $request->lname_creator,
            'phone_creator' => $request->phone_creator,
            'proj_credit_resourse' => $request->proj_credit_resourse ?? null
        ]);

        // TODO: upload to server and add unique_id table in database new randd
        $year = Verta::now()->format('y');
        $temp = ($request->province_id < 10) ?"0".$request->province_id:$request->province_id ;
        $unique_id = '1' . $request->domain_id .$temp. $year . $create->id;
        $create->update(['unique_id' => $unique_id]);

        $getRandD = NewRandD::where('id', $create->id)->get();

        Auth::user()->addActivity("پروژه با کد یکتا {$create->id} در بخش تحقیق و توسعه ایجاد شد.");



        return response()->json([
           'message' => 'success',
           'data' => $getRandD
        ], 200);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        $d = NewRandD::find($id);
        
        $msg = ' پروژه‌ پیشنهادی کمیته، با کد یکتا ' . $d->unique_id . '(' .$d->title.')، توسط ' . Auth::user()->first_name . ' ' . Auth::user()->last_name . ' حذف شد.';
        
        Auth::user()->activityLogs()->create([
            'description' => $msg
        ]);

        $d->delete(); 

        return response()->json([
           'message' => 'با موفقیت حذف شد'
        ], 200);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(NewRandD $newRandD, Request $request)
    {
        // Set automatic province persian name in table
        if ($request->province_id > 49) {
            $prov_item = SetadProvince::find($request->province_id);
            $province_fa = $prov_item->name_fa;
        } else {
            $prov_item = Province::find($request->province_id);
            $province_fa = $prov_item->name_fa;
        }

        // Make Unique Code
        $uuid = Str::uuid();
        // Upload Final report 1
        $rfp_file = $newRandD->rfp_file;

        if ($request->has('proj_rfp_file')) {
            $file = $request->file('proj_rfp_file');
            $destinationPath = 'storage/rand/rfp_file/' . now()->year . '/' . now()->month . '/';
            $filename = $uuid . '-one.' . $file->getClientOriginalExtension();
            $file->move($destinationPath, $filename);
            $rfp_file = $destinationPath . $filename;
        }

        switch ($request->domain_id) {
            case "1":
                $domain_fa = 'راهداری';
                break;
            case "2":
                $domain_fa = 'حمل و نقل';
                break;
            case "3":
                $domain_fa = 'فناوری و سیستم هوشمند';
                break;
            case "4":
                $domain_fa = 'منابع انسانی';
                break;
            case "5":
                $domain_fa = 'روستایی';
                break;
        }

        // Store Data
        $newRandD->update([
            'title' => $request->title,
            'province_id' => $request->province_id,
            'province_fa' => $province_fa,
            'domain_id' => $request->domain_id,
            'domain_fa' => $domain_fa,
            'project_amount' => $request->project_amount,
            'credit_status' => $request->credit_status,
            'unique_code' => $uuid,
            'fname_creator' => $request->fname_creator,
            'lname_creator' => $request->lname_creator,
            'phone_creator' => $request->phone_creator,
            'proj_credit_resourse' => $request->proj_credit_resourse ?? null,
            'rfp_file' => $rfp_file
        ]);

        // TODO: upload to server and add unique_id table in database new randd
        $year = Verta::now()->format('y');
        $temp = ($request->province_id < 10) ?"0".$request->province_id:$request->province_id ;
        $unique_id = '1' . $request->domain_id .$temp. $year . $newRandD->id;
        $newRandD->update(['unique_id' => $unique_id]);


        $getRandD = NewRandD::whereId($newRandD->id)->first();

        $msg = ' پروژه‌ پیشنهادی کمیته، با کد یکتا ' . $getRandD->unique_id . '(' .$getRandD->title.')، توسط ' . Auth::user()->first_name . ' ' . Auth::user()->last_name . ' ویرایش شد.';
        
        Auth::user()->activityLogs()->create([
            'description' => $msg
        ]);


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

    public function reject(NewRandD $newRandD, Request $request)
    {
        if (auth()->user()) {
            auth()->user()->addActivityComplete(1065);
        }
        // Update Data
        $newRandD->reject_description = $request->reject_description;
        $newRandD->project_status = 3;
        $newRandD->save();

        $msg = ' پروژه‌ پیشنهادی کمیته، با کد یکتا ' . $newRandD->unique_id . '(' .$newRandD->title.')، توسط ' . Auth::user()->first_name . ' ' . Auth::user()->last_name . 'رد شد.';
        
        Auth::user()->activityLogs()->create([
            'description' => $msg
        ]);


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

    public function operationStatus($id)
    {
        $new = NewRandD::find($id);
        $new->update([
           'operation_status' => 1
        ]);

        return response()->json([
           'message' => 'ثبت فرایند با موفقیت انجام شد.',
           'data' => $new
        ]);
    }

    public function search(Request $request)
    {
        switch ($request->type) {
            case "1":
                $research = new ResearchDev();
                $data = $research->where("contract_status", 1)->where('project_title', 'like', '%'.$request->search.'%')->orderByDesc('id')->get();
                break;
            case "2":
                $research = new ResearchDev();
                $data = $research->where("contract_status", 2)->where('project_title', 'like', '%'.$request->search.'%')->orderByDesc('id')->get();
                break;
            case "3":
                $research = new NewRandD();
                $data = $research->where('title', 'like', '%'.$request->search.'%')->orderByDesc('id')->get();
                break;
        }

        return response()->json([
            'status'       => 'succeed',
            'message'      => 'yes',
            'status_bool'  => 1,
            'data'         => $data,
        ], 200);
    }


    public function statics(Request $request)
    {
        $comite = NewRandD::all()->count();
        $ejra = ResearchDev::where('contract_status', 1)->get()->count();
        $end = ResearchDev::where('contract_status', 2)->get()->count();
        // $members = RandDMembers::all();
        return response()->json([
            'message' => 'success',
            'statics' => [
                'comite' => $comite,
                'ejra'   => $ejra,
                'end'    => $end
            ],
            'data' => [
                // 'aazaye_comite' => $members,
            ]
        ]);
    }
}