<?php

namespace App\Http\Controllers\Drives;

use App\Http\Controllers\Controller;
use App\Models\Drive;
use App\Models\Team;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class Create extends Controller
{



    public function index(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'image' => 'nullable|image|max:1024',
            'phone' => 'required',

        ]);
        $fname = $request->input('fname');
        $lname = $request->input('lname');
        $cname = $request->input('cname');
        $phone = $request->input('phone');
        $email = $request->input('email');
        $new_user = $request->input('new_user');


        if ($new_user == '[New User]') {


            $user = new User();
            $user->first_name = $fname;
            $user->last_name = $lname;
            $user->company_name = $cname;
            $user->phone = $phone;
            $user->email = $email;
            $user->phone = $phone;
            $user->password = Hash::make($phone);
            $user->save();


            $team = Team::find(3);
            $team->users()->attach(
                $newTeamMember = $user,
                ['role' => 'Editor']
            );
            $user->current_team_id = $team->id;
            $user->save();
        } else {


            $user = User::find($request->input('new_user'));
            $user->first_name = $fname;
            $user->last_name = $lname;
            $user->company_name = $cname;
            $user->phone = $phone;
            $user->email = $email;
            $user->phone = $phone;
            $user->save();
        }

        $reason = $request->input('reason');
        $amount_paid = $request->input('amount');
        $drive_name = $request->input('drive_name');
        $serial_no = $request->input('serial_no');
        $model_no = $request->input('model_no');
        $status = $request->input('status');















        $drive = new Drive();
        $drive->name = $drive_name;
        $drive->serial_no = $serial_no;
        $drive->model_no = $model_no;
        $drive->status = $status;
        $drive->user_id = $user->id;
        $drive->image = 'none';
        $drive->screenshot = 'none';
        $drive->progress = 0;
        $drive->reason = $reason;
        $drive->amount_paid = $amount_paid;
        if($request->file('image')!=null)
        $drive->image = $request->file('image')->store('driveImages');
        $drive->save();
        $drive->iaea_no = 'iaea-' . $drive->id . $drive->name[0] . rand(1, 800);
        $drive->save();

        if (Auth::user()->belongsToTeam(\App\Models\Team::find(1))) {
            return redirect()->to('engineers/drives/'.$drive->id);
        } else {
            return redirect()->to('frontdesk/drives/'.$drive->id);
        }
    }
}
