<?php

namespace App\Http\Controllers;

use App\Models\branch;
use App\Models\Salesman;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Models\SalesmanHasImages;
use PhpParser\Node\Stmt\TryCatch;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class SalesmanController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $salesmans = Salesman::with('branch')->orderBy('id','desc')->paginate(5);
        return view('salesman/all', compact('salesmans'));
        //return $salesmans;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $branch = branch::all();
        return view('salesman/new', compact('branch'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|unique:salesmans',
            'dob' => 'required|date|before:today',
            'nic' => 'string|required|unique:salesmans',
            'mobile' => 'string|nullable',
            'land' => 'string|nullable',
            'email' => 'email|nullable',
            'address' => 'string|nullable|max:200',
            'note' => 'string|nullable|max:200',
            'branch' => 'required|gt:0',
            'picture' => 'image|nullable|mimes:jpeg,jpg,png|max:2048',
            'document_1' => 'image|nullable|mimes:jpeg,jpg,png|max:2048',
            'document_2' => 'image|nullable|mimes:jpeg,jpg,png|max:2048'
        ]);

        $salesman = [
            'name' => $request->name,
            'dob' => $request->dob,
            'nic' => $request->nic,
            'mobile' => $request->mobile,
            'land' => $request->land,
            'email' => $request->email,
            'address' => $request->address,
            'note' => $request->note,
            'branch_id' => $request->branch

        ];


        if ($request->hasFile('picture')) {
            $imageName = $request->file('picture')->store('images', 'public');
            $salesman['profile_picture_name'] = $imageName;
        }


        try {
            DB::beginTransaction();

            $salesman = Salesman::create($salesman);
            $salesman->code = 'SLM-' . str_pad($salesman->id, 5, '0', STR_PAD_LEFT); // LN-001, LN-002 etc.
            $salesman->save();


            //if exist document one then save and upload
            if ($request->hasFile('document_1')) {
                $image_name = $request->file('document_1')->store('images', 'public');



                $salesman_has_document = [
                    'salesman_id' => $salesman->id,
                    'image_name' => $image_name,
                ];

                $salesman_has_document = SalesmanHasImages::create($salesman_has_document);
                $salesman_has_document->code = 'SLD-' . str_pad($salesman_has_document->id, 5, '0', STR_PAD_LEFT); // LN-001, LN-002 etc.
                $salesman_has_document->save();
            }



            //if exist document two then save and upload
            if ($request->hasFile('document_2')) {
                $image_name = $request->file('document_2')->store('images', 'public');



                $salesman_has_document = [
                    'salesman_id' => $salesman->id,
                    'image_name' => $image_name,
                ];

                $salesman_has_document = SalesmanHasImages::create($salesman_has_document);
                $salesman_has_document->code = 'SLD-' . str_pad($salesman_has_document->id, 5, '0', STR_PAD_LEFT); // LN-001, LN-002 etc.
                $salesman_has_document->save();
            }

            DB::commit();

            return redirect('salesman/all')->with('success', 'Salesman data saved successfully');
        } catch (\Throwable $e) {
            DB::rollBack();
            return redirect('salesman/all')->with('success', 'Error: ' . $e->getMessage());
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Salesman  $salesman
     * @return \Illuminate\Http\Response
     */
    public function show(Salesman $salesman, $id)
    {
        $salesman  = Salesman::with('branch')->find($id);
        $branches = branch::all();
        return view('salesman/view', compact('salesman', 'branches'));
        //return compact('salesman','branches');

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Salesman  $salesman
     * @return \Illuminate\Http\Response
     */
    public function edit(Salesman $salesman, $id)
    {
        $branches = branch::all();
        $salesman = Salesman::with('images')->find($id);
        return view('salesman/edit', compact('branches', 'salesman'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Salesman  $salesman
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Salesman $salesman, $id)
    {

        $request->validate([
            'name' => ['required', 'string', Rule::unique('salesmans', 'name')->ignore($id)],
            'dob' => 'required|date|before:today',
            'nic' => ['string', 'required', Rule::unique('salesmans', 'nic')->ignore($id)],
            'mobile' => 'string|nullable',
            'land' => 'string|nullable',
            'email' => 'email|nullable',
            'address' => 'string|nullable|max:200',
            'note' => 'string|nullable|max:200',
            'branch' => 'required|gt:0',
            'picture' => 'image|nullable|mimes:jpeg,jpg,png|max:2048',
            'document_1' => 'image|nullable|mimes:jpeg,jpg,png|max:2048',
            'document_2' => 'image|nullable|mimes:jpeg,jpg,png|max:2048'
        ]);

        $salesman = Salesman::findOrFail($id);

        $salesman->name = $request->name;
        $salesman->nic = $request->nic;
        $salesman->dob = $request->dob;
        $salesman->mobile = $request->mobile;
        $salesman->land = $request->land;
        $salesman->address = $request->address;
        $salesman->email = $request->email;
        $salesman->branch_id = $request->branch;
        $salesman->note = $request->note;



        //check profile picture is selected
        if ($request->hasFile('picture')) {
            //check previouse image is exist
            if (($salesman->profile_picture_name != '' || $salesman->profile_picture_name != null) && Storage::disk('public')->exists($salesman->profile_picture_name)) {
                Storage::disk('public')->delete($salesman->profile_picture_name);
            }
            $imageName = $request->file('picture')->store('images', 'public');
            $salesman->profile_picture_name = $imageName;
        } elseif ($request->has('picture_remove')) {
            if (($salesman->profile_picture_name != '' || $salesman->profile_picture_name != null) && Storage::disk('public')->exists($salesman->profile_picture_name)) {
                Storage::disk('public')->delete($salesman->profile_picture_name);
                $salesman->profile_picture_name = '';
            }
        }


        $salesman->update();

        //document one
        if ($request->hasFile('document_1')) {
            //check previouse image is exist
            if (count($salesman->images) > 0) {
                if (($salesman->images[0]->image_name != '' || $salesman->images[0]->image_name != null) && Storage::disk('public')->exists($salesman->images[0]->image_name)) {
                    Storage::disk('public')->delete($salesman->images[0]->image_name);
                }

                $salesman_has_document = SalesmanHasImages::findOrFail($salesman->images[0]->id);
                $imageName = $request->file('document_1')->store('images', 'public');
                $salesman_has_document->image_name = $imageName;
                $salesman_has_document->update();
            } else {
                $imageName = $request->file('document_1')->store('images', 'public');
                $salesman_has_document = [
                    'salesman_id' => $salesman->id,
                    'image_name' => $imageName,
                ];

                $salesman_has_document = SalesmanHasImages::create($salesman_has_document);
                $salesman_has_document->code = 'SLD-' . str_pad($salesman_has_document->id, 5, '0', STR_PAD_LEFT); // LN-001, LN-002 etc.
                $salesman_has_document->save();
            }
        } elseif ($request->has('document_1_remove')) {
            if (count($salesman->images) > 0) {
                if (($salesman->images[0]->image_name != '' || $salesman->images[0]->image_name != null) && Storage::disk('public')->exists($salesman->images[0]->image_name)) {
                    Storage::disk('public')->delete($salesman->images[0]->image_name);
                }
                $salesman_has_document = SalesmanHasImages::findOrFail($salesman->images[0]->id);
                $salesman_has_document->delete();
            }
        }

        //document 2
        if ($request->hasFile('document_2')) {
            //check previouse image is exist
            if (count($salesman->images) > 1) {
                if (($salesman->images[1]->image_name != '' || $salesman->images[1]->image_name != null) && Storage::disk('public')->exists($salesman->images[1]->image_name)) {
                    Storage::disk('public')->delete($salesman->images[1]->image_name);
                }

                $salesman_has_document = SalesmanHasImages::findOrFail($salesman->images[1]->id);
                $imageName = $request->file('document_2')->store('images', 'public');
                $salesman_has_document->image_name = $imageName;
                $salesman_has_document->update();
            } else {
                $imageName = $request->file('document_2')->store('images', 'public');
                $salesman_has_document = [
                    'salesman_id' => $salesman->id,
                    'image_name' => $imageName,
                ];

                $salesman_has_document = SalesmanHasImages::create($salesman_has_document);
                $salesman_has_document->code = 'SLD-' . str_pad($salesman_has_document->id, 5, '0', STR_PAD_LEFT); // LN-001, LN-002 etc.
                $salesman_has_document->save();
            }
        } elseif ($request->has('document_2_remove')) {
            if (count($salesman->images) > 1) {
                if (($salesman->images[1]->image_name != '' || $salesman->images[1]->image_name != null) && Storage::disk('public')->exists($salesman->images[1]->image_name)) {
                    Storage::disk('public')->delete($salesman->images[1]->image_name);
                }
                $salesman_has_document = SalesmanHasImages::findOrFail($salesman->images[1]->id);
                $salesman_has_document->delete();
            }
        }

        return redirect('salesman/all')->with('success', 'Salesman data updatead successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Salesman  $salesman
     * @return \Illuminate\Http\Response
     */
    public function destroy(Salesman $salesman, $id)
    {
        //
        $salesman  = Salesman::findOrFail($id);

        foreach ($salesman->images as $images) {
            if (($images->image_name != '' || $images->image_name != null) && Storage::disk('public')->exists($images->image_name)) {
                Storage::disk('public')->delete($images->image_name);
            }
        }
        $salesman->images()->delete();
        $salesman->delete();

        return redirect('salesman/all')->with('success', 'Salesman data removed successfully');
    }
}
