<?php

namespace App\Http\Controllers;

use App\Models\Demande;
use App\Http\Requests\StoreDemandeRequest;
use App\Http\Requests\UpdateDemandeRequest;
use App\Models\Ticket;
use App\Models\User;
use App\Services\TwilioService;
use App\Services\VeriffService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Auth as FacadesAuth;

class DemandeController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    protected $twilioService;
    protected $veriffService;
    public function __construct(VeriffService $veriffService,TwilioService $twilioService)
    {
        $this->twilioService = $twilioService;
        $this->veriffService = $veriffService;
    }
    public function index()
    {
        return Demande::with('user')->get();
    }

    public function getWithSharesHolders($id)
    {
        return Demande::with('shareholders')->findOrFail($id);
    }

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreDemandeRequest $request)
    {
        $demande = Demande::create([
            'user_id' => Auth::id(),
            'bce_data' => json_encode($request->bce_data),
            'enterprise_number' => $request->enterprise_number,
            'langue_entreprise' => $request->bce_data['lang_entre'],
        ]);
        return response()->json(['demande_id'=>$demande->id,'demande'=>$demande]);
        
    }

    /**
     * Display the specified resource.
     */
    public function show(Demande $demande)
    {
        $demande = $demande->load('dirigeants');
        return response()->json(['demande'=>$demande]);
    }

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

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateDemandeRequest $request, Demande $demande)
    {
        // $demande = Demande::find($demande);
        // if(!$demande){
        //     return response()->json(['message'=>'the demande does not existe'],401);
        // }
        $demande = Demande::where('id',$demande->id)->update($request->all());
        return response()->json(['demande'=>$demande]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Demande $demande)
    {
        //
    }
    public function updateGSM(UpdateDemandeRequest $request,Demande $demande){
        Demande::where('id',$demande->id)->update($request->all());
        // create veriff session
        $session = $this->veriffService->createSession();
        if($session['session_id']){
            $d = Demande::where('id',$demande->id)->update(['veriff_session'=>$session['session_id'],'veriff_url'=>$session['verification_url']]);
            if($d){
                // send SMS to GSM
                $to = $request->GSM;
                $link = $session['verification_url'];
                // $message = "Cliquez ici pour vérifier votre compte : $link. Cela nous permettra de confirmer votre identité.\nAktly.";
                $message = "Cliquez ici pour vérifier votre identité : $link.";
                $this->twilioService->sendSms($to,$message);
                // return response()->json($d);
            }
        }else{
            return response()->json(['error'=>"Something want wrong !"]);
        }
    }

    public function userDemandes(){
        $demandes = Demande::where('user_id',Auth::id())->get();
        return response()->json($demandes);
    }
    public function lastDemandes(){
        $demandes = Demande::with(['user'])->orderBy('created_at','desc')->take(5)->get();
        return response()->json($demandes);
    }
    public function count(){
        $demandes = Demande::count();
        $tickets = Ticket::count();
        $users = User::count();
        return response()->json(['demandes'=>$demandes,'tickets'=>$tickets,'users'=>$users]);
    }
    public function countClient(){
        $demandes = Demande::where('user_id',Auth::user()->id)->count();
        $tickets = Ticket::whereHas('demande', function ($query) {
            $query->where('user_id', Auth::id());
        })->with('demande.user')->count();;
        return response()->json(['demandes'=>$demandes,'tickets'=>$tickets]);
    }
    public function getMyDemandes(){
        return Demande::with('user')->where('user_id',Auth::user()->id)->get();
    }
    public function changeState(Request $request, $demande_id)
    {
        $state = $request['state']; // or $request->state
    
        // Example: update the Demande model
        $demande = Demande::findOrFail($demande_id)->update([
            'status' => $state == true ? 'résolu' : 'annulé'
        ]);
        // $demande->state = $state;
        // $demande->save();
    
        return response()->json([
            'message' => 'State updated successfully',
            'data' => $demande
        ]);
    }

    public function storeText(Request $request, $demande_id)
    {
        $text = $request->text;
        //afficher texte dans log
        \Log::info('Text to store: ' . $text);
        if($text!= null && $text != '') {
            $demande = Demande::findOrFail($demande_id);
            $demande->pub_text = $text;
            $demande->save();
        }
    
        return response()->json([
            'message' => 'Text stored successfully',
        ]);
    }
}
