<?php

namespace App\Http\Controllers;

use App\Models\Province;
use Hekmatinasser\Verta\Facades\Verta;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Models\ResearchDev;
use Illuminate\Support\Facades\Auth;
use App\Models\SetadProvince;
use phpDocumentor\Reflection\Utils;
use Webpatser\Uuid\Uuid;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;

class ResearchDevController extends Controller
{
    public function researchMembers()
    {
        return response()->json([
            'message' => 'success',
            'data' => \App\Models\RandDMembers::all()
        ]);
    }

    public function interfaceMembers()
    {
        $interface_members_list = [
            [
            'member_duty'=>"استان هرمزگان",
            'member_url'=>"storage/rand/interface/1.jpg",
            'member_name'=>"محمدنجيب پيشرو",
            ],
            [
            'member_duty'=>"استان سیستان و بلوچستان",
            'member_url'=>"storage/rand/interface/2.jpg",
            'member_name'=>"مرضیه افضلی",
            ],
            [
            'member_duty'=>"استان يزد",
            'member_url'=>"storage/rand/interface/3.jpg",
            'member_name'=>"مهديه حسن آبادي",
            ],
            [
            'member_duty'=>"استان آذربایجان شرقی",
            'member_url'=>"storage/rand/interface/4.jpg",
            'member_name'=>"سارا سرنج",
            ],
            [
            'member_duty'=>"استان خراسان رضوی",
            'member_url'=>"storage/rand/interface/5.jpg",
            'member_name'=>"علی زایرزاده",
            ],
            [
            'member_duty'=>"استان گیلان",
            'member_url'=>"storage/rand/interface/6.jpg",
            'member_name'=>"نیما آجلی لاهیجی",
            ],
            [
            'member_duty'=>"استان بوشهر",
            'member_url'=>"storage/rand/interface/7.jpg",
            'member_name'=>"سیداحمدرضاکازرونیان",
            ],
            [
            'member_duty'=>"استان خراسان شمالی",
            'member_url'=>"storage/rand/interface/8.jpg",
            'member_name'=>"حامد معروف",
            ],
            [
            'member_duty'=>"استان کردستان",
            'member_url'=>"storage/rand/interface/9.jpg",
            'member_name'=>"محمد وریا  خورده بینان",
            ],
            [
            'member_duty'=>"استان سمنان",
            'member_url'=>"storage/rand/interface/10.jpg",
            'member_name'=>"امین دوست محمدی",
            ],
            [
            'member_duty'=>"استان همدان",
            'member_url'=>"storage/rand/interface/11.jpg",
            'member_name'=>"علیرضا سیاوشی",
            ],
            [
            'member_duty'=>"استان مازندران",
            'member_url'=>"storage/rand/interface/12.jpg",
            'member_name'=>"معصومه اميري",
            ],
            [
            'member_duty'=>"استان چهارمحال و بختیاری",
            'member_url'=>"storage/rand/interface/13.jpg",
            'member_name'=>"محمد حسین پور قندعلی",
            ],
            [
            'member_duty'=>"استان اردبیل",
            'member_url'=>"storage/rand/interface/14.jpg",
            'member_name'=>"زهرا آذرنوش",
            ],
            [
            'member_duty'=>"استان کرمانشاه",
            'member_url'=>"storage/rand/interface/15.jpg",
            'member_name'=>"فرزین صیادی",
            ],
            [
            'member_duty'=>"استان قم",
            'member_url'=>"storage/rand/interface/16.jpg",
            'member_name'=>"سارا واعظی",
            ],
            [
            'member_duty'=>"استان خراسان جنوبی",
            'member_url'=>"storage/rand/interface/17.jpg",
            'member_name'=>"مسعود قاسمی",
            ],
            [
            'member_duty'=>"استان اذربایجان غربی",
            'member_url'=>"storage/rand/interface/18.jpg",
            'member_name'=>"میکائیل مینائی",
            ],
            [
            'member_duty'=>"استان فارس",
            'member_url'=>"storage/rand/interface/19.jpg",
            'member_name'=>"وحید مکرم",
            ],
            [
            'member_duty'=>"استان مرکزی",
            'member_url'=>"storage/rand/interface/20.jpg",
            'member_name'=>"صدیقه فهیم زاده",
            ],
            [
            'member_duty'=>"استان اصفهان",
            'member_url'=>"storage/rand/interface/21.jpg",
            'member_name'=>"مریم تاکی",
            ],
            [
            'member_duty'=>"استان گلستان",
            'member_url'=>"storage/rand/interface/22.jpg",
            'member_name'=>"ابوطالب جلینی کرد",
            ],
            [
            'member_duty'=>"استان کهگیلویه و بویراحمد",
            'member_url'=>"storage/rand/interface/23.jpg",
            'member_name'=>"سعیده محقق زاده",
            ],
            [
            'member_duty'=>"استان قزوین",
            'member_url'=>"storage/rand/interface/24.jpg",
            'member_name'=>"مهدی سلطانی",
            ],
            [
            'member_duty'=>"استان خوزستان",
            'member_url'=>"storage/rand/interface/25.jpg",
            'member_name'=>"رسول متولیان زاده",
            ],
            [
            'member_duty'=>"اداره كل ایرانشهر",
            'member_url'=>"storage/rand/interface/26.jpg",
            'member_name'=>"پروانه راوش",
            ],
            [
            'member_duty'=>"استان زنجان دکتری عمران",
            'member_url'=>"storage/rand/interface/27.jpg",
            'member_name'=>"علی مدقالچی",
            ],
            [
            'member_duty'=>"استان تهران",
            'member_url'=>"storage/rand/interface/28.jpg",
            'member_name'=>"راحله باهو",
            ],
            [
            'member_duty'=>"استان البرز",
            'member_url'=>"storage/rand/interface/29.jpg",
            'member_name'=>"پیمان بختیاری",
            ],
            [
            'member_duty'=>"استان کرمان",
            'member_url'=>"storage/rand/interface/30.jpg",
            'member_name'=>"زینب پورجمشیدی",
            ],
            [
            'member_duty'=>"استان ايلام",
            'member_url'=>"storage/rand/interface/31.jpg",
            'member_name'=>"حسين بلوچيان",
            ],
            [
            'member_duty'=>"اداره كل شاهرود",
            'member_url'=>"storage/rand/interface/32.jpg",
            'member_name'=>"فاطمه حسين پور",
            ],
            [
            'member_duty'=>"استان لرستان",
            'member_url'=>"storage/rand/interface/33.jpg",
            'member_name'=>"ابوذر احمدي فيروزآبادي",
            ],
            [
            'member_duty'=>"استان کرمان جنوب",
            'member_url'=>"storage/rand/interface/34.jpg",
            'member_name'=>"سجاد شهابی نیا",
            ],
            [
            'member_duty'=>"مرکز مدیریت راهها",
            'member_url'=>"storage/rand/interface/B (1).jpg",
            'member_name'=>"سید احسان جعفری نسب",
            ],
            [
            'member_duty'=>"دفتر ترانزیت",
            'member_url'=>"storage/rand/interface/B (1).jpeg",
            'member_name'=>"یونس افتخاری یگانه",
        ],
        [
            'member_duty'=>"دفتر مديريت بحران و تجهيز ماشين آلات",
            'member_url'=>"storage/rand/interface/B (2).jpg",
            'member_name'=>"سيد محسن هاشمي",
        ],
        [
            'member_duty'=>"دفتر فناوری اطلاعات",
            'member_url'=>"storage/rand/interface/B (3).jpg",
            'member_name'=>"رضابیابانی اردکانی",
        ],
        [
            'member_duty'=>"دفتر برنامه و بودجه",
            'member_url'=>"storage/rand/interface/B (4).jpg",
            'member_name'=>"حمیدرضا فلاح کهن",
        ],
        [
            'member_duty'=>"دفتر حمل و نقل کالا",
            'member_url'=>"storage/rand/interface/B (5).jpg",
            'member_name'=>"محمد سرایی",
        ],
        [
            'member_duty'=>"دفترنگهداری راههای روستایی و فرعی",
            'member_url'=>"storage/rand/interface/B (6).jpg",
            'member_name'=>"سجاد میرزایی",
        ],
        [
            'member_duty'=>"دفتر فنی و امور پیمان ها",
            'member_url'=>"storage/rand/interface/B (7).jpg",
            'member_name'=>"امیر مسعود منتظري",
        ],
        [
            'member_duty'=>"نگهداری راه ها",
            'member_url'=>"storage/rand/interface/B (8).jpg",
            'member_name'=>"امیررضا خانمحمدی",
        ],
        [
            'member_duty'=>"دفتر آمار، ایمنی و ترافیک",
            'member_url'=>"storage/rand/interface/B (9).jpg",
            'member_name'=>"محمد پگاه رشيدبيگي",
        ],
        [
            'member_duty'=>"دفترساخت و توسعه راههای فرعی و روستایی",
            'member_url'=>"storage/rand/interface/B (10).jpg",
            'member_name'=>"امیر مهرآرا",
        ],
        [
            'member_duty'=>"دفتر سرمایه گذاری",
            'member_url'=>"storage/rand/interface/B (11).jpg",
            'member_name'=>"فاطمه باقري خليلي",
        ],
        [
            'member_duty'=>"دفتر حمل و نقل مسافر",
            'member_url'=>"storage/rand/interface/B (12).jpg",
            'member_name'=>"علي نفري",
            ],
        ];

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

    public function homepage()
    {
        $allrecords = ResearchDev::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(Request $request)
    {
        if (auth()->user()) {
            auth()->user()->addActivityComplete(1055);
        }
        $allrecords = ResearchDev::all();
        
        

        if (Auth::check()) {

            if (Auth::user()->can('member-RandD')) {
                foreach ($allrecords as $item) {
                    $this->addItemPermissions(false, false, true, true, true, $item);
                }
            } elseif (Auth::user()->can('staff-RandD')) {
                foreach ($allrecords as $item) {
                $this->addItemPermissions(true, true, true, true, true, $item);
                }
            } elseif (Auth::user()->can('province-office-RandD')) {
                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);
                        }
                    }
                }
            } else {
                foreach ($allrecords as $item) {
                    $this->addItemPermissions(false, false, false, true, false, $item);
                }
            }
        } else {
            foreach ($allrecords as $item) {
                $this->addItemPermissions(false, false, false, true, false, $item);
            }
        }

        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,
        ];
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    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;
        }

        // Make Unique Code
        $uuid = Str::uuid();


        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
        $new = ResearchDev::create([
            'project_title' => $request->project_title,
            'province_id' => $request->province_id,
            'province_fa' => $province_fa,
            'project_agent' => $request->project_agent,
            'contract_amount' => $request->contract_amount,
            'contract_date' => $request->contract_date,
            'contract_number' => $request->contract_number,
            'contract_term' => $request->contract_term,
            'domain_fa' => $domain_fa,
            'domain_id' => $request->domain_id,
            'contract_status' => $request->contract_status,
            'uuid' => $uuid,
        ]);



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



        // Upload Final report 1
        if ($request->has('file1')) {
            $file1 = $request->file('file1');
            $destinationPath1 = 'storage/rand/1/' . now()->year . '/' . now()->month . '/';
            $filename1 = $uuid . '-one.' . $file1->getClientOriginalExtension();
            ResearchDev::find($new->id)->update([
                'final_report_one' => $destinationPath1 . $filename1
            ]);
            $file1->move($destinationPath1, $filename1);
        }

        // Upload Final report 2
        if ($request->has('file2')) {
            $file2 = $request->file('file2');
            $destinationPath2 = 'storage/rand/2/' . now()->year . '/' . now()->month . '/';
            $filename2 = $uuid . '-two.' . $file2->getClientOriginalExtension();
            ResearchDev::find($new->id)->update([
                'final_report_two' => $destinationPath2 . $filename2
            ]);
            $file2->move($destinationPath2, $filename2);
        }
        if ($request->has('file3')) {
            $file3 = $request->file('file3');
            $destinationPath3 = 'storage/rand/3/' . now()->year . '/' . now()->month . '/';
            $filename3 = $uuid . '-three.' . $file3->getClientOriginalExtension();
            ResearchDev::find($new->id)->update([
                'final_report_three' => $destinationPath3 . $filename3
            ]);
            $file3->move($destinationPath3, $filename3);
        }
        // Upload Final report 2
        if ($request->has('file4')) {
            $file4 = $request->file('file4');
            $destinationPath4 = 'storage/rand/4/' . now()->year . '/' . now()->month . '/';
            $filename4 = $uuid . '-four.' . $file4->getClientOriginalExtension();
            ResearchDev::find($new->id)->update([
                'final_report_four' => $destinationPath4 . $filename4
            ]);
            $file4->move($destinationPath4, $filename4);
        }

        $getNew = ResearchDev::where('id', $new->id)->get();

        $msg = ' پروژه های در حال اجرا/خاتمه یافته تحقیق و توسعه، با کد یکتا ' . $new->unique_id . '(' .$new->title.')، توسط ' . Auth::user()->first_name . ' ' . Auth::user()->last_name . ' ثبت شد.';
        
        Auth::user()->activityLogs()->create([
            'description' => $msg
        ]);

        // Auth::user()->addActivity("پروژه مطالعاتی با آیدی {$new->id} ثبت شد.");



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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $getRD = ResearchDev::find($id);

        // 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;
        }

        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;
        }

        $rd = ResearchDev::find($id)->update([
            'project_title' => $request->project_title,
            'province_id' => $request->province_id,
            'province_fa' => $province_fa,
            'project_agent' => $request->project_agent,
            'contract_amount' => $request->contract_amount,
            'contract_date' => $request->contract_date,
            'contract_number' => $request->contract_number,
            'contract_term' => $request->contract_term,
            'contract_status' => $request->contract_status,
            'domain_id' => $request->domain_id,
            'domain_fa' => $domain_fa ?? null,
            'contract_status' => $request->contract_status,
        ]);


        // $year = Verta::now()->format('y');
        // $temp = ($request->province_id < 10) ?"0".$request->province_id:$request->province_id ;
        // $unique_id = '2' . $request->domain_id .$temp. $year . $id;
        // ResearchDev::find($id)->update(['unique_id' => $unique_id]);

        $getDataForUUID = ResearchDev::where('id', $id)->first();
        $uuid = $getDataForUUID->uuid;

        // // Upload Final report 1
        if ($request->has('final_report_one')) {
            $file1 = $request->file('final_report_one');
            $destinationPath1 = 'storage/rand/1/' . now()->year . '/' . now()->month . '/';
            $filename1 = $uuid . '-one.' . $file1->getClientOriginalExtension();
            
            $file1->move($destinationPath1, $filename1);
            ResearchDev::find($id)->update([
                'final_report_one' => $destinationPath1 . $filename1
            ]);
        }

        // Upload Final report 2
        if ($request->has('final_report_two')) {
            $file2 = $request->file('final_report_two');
            $destinationPath2 = 'storage/rand/2/' . now()->year . '/' . now()->month . '/';
            $filename2 = $uuid . '-two.' . $file2->getClientOriginalExtension();
            $file2->move($destinationPath2, $filename2);
            ResearchDev::find($id)->update([
                'final_report_two' => $destinationPath2 . $filename2
            ]);
        }
        if ($request->has('final_report_three')) {
            $file3 = $request->file('final_report_three');
            $destinationPath3 = 'storage/rand/3/' . now()->year . '/' . now()->month . '/';
            $filename3 = $uuid . '-three.' . $file3->getClientOriginalExtension();
            $file3->move($destinationPath3, $filename3);
            ResearchDev::find($id)->update([
                'final_report_three' => $destinationPath3 . $filename3
            ]);
        }
        // Upload Final report 2
        if ($request->has('final_report_four')) {
            $file4 = $request->file('final_report_four');
            $destinationPath4 = 'storage/rand/4/' . now()->year . '/' . now()->month . '/';
            $filename4 = $uuid . '-four.' . $file4->getClientOriginalExtension();
            $file4->move($destinationPath4, $filename4);
            ResearchDev::find($id)->update([
                'final_report_four' => $destinationPath4 . $filename4
            ]);
        }

        $d = ResearchDev::find($id);
        $msg = ' پروژه های در حال اجرا/خاتمه یافته تحقیق و توسعه، با کد یکتا ' . $d->unique_id . '(' .$d->title.')، توسط ' . Auth::user()->first_name . ' ' . Auth::user()->last_name . ' ویرایش شد.';
        
        Auth::user()->activityLogs()->create([
            'description' => $msg
        ]);

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        $d = ResearchDev::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);
    }


    public function download(Request $request, $id)
    {
        $getData = ResearchDev::find($id);

        $file1 =  $getData->final_report_one;
        $link1 = 'https://rms.rmto.ir' . $file1;

        $file2 =  $getData->final_report_two;
        $link2 = 'https://rms.rmto.ir' . $file2;

        return response()->json([
            'data' => [
                'File 1' => $link1,
                'File 2' => $link2,
            ]
        ]);
    }

    public function processRegistration(Request $request, $id)
    {
        $rd = ResearchDev::where('id', $id)->update([
            'project_status' => 1
        ]);

        $getData = ResearchDev::where('id', $id)->get();

        return response()->json([
            'message' => 'وضعیت پروژه به ثبت فرایند تغییر کرد.',
            'data' => $getData,
        ]);
    }
}
