<?php

namespace App\Http\Controllers;

use App\Models\Demande;
use App\Models\ShareHolder;
use App\Http\Requests\StoreShareHolderRequest;
use App\Http\Requests\UpdateShareHolderRequest;

class ShareHolderController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreShareHolderRequest $request)
    {

        foreach($request['shareholders'] as $shareHolder){
            ShareHolder::create([
                'demande_id' => $request['demande_id'],
                'full_name' => $shareHolder['full_name'],
                'shares' => $shareHolder['shares'],
                'shares_old' => (isset($request['is_origin']) && $request['is_origin'] == true) ? $shareHolder['shares'] : null,
                'GSM' => isset($shareHolder['GSM']) ? $shareHolder['GSM'] : null,
                'is_origin' => isset($request['is_origin']) == true ? $request['is_origin'] : false,
            ]);
        }
        $demande = Demande::find($request['demande_id']);
        $demande->update([
            'nb_total_actions' => $request['total_shares'],
        ]);
        return ShareHolder::where('demande_id',$request['demande_id'])->get();
    }

    /**
     * Display the specified resource.
     */
    public function show(ShareHolder $shareHolder)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(ShareHolder $shareHolder)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateShareHolderRequest $request, $shareHolder)
    {
        $shareHolderModel = ShareHolder::find($shareHolder);

        $shareHolderModel->update([
            'full_name' => $request->full_name,
            'shares' => $request->shares,
            'GSM' => $request->GSM
        ]);

        return response()->json(ShareHolder::find($shareHolder));
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(ShareHolder $shareHolder)
    {
        //
    }
}
