<?php

namespace App\Http\Controllers;

use App\Models\Registration;
use App\Models\Participant;
use App\Models\Attendance;
use App\Models\states;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Facades\Crypt;

use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Writer\PngWriter;

class attendancecontroller extends Controller
{
    //
     public function index()
    {
        //
       /* $banksData=banks_lkp::join('users', 'users.id', '=', 'banks_lkps.user_id')
                    ->get(['banks_lkps.*','users.name']);
*/
        $Participant = Participant::all();
        $Attendance = Attendance::all();
        $states = states::all();
        return view('registration.Attendance',compact('Participant','Attendance','states'));
    }

     public function store(Request $request)
    {
        $validated = $request->validate([
            'Full_Name'          => 'required|string|max:255',
            'E_mail'             => 'required|email|unique:registrations,E_mail',
            'Tel'                => 'required|numeric',
            'state_id'           => 'required|exists:states,id',
            'participant_id'     => 'required|exists:participants,id',
            'attendance_id'      => 'required|exists:attendances,id',
            'Job'                => 'required|string|max:255',
            'Identification'     => 'required|numeric',
            'Identification_File'=> 'required|file|mimes:jpg,png,pdf|max:2048',
        ]);

        // Handle file upload
        if ($request->hasFile('Identification_File')) {
            $path = $request->file('Identification_File')->store('ids', 'public');
            $validated['Identification_File'] = $path;
        }

        Registration::create($validated);

        return redirect()->back()->with('success', 'تم التسجيل بنجاح!');
    }

    public function getData()
{
    
    $data = DB::table('registrations')
    ->join('states', 'states.id', '=', 'registrations.state_id')
    ->join('participants', 'participants.id', '=', 'registrations.participant_id')
    ->join('attendances', 'attendances.id', '=', 'registrations.attendance_id')
    ->get(['registrations.*','states.StatesName','participants.Participant_name','attendances.attendances_type']);

return DataTables::of($data)
    ->addColumn('file', function($row) {
        if ($row->Identification_File) {
            return '<a href="'.asset('storage/'.$row->Identification_File).'" target="_blank">عرض الملف</a>';
        }
        return 'لا يوجد ملف';
    })
   ->addColumn('Card', function($row) {
        if ($row->id) {
            $guest_id = Crypt::encrypt($row->id);
            return '<a href="'.asset('attendance/card/'.$guest_id).'" 
           target="_blank" 
           style="display:inline-block;
                  padding:6px 12px;
                  background:#007bff;
                  color:#fff;
                  border-radius:4px;
                  text-decoration:none;">
          <i class="fa fa-id-card"></i>
        </a>';
        }
        return 'لا يوجد ملف';
    })

    ->rawColumns(['file','Card']) // allow HTML rendering
    ->make(true);
}

            public function getcard($guest_id)
                {
                  $Gst_id = Crypt::decrypt($guest_id);

                $Gust_data = DB::table('registrations')
        ->join('states', 'states.id', '=', 'registrations.state_id')
        ->join('participants', 'participants.id', '=', 'registrations.participant_id')
        ->join('attendances', 'attendances.id', '=', 'registrations.attendance_id')
        ->where('registrations.id', '=', $Gst_id)
        ->first([
            'registrations.*',
            'states.StatesName',
            'participants.Participant_name',
            'attendances.attendances_type'
        ]);

        $GstIdencrypt = Crypt::encrypt($Gust_data->id);
    // Step 2: Generate QR code
    $result = Builder::create()
        ->writer(new PngWriter())
        //->data("Name: {$Gust_data->id}\nID: {$Gust_data->Identification}\nPhone: {$Gust_data->Tel}")
        ->data("{$GstIdencrypt}")
        ->size(300)
        ->margin(10)
        ->logoPath(public_path('images/fmoh.png')) // optional logo
        ->logoResizeToWidth(100)
        ->logoResizeToHeight(100)
        ->build();

    // Step 3: Save QR code image
    $fileName = 'qrcode_' . $GstIdencrypt . '.png';
    $filePath = storage_path('app/public/' . $fileName);
    file_put_contents($filePath, $result->getString());

    // Step 4: Pass data to view
    return view('registration.Id_card',compact('Gust_data','GstIdencrypt'));


                    
                    
                }

}

/*

->addColumn('barcode', function($row) {
    $result = Builder::create()
        ->writer(new PngWriter())
        ->data($row->Identification) // or any unique field you want encoded
        ->size(300)
        ->margin(10)
        ->logoPath(public_path('images/fmoh.png')) // optional logo
        ->logoResizeToWidth(150)
        ->logoResizeToHeight(150)
        ->build();

    // Save file into public storage with unique name
    $fileName = 'qrcode_' . $row->id . '.png';
    $filePath = storage_path('app/public/' . $fileName);
    file_put_contents($filePath, $result->getString());

    // Return public URL for browser
    $url = asset('storage/' . $fileName);
    return '<img src="' . $url . '" alt="barcode" width="120" />';
})


*/