<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\License;
use App\Models\Application;
use App\Models\Setting;
use DateTime;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;


use Yajra\DataTables\Facades\DataTables;


class LicenseController extends Controller
{
    const LICENSE_VALIDITY_IN_MONTHS = 6;

    public function index(Request $request)
    {
        $licenses = License::latest()->get();
        $applications = Application::latest()->get();
        $setting = Setting::latest()->first();
        
        $licenseValidityInMonths = self::LICENSE_VALIDITY_IN_MONTHS;

        if ($setting) {
            $licenseValidityInMonths = $setting->license_validity_in_months;
        }       
        
        if ($request->ajax()) {

            return Datatables::of($licenses)
                    ->addIndexColumn()
                    ->addColumn('action', function($row){

                        $btn = '<a href="javascript:void(0)" data-id="' . $row->id . '" data-toggle="tooltip" data-original-title="Edit" class="edit btn btn-primary btn-sm editlicense">Edit</a>';
                        $btn .= ' <a href="javascript:void(0)" data-id="' . $row->id . '" data-toggle="tooltip" data-original-title="View" class="btn btn-info btn-sm viewlicense">View</a>';
                        $btn .= ' <a href="javascript:void(0)" style="display: none;" data-id="' . $row->id . '" data-toggle="tooltip" data-original-title="Delete" class="delete btn btn-danger btn-sm deletelicense">Delete</a>';
                        return $btn;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }
      
        return view('admin.licenses.index',compact('licenses','applications','licenseValidityInMonths'));
    }

    public function create()
    {
        return view('admin.licenses.create');
    }

    public function store(Request $request)
    {
        $user = Auth::user();
        $dealerId = Auth::id();

        $validatedData = $request->validate([
            'payment' => 'required|string',
            'phone' => 'nullable|string',
            'price' => 'nullable|string',
            'expire_date' => 'nullable|string',
            'coupon' => 'nullable|string',
            'disabled' => 'nullable|string',
            'application_id' => 'required',
        ]);
        
        if ($request->input('expire_date') == null) {
            $license_validity_in_months = Setting::latest()->first()->license_validity_in_months;
            if ($license_validity_in_months !== null) {
                // Initialisez la date actuelle
                $currentDate = new DateTime();
                // Ajoutez 6 mois à la date actuelle
                $expireDate = $currentDate->modify('+' . $license_validity_in_months . ' months');
                // Obtenez le timestamp de la date d'expiration
                $expireTimestamp = $expireDate->getTimestamp();
                $validatedData['expire_date'] = $expireTimestamp; 
            }
        }

        $timestamp = strtotime($request->input('expire_date'));

        //$validatedData['code'] = 'ABC2DE';
       // $validatedData['expire_date'] =  $timestamp;
        $validatedData['active_date'] =  now(); 
        $validatedData['dealer_id'] = $dealerId;
        

        $license = License::create($validatedData);
        return response()->json(['success'=>'License saved successfully.']);  
    }

    public function show(License $license)
    {
        $licenseValidityInMonths = self::LICENSE_VALIDITY_IN_MONTHS;
        $setting = Setting::latest()->first();

        if ($setting) {
            $licenseValidityInMonths = $setting->license_validity_in_months;
        }  

        return view('admin.licenses.show', compact('license','licenseValidityInMonths'));
    }

    public function edit($id)
    {
        $license = License::findOrFail($id);
        return response()->json($license);  // Ajoutez le signe dollar devant $project
    }

    public function update(Request $request, License $license)
    {
        $validatedData = $request->validate([
            'payment' => 'required|string',
            'phone' => 'nullable|string',
            'price' => 'nullable|string',
            'expire_date' => 'nullable|string',
            'coupon' => 'nullable|string',
            'disabled' => 'nullable|string',
            'application_id' => 'required',
        ]);

        $license->update($validatedData);

        return response()->json(['message' => 'Projet mis à jour avec succès']);
    }

    public function destroy(License $license)
    {
        $license->delete();
        return response()->json(['message' => 'Projet supprimé avec succès']);
    }

    public function indexbyser(Request $request)
    {
        $user = Auth::user();
        $id = Auth::id();

        $licenses = License::where('dealer_id', $id)->get();
        $applications = Application::latest()->get();
        $setting = Setting::latest()->first();
        
        $licenseValidityInMonths = self::LICENSE_VALIDITY_IN_MONTHS;

        if ($setting) {
            $licenseValidityInMonths = $setting->license_validity_in_months;
        }       
        
        if ($request->ajax()) {

            return Datatables::of($licenses)
                    ->addIndexColumn()
                    ->addColumn('action', function($row){

                        $btn = '<a href="javascript:void(0)" data-id="' . $row->id . '" data-toggle="tooltip" data-original-title="Edit" class="edit btn btn-primary btn-sm editlicense">Edit</a>';
                        $btn .= ' <a href="javascript:void(0)" data-id="' . $row->id . '" data-toggle="tooltip" data-original-title="View" class="btn btn-info btn-sm viewlicense">View</a>';
                        $btn .= ' <a href="javascript:void(0)" style="display: none;" data-id="' . $row->id . '" data-toggle="tooltip" data-original-title="Delete" class="delete btn btn-danger btn-sm deletelicense">Delete</a>';
                        return $btn;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }
      
        return view('admin.licenses.indexbyuser',compact('licenses','applications','licenseValidityInMonths'));
    }


    public function states(Request $request)
    {
        $query = License::query();

        $applications = Application::latest()->get();
        $setting = Setting::latest()->first();

        $coupon = $request->input('coupon');
        // Récupération des dates du formulaire
        $start_date = $request->input('start_date');
        $end_date = $request->input('end_date');
        $application_id = $request->input('application_id');



        // Validation et formatage des dates
         // Validation et formatage des dates et heures
        if ($start_date) {
            $start_date = Carbon::createFromFormat('Y-m-d\TH:i', $start_date);
        }
        if ($end_date) {
            $end_date = Carbon::createFromFormat('Y-m-d\TH:i', $end_date);
        }

        // Conditions de la requête pour les dates et heures
        if ($start_date && $end_date) {
            $query->whereBetween('active_date', [$start_date, $end_date]);
        } elseif ($start_date) {
            $query->where('active_date', '>=', $start_date);
        } elseif ($end_date) {
            $query->where('active_date', '<=', $end_date);
        }


        // Condition pour le coupon
        if (!is_null($coupon)) {
            $query->where('coupon', $coupon);
        }

        $application_id = $request->input('application_id');
        
        if (!is_null($application_id)) {
            $query->where('application_id', $application_id);
        }
        

        $licenses = $query->get();
             
        
        if ($request->ajax()) {

            return Datatables::of($licenses)
                    ->addIndexColumn()
                    ->addColumn('action', function($row){

                        $btn = '<a href="javascript:void(0)" data-id="' . $row->id . '" data-toggle="tooltip" data-original-title="Edit" class="edit btn btn-primary btn-sm editlicense">Edit</a>';
                        $btn .= ' <a href="javascript:void(0)" data-id="' . $row->id . '" data-toggle="tooltip" data-original-title="View" class="btn btn-info btn-sm viewlicense">View</a>';
                        $btn .= ' <a href="javascript:void(0)" style="display: none;" data-id="' . $row->id . '" data-toggle="tooltip" data-original-title="Delete" class="delete btn btn-danger btn-sm deletelicense">Delete</a>';
                        return $btn;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }
      
        return view('admin.licenses.states',compact('licenses','applications'));
    }
}
