<?php

namespace App\Http\Controllers\Admin;

use Carbon\Carbon;
use App\Models\Data;
use App\Models\Room;
use App\Models\Client;
use App\Models\Examiner;
use App\Models\Whatsapp;
use App\Models\Examination;
use Illuminate\Http\Request;
use App\Models\WhatsAppTemplate;
use App\Services\WhatsAppService;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Jobs\SendWhatsappMessageForOperations;

class OperationController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:operations-list', ['only' => ['index']]);
        $this->middleware('permission:operations-create', ['only' => ['create', 'store']]);
        $this->middleware('permission:operations-edit', ['only' => ['edit', 'update']]);
        $this->middleware('permission:operations-delete', ['only' => ['destroy']]);
    }

    // Display a listing of the examinations
    public function index()
    {
        // تحديد التاريخ الحالي وطرح 30 يوم
        $thirtyDaysAgo = Carbon::now()->subDays(30);

        // استرجاع الفحوصات التي لم تتجاوز 30 يومًا
        $examinations = Examination::with('client')
            ->where('status', 'ارسال الي المشغل')
            ->where('created_at', '>=', $thirtyDaysAgo) // الفحص الذي تم إنشاؤه في آخر 30 يومًا
            ->latest()
            ->get();

        return view('admin.operations.index', compact('examinations'));
    }

    public function show(int $id)
    {
        // Retrieve the examination record by its ID
        $examination = Examination::where('id', $id)->with('details')->first();
        $client = $examination->client;

        // Fetch the data based on room_code for the specific examination
        $user = Auth::user();
        $data = Data::where('room_code', $user->room_code)->get();
        $rooms = Room::all();

        // Prepare an array to hold formatted data
        $formatted_data = [];

        // Format the data as needed (similar to the create method)
        foreach ($data as $item) {
            // Parse the right eye (data_rt)
            preg_match('/R\s*-\s*-\s*-\s*(\d+\.\d+)\s*-\s*-\s*-\s*(\d+\.\d+)\s*-\s*(\d+)/', $item->data_rt, $matches_rt);
            $formatted_rt = [
                'type' => 'R',
                'sph' => $matches_rt[1] ?? 'N/A',  // SPH: -4.50
                'cyl' => $matches_rt[2] ?? 'N/A',  // CYL: -1.00
                'axis' => $matches_rt[3] ?? 'N/A', // Axis: 175
                'lpd' => $item->lpd_rt ?? 'N/A',   // Lens Power Difference for right eye
                'add' => $item->add_rt ?? 'N/A',   // Addition for right eye
            ];

            // Parse the left eye (data_lt)
            preg_match('/L\s*-\s*-\s*-\s*(\d+\.\d+)\s*-\s*-\s*-\s*(\d+\.\d+)\s*-\s*(\d+)/', $item->data_lt, $matches_lt);
            $formatted_lt = [
                'type' => 'L',
                'sph' => $matches_lt[1] ?? 'N/A',  // SPH: -4.25
                'cyl' => $matches_lt[2] ?? 'N/A',  // CYL: -1.75
                'axis' => $matches_lt[3] ?? 'N/A', // Axis: 170
                'lpd' => $item->lpd_lt ?? 'N/A',   // Lens Power Difference for left eye
                'add' => $item->add_lt ?? 'N/A',   // Addition for left eye
            ];

            // Collect formatted data for each item
            $formatted_data[] = [
                'id' => $item->id,
                'room_code' => $item->room_code,
                'right_eye' => $formatted_rt,
                'left_eye' => $formatted_lt,
            ];
        }

        // Fetch other required data for the view
        $clients = Client::all(); // Fetch all clients
        $types = ['نظارات', 'عدسات']; // Example types
        $examiners = Examiner::all();

        // Return the formatted data along with the rest of the information to the view
        return view('admin.operations.show', compact('examination', 'client', 'clients', 'types', 'examiners', 'formatted_data', 'rooms'));
    }







    public function updateCategoryForm($id)
    {
        // جلب الفحص حسب الـ ID
        $examination = Examination::findOrFail($id);
        // تعريف الحالات المتاحة
        $categories = ['a', 'b', 'c', 'd'];

        return view('admin.operations.update-category', compact('examination', 'categories'));
    }

    public function updateCategory(Request $request, $id)
    {
        // جلب الفحص حسب الـ ID
        $examination = Examination::findOrFail($id);
        // تحديث الفئة
        $examination->category = $request->input('category');
        $examination->save();

        // إعادة التوجيه بعد التحديث
        return redirect()->route('admin.operations.index')->with('success', 'تم تحديث الفئة الفئة');
    }

    public function updateStatus(Request $request, $id)
    {
        $examination = Examination::with('client')->findOrFail($id);

        // Validate the status input
        $request->validate([
            'status' => 'required|string',
        ]);

        // Check if the status has changed
        if ($examination->status !== $request->input('status')) {
            // Update status and save
            $examination->status = $request->input('status');
            $examination->save();

            // Check for WhatsApp configuration and send message if needed
            $whatsapp = Whatsapp::first();
            if ($whatsapp && $whatsapp->active == 1) {
                // Dispatch job to send WhatsApp message asynchronously
                SendWhatsappMessageForOperations::dispatch($examination, $request->input('status'));
                return redirect()->route('admin.operations.index')->with('success', 'تم تحديث الحالة وإرسال رسالة WhatsApp بنجاح.');
            } else {
                return redirect()->route('admin.operations.index')->with('success', 'تم تحديث الحالة بنجاح ولكن WhatsApp غير مفعل.');
            }
        }

        // Handle the case where the status is the same as before
        return redirect()->route('admin.operations.index')->with('info', 'الحالة لم تتغير.');
    }




    public function updateSpecial(Request $request, $id)
    {
        // العثور على الفحص باستخدام الـ ID
        $examination = Examination::findOrFail($id);
        // تحديث حقل `special` فقط إذا تم إرساله في الـ request
        if ($request->has('special')) {
            $examination->special = $request->input('special');
        }
        // حفظ التغييرات
        $examination->save();
        // إذا لم تتغير القيمة
        return redirect()->route('admin.operations.index')->with('success', 'تم تحديث نوع الفحص بنجاح');
    }




    public function print($id)
    {
        // Retrieve the examination record by its ID with related client, examiner, and details
        $examination = Examination::with(['client', 'examiner', 'details'])->findOrFail($id);

        // Fetch the client associated with the examination
        $client = $examination->client;

        // Fetch the data based on room_code for the specific examination
        $user = Auth::user();
        $data = Data::where('room_code', $user->room_code)->get();

        // Prepare an array to hold formatted data
        $formatted_data = [];

        // Format the data as needed (similar to the show method)
        foreach ($data as $item) {
            // Parse the right eye (data_rt)
            preg_match('/R\s*-\s*-\s*-\s*(\d+\.\d+)\s*-\s*-\s*-\s*(\d+\.\d+)\s*-\s*(\d+)/', $item->data_rt, $matches_rt);
            $formatted_rt = [
                'type' => 'R',
                'sph' => $matches_rt[1] ?? 'N/A',  // SPH: -4.50
                'cyl' => $matches_rt[2] ?? 'N/A',  // CYL: -1.00
                'axis' => $matches_rt[3] ?? 'N/A', // Axis: 175
                'lpd' => $item->lpd_rt ?? 'N/A',   // Lens Power Difference for right eye
                'add' => $item->add_rt ?? 'N/A',   // Addition for right eye
            ];

            // Parse the left eye (data_lt)
            preg_match('/L\s*-\s*-\s*-\s*(\d+\.\d+)\s*-\s*-\s*-\s*(\d+\.\d+)\s*-\s*(\d+)/', $item->data_lt, $matches_lt);
            $formatted_lt = [
                'type' => 'L',
                'sph' => $matches_lt[1] ?? 'N/A',  // SPH: -4.25
                'cyl' => $matches_lt[2] ?? 'N/A',  // CYL: -1.75
                'axis' => $matches_lt[3] ?? 'N/A', // Axis: 170
                'lpd' => $item->lpd_lt ?? 'N/A',   // Lens Power Difference for left eye
                'add' => $item->add_lt ?? 'N/A',   // Addition for left eye
            ];

            // Collect formatted data for each item
            $formatted_data[] = [
                'id' => $item->id,
                'room_code' => $item->room_code,
                'right_eye' => $formatted_rt,
                'left_eye' => $formatted_lt,
            ];
        }

        // Fetch other required data for the view
        $clients = Client::all(); // Fetch all clients
        $types = ['نظارات', 'عدسات']; // Example types
        $examiners = Examiner::all(); // Fetch all examiners

        // Return the formatted data along with the rest of the information to the print view
        return view('admin.operations.print', compact('examination', 'client', 'clients', 'types', 'examiners', 'formatted_data'));
    }


    public function printSpecial($id)
    {
        $examination = Examination::with(['client', 'examiner'])->findOrFail($id);
        $specials = ['عادي', 'مميز', 'مستعجل', 'تحضير', 'توصيل'];

        // تأكد من أن الفحص مميز
        if ($examination->special) {
            return view('admin.operations.print_special', compact('examination','specials'));
        } else {
            return view('admin.operations.print', compact('examination','specials'));
        }
    }
}
