<?php

namespace App\Http\Controllers\admin;
use Illuminate\Support\Facades\Notification;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\sessionRequest;
use App\Models\client;
use App\Models\file;
use App\Models\lawyer;
use App\Models\court;
use App\Models\session;
use Illuminate\Support\Facades\DB;
use LaravelLocalization;
use App\Traits\allTraits;
use App\Models\User;
use App\Notifications\SessionAdded;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\JsonResponse;

class sessionController extends Controller
{

    public function sessionPost(sessionRequest $request)
    {
        $photo = array();
        if ($files = $request->file('photo')) {
            foreach ($files as $file) {
                $photo_name = md5(rand(1000, 10000));
                $ext = strtolower($file->getClientOriginalExtension());
                $photo_full_name = $photo_name . '.' . $ext;
                $upload_path = 'images/session/';
                $photo_url = $upload_path . $photo_full_name;
                $file->move($upload_path, $photo_full_name);
                $photo[] = $photo_url;
            }
        }
        $session = Session::create([
            'client_id' => $request->client_id,
            'file_id' => $request->file_id,
            'lawyer_id' => $request->lawyer_id,
            'court_id' => $request->court_id,
            'date' => $request->date,
            'photo' => implode('|', $photo),
            'details' => $request->details,
            'postponementDate' => $request->postponementDate,
            'requests' => $request->requests,
            'notes' => $request->notes,

        ]);


        $user = User::get();
        $sessions = session::latest()->first();
        Notification::send($user, new \App\Notifications\SessionAdded($sessions));

     if (strtotime($request->date) < strtotime(date('Y-m-d'))) {
    return redirect()->route('session.archive', ['session_id' => $session->id])->with(['successAdd' => '']);
}

        return redirect()->back()->with(['successAdd' => '']);
    }


   public function getSessions(): JsonResponse
{
    try {
        $sessions = Session::all()->flatMap(function ($session) {
            $events = [];

            // الموعد الأصلي - يظهر فيه الملاحظات فقط
            $events[] = [
                'title' => 'جلسة: ' . $session->clients->name,
                'casenum' => 'رقم القضية: ' . $session->files->caseNum,
                'start' => $session->date,
                'description' => $session->notes ?? 'لا توجد ملاحظات'
            ];

            // الموعد المؤجل - يظهر فيه الطلبات فقط
            if (!empty($session->postponementDate)) {
                $events[] = [
                    'title' => 'جلسة مؤجلة: ' . $session->clients->name,
                    'casenum' => 'رقم القضية: ' . $session->files->caseNum,
                    'start' => $session->postponementDate,
                    'description' => $session->requests ?? 'لا توجد طلبات'
                ];
            }

            return $events;
        });

        return response()->json($sessions);

    } catch (\Exception $e) {
        return response()->json([
            'error' => 'خطأ في جلب الجلسات',
            'message' => $e->getMessage()
        ], 500);
    }
}




    public function getsessionOld($id)
    {
        $files = DB::table("files")->where("client_id", $id)->pluck("caseNum", "id");
        return response()->json($files); // تأكد من استخدام response()->json
    }
    /* for get product ajax */


public function getsession($id, $type)
{
    if ($type === "case") {
        $files = DB::table("files")
            ->where("client_id", $id)
            ->whereNotNull("caseNum") // يمنع null
            ->pluck("caseNum", "id");
    } elseif ($type === "file") {
        $files = DB::table("files")
            ->where("client_id", $id)
            ->whereNotNull("fileCaseNum") // يمنع null
            ->pluck("fileCaseNum", "id");
    } else {
        $files = collect();
    }

    return response()->json($files);
}








    public function addSessions() {
        $files =  file::All();
        $clients =  client::All();
        $sessions =  session::All();
        $lawyers =  lawyer::All();
        $courts =  court::All();
        return view('admin.dashboard.addSession', compact('clients', 'files', 'sessions', 'lawyers', 'courts'));
    }


    public function AllSessions() {
        $user = auth()->user();

        // حذف الجلسات القديمة بشكل أوتوماتيك قبل العرض
        $oldSessions = Session::where('date', '<', date('Y-m-d'))->get();

        foreach ($oldSessions as $session) {
            $session->delete();  // نفس فكرتك في دالة archiveSessions
        }

        // بعدها نجيب الجلسات النشطة
        if ($user->hasRole('Admin')) {
            $sessions = Session::orderBy('created_at', 'desc')->get();
        } else {
            $allowedCaseIds = $user->permissions->pluck('name')->map(function ($permission) {
                return str_replace('ارقام القضايا', '', $permission);
            })->toArray();

            $sessions = Session::whereIn('file_id', $allowedCaseIds)
                               ->orderBy('created_at', 'desc')
                               ->get();
        }

        $files = file::all();
        $clients = client::all();
        $lawyers = lawyer::all();
        $courts = court::all();

        return view('admin.dashboard.sessions', compact('clients', 'files', 'sessions', 'lawyers', 'courts'));
    }





    public function archiveSessions($sessions_id)
    {

        $sessions = session::find($sessions_id);

        if (!$sessions)
            return redirect()->back()->with(['error' => __('messages.news not exist')]);

        $sessions->delete();

        return redirect()
            ->route('AllSessions')
            ->with(['successArchive' => __('messages.news deleted successfully')]);
    }


public function sessionsTrashed()
{


    $sessions = Session::onlyTrashed()
        ->orderBy('date', 'desc')  // التاريخ الأحدث أولًا
        ->get();

    return view('admin.dashboard.sessionsArchive', compact('sessions'));
}





    public function DeleteSession($sessions_id)
    {

        session::where('id', $sessions_id)->withTrashed()->forceDelete();
        return redirect()->back()

        ->with(['successDelete' => __('messages.news deleted successfully')]);

    }





    public function editSession($sessions_id)
    {

        $sessions = session::find($sessions_id);  // search in given table id only
        if (!$sessions)
            return redirect()->back();
        $sessions = session::all()->find($sessions_id);
        $files =  file::All();
        $clients =  client::All();
        $lawyers =  lawyer::All();
        $courts =  court::All();
        return view('admin.dashboard.editSession', compact('sessions', 'files', 'clients', 'lawyers', 'courts'));

    }



    public function UpdateSession(sessionRequest $request, $sessions_id)
    {

        $session = session::find($sessions_id);
        if (!$session)
            return redirect()->back();

        //update data



        $session->update([
            'client_id' => $request -> client_id,
            'file_id' => $request -> file_id,
            'laywer_id' => $request -> laywer_id,
            'court_id' => $request -> court_id,
            'date' => $request -> date,
            'photo' => implode('|', $photo),
            'details' => $request -> details,
            'postponementDate' => $request->postponementDate,
            'requests' => $request->requests,
            'notes' => $request -> notes,
        ]);


        return redirect()->back()->with(['successEdit' => ' تم التحديث بنجاح ']);

    }






public function sessionDetails($sessions_id)
{
    // البحث عن الجلسة باستخدام ID، مع جلب الجلسات المحذوفة أيضًا باستخدام withTrashed()
    $sessions = session::withTrashed()->find($sessions_id);

    // إذا لم يتم العثور على الجلسة
    if (!$sessions) {
        return redirect()->back()->with('error', 'الجلسة غير موجودة');
    }

    // عرض التفاصيل
    return view('admin.dashboard.sessionDetails', compact('sessions'));
}







}
