<?php

namespace App\Http\Controllers;

use App\Models\Elevator;
use App\Models\Customer;
use App\Models\Location;
use App\Models\Company;
use App\Imports\ElevatorsImport;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class ElevatorController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $user = Auth::user();
        $company_id = $user->company_id;

        $search = $request->input('search');

        $query = Elevator::with(['customer', 'location'])
            ->where('company_id', $company_id);

        if ($search) {
            $query->where(function($q) use ($search) {
                $q->where('serial_number', 'LIKE', "%{$search}%")
                  ->orWhereHas('customer', function($q2) use ($search) {
                      $q2->where('name', 'LIKE', "%{$search}%");
                  });
            });
        }

        $elevators = $query->orderBy('created_at', 'desc')
            ->paginate(10)
            ->appends(['search' => $search]);

        return view('elevators.index', compact('elevators', 'search'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $user = Auth::user();
        $company_id = $user->company_id;

        // Obtener solo los clientes activos (no los prospectos o leads)
        $customers = Customer::where('company_id', $company_id)
            ->where('is_active', true)
            ->whereIn('status', ['active'])
            ->get();
        $locations = Location::where('company_id', $company_id)->get();

        // جلب موديلات المصاعد النشطة
        $elevatorModels = \App\Models\ElevatorModel::where('company_id', $company_id)
            ->where('is_active', true)
            ->orderBy('name')
            ->get();

        $elevatorTypes = [
            'passenger' => 'مصعد ركاب',
            'freight' => 'مصعد بضائع',
            'hospital' => 'مصعد مستشفى',
            'panoramic' => 'مصعد بانورامي',
            'residential' => 'مصعد سكني',
            'commercial' => 'مصعد تجاري',
            'other' => 'أخرى'
        ];

        $elevatorStatuses = [
            'operational' => 'تشغيلي',
            'under_maintenance' => 'تحت الصيانة',
            'out_of_service' => 'خارج الخدمة',
            'installation' => 'قيد التركيب'
        ];

        return view('elevators.create', compact('customers', 'locations', 'elevatorTypes', 'elevatorStatuses', 'elevatorModels'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $user = Auth::user();
        $company_id = $user->company_id;

        $validator = Validator::make($request->all(), [
            'customer_id' => 'required|exists:customers,id',
            'location_id' => 'nullable|exists:locations,id',
            'serial_number' => [
                'required',
                'string',
                'max:50',
                function ($attribute, $value, $fail) use ($company_id) {
                    // التحقق من فريدية الرقم التسلسلي ضمن نطاق الشركة الواحدة
                    $exists = Elevator::where('company_id', $company_id)
                        ->where('serial_number', $value)
                        ->exists();

                    if ($exists) {
                        $fail('قيمة serial number مُستخدمة من قبل في نفس الشركة.');
                    }
                }
            ],
            'model' => 'nullable|string|max:100',
            'manufacturer' => 'nullable|string|max:100',
            'installation_date' => 'nullable|date',
            'warranty_end_date' => 'nullable|date|after_or_equal:installation_date',
            'free_maintenance_end_date' => 'nullable|date|after_or_equal:installation_date',
            'control_warranty_end_date' => 'nullable|date|after_or_equal:installation_date',
            'machine_warranty_end_date' => 'nullable|date|after_or_equal:installation_date',
            'delivery_date' => 'nullable|date|after_or_equal:installation_date',
            'capacity' => 'nullable|numeric|min:1',
            'floors_count' => 'nullable|integer|min:2',
            'speed' => 'nullable|numeric|min:0.1',
            'price' => $request->status == 'installation' ? 'required|numeric|min:0' : 'nullable|numeric|min:0',
            'type' => 'required|string|in:passenger,freight,hospital,panoramic,residential,commercial,other',
            'status' => 'required|string|in:operational,under_maintenance,out_of_service,installation',
            'specifications' => 'nullable|string',
            'notes' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $user = Auth::user();

        // إذا لم يتم تحديد موقع، قم بإنشاء موقع افتراضي
        if (!$request->location_id) {
            // استخدام معرف العميل المحدد في النموذج
            $customerId = $request->customer_id;

            // البحث عن موقع افتراضي لهذا العميل
            $defaultLocation = Location::where('name', 'موقع افتراضي')
                ->where('company_id', $user->company_id)
                ->where('customer_id', $customerId)
                ->first();

            // إذا لم يتم العثور على موقع افتراضي، قم بإنشاء واحد
            if (!$defaultLocation) {
                $defaultLocation = new Location();
                $defaultLocation->company_id = $user->company_id;
                $defaultLocation->customer_id = $customerId;
                $defaultLocation->name = 'موقع افتراضي';
                $defaultLocation->address = 'عنوان افتراضي';
                $defaultLocation->city = 'المدينة';
                $defaultLocation->state = 'المنطقة';
                $defaultLocation->country = 'البلد';
                $defaultLocation->postal_code = '00000';
                $defaultLocation->contact_person = 'غير محدد';
                $defaultLocation->contact_phone = 'غير محدد';
                $defaultLocation->notes = 'موقع افتراضي تم إنشاؤه تلقائيًا';
                $defaultLocation->save();
            }

            $locationId = $defaultLocation->id;
        } else {
            $locationId = $request->location_id;
        }

        $elevator = new Elevator();
        $elevator->company_id = $user->company_id;
        $elevator->customer_id = $request->customer_id;
        $elevator->location_id = $locationId;
        $elevator->serial_number = $request->serial_number;
        $elevator->model = $request->model;
        $elevator->manufacturer = $request->manufacturer;
        $elevator->installation_date = $request->installation_date;
        $elevator->warranty_end_date = $request->warranty_end_date;
        $elevator->free_maintenance_end_date = $request->free_maintenance_end_date;
        $elevator->control_warranty_end_date = $request->control_warranty_end_date;
        $elevator->machine_warranty_end_date = $request->machine_warranty_end_date;
        $elevator->delivery_date = $request->delivery_date;
        $elevator->capacity = $request->capacity;
        $elevator->floors_count = $request->floors_count;
        $elevator->speed = $request->speed;
        $elevator->price = $request->price;
        $elevator->type = $request->type;
        $elevator->status = $request->status;
        $elevator->specifications = $request->specifications;
        $elevator->notes = $request->notes;
        $elevator->save();

        return redirect()->route('elevators.index')
            ->with('success', 'تم إضافة المصعد بنجاح');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $user = Auth::user();
        $company_id = $user->company_id;

        $elevator = Elevator::with(['customer', 'location', 'maintenanceContracts'])
            ->where('company_id', $company_id)
            ->findOrFail($id);

        $elevatorTypes = [
            'passenger' => 'مصعد ركاب',
            'freight' => 'مصعد بضائع',
            'hospital' => 'مصعد مستشفى',
            'panoramic' => 'مصعد بانورامي',
            'residential' => 'مصعد سكني',
            'commercial' => 'مصعد تجاري'
        ];

        $elevatorStatuses = [
            'operational' => 'تشغيلي',
            'under_maintenance' => 'تحت الصيانة',
            'out_of_service' => 'خارج الخدمة',
            'installation' => 'قيد التركيب'
        ];

        return view('elevators.show', compact('elevator', 'elevatorTypes', 'elevatorStatuses'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $user = Auth::user();
        $company_id = $user->company_id;

        $elevator = Elevator::where('company_id', $company_id)->findOrFail($id);

        // Obtener solo los clientes activos (no los prospectos o leads)
        $customers = Customer::where('company_id', $company_id)
            ->where('is_active', true)
            ->whereIn('status', ['active'])
            ->get();
        $locations = Location::where('company_id', $company_id)->get();

        // جلب موديلات المصاعد النشطة
        $elevatorModels = \App\Models\ElevatorModel::where('company_id', $company_id)
            ->where('is_active', true)
            ->orderBy('name')
            ->get();

        $elevatorTypes = [
            'passenger' => 'مصعد ركاب',
            'freight' => 'مصعد بضائع',
            'hospital' => 'مصعد مستشفى',
            'panoramic' => 'مصعد بانورامي',
            'residential' => 'مصعد سكني',
            'commercial' => 'مصعد تجاري'
        ];

        $elevatorStatuses = [
            'operational' => 'تشغيلي',
            'under_maintenance' => 'تحت الصيانة',
            'out_of_service' => 'خارج الخدمة',
            'installation' => 'قيد التركيب'
        ];

        return view('elevators.edit', compact('elevator', 'customers', 'locations', 'elevatorTypes', 'elevatorStatuses', 'elevatorModels'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $user = Auth::user();
        $company_id = $user->company_id;

        $validator = Validator::make($request->all(), [
            'customer_id' => 'required|exists:customers,id',
            'location_id' => 'nullable|exists:locations,id',
            'serial_number' => [
                'required',
                'string',
                'max:50',
                function ($attribute, $value, $fail) use ($company_id, $id) {
                    // التحقق من فريدية الرقم التسلسلي ضمن نطاق الشركة الواحدة
                    // مع استثناء المصعد الحالي من التحقق
                    $exists = Elevator::where('company_id', $company_id)
                        ->where('serial_number', $value)
                        ->where('id', '!=', $id)
                        ->exists();

                    if ($exists) {
                        $fail('قيمة serial number مُستخدمة من قبل في نفس الشركة.');
                    }
                }
            ],
            'model' => 'nullable|string|max:100',
            'manufacturer' => 'nullable|string|max:100',
            'installation_date' => 'nullable|date',
            'warranty_end_date' => 'nullable|date|after_or_equal:installation_date',
            'free_maintenance_end_date' => 'nullable|date|after_or_equal:installation_date',
            'control_warranty_end_date' => 'nullable|date|after_or_equal:installation_date',
            'machine_warranty_end_date' => 'nullable|date|after_or_equal:installation_date',
            'delivery_date' => 'nullable|date|after_or_equal:installation_date',
            'capacity' => 'nullable|numeric|min:1',
            'floors_count' => 'nullable|integer|min:2',
            'speed' => 'nullable|numeric|min:0.1',
            'price' => $request->status == 'installation' ? 'required|numeric|min:0' : 'nullable|numeric|min:0',
            'type' => 'required|string|in:passenger,freight,hospital,panoramic,residential,commercial,other',
            'status' => 'required|string|in:operational,under_maintenance,out_of_service,installation',
            'specifications' => 'nullable|string',
            'notes' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $user = Auth::user();
        $company_id = $user->company_id;

        // إذا لم يتم تحديد موقع، قم بإنشاء موقع افتراضي
        if (!$request->location_id) {
            // استخدام معرف العميل المحدد في النموذج
            $customerId = $request->customer_id;

            // البحث عن موقع افتراضي لهذا العميل
            $defaultLocation = Location::where('name', 'موقع افتراضي')
                ->where('company_id', $user->company_id)
                ->where('customer_id', $customerId)
                ->first();

            // إذا لم يتم العثور على موقع افتراضي، قم بإنشاء واحد
            if (!$defaultLocation) {
                $defaultLocation = new Location();
                $defaultLocation->company_id = $user->company_id;
                $defaultLocation->customer_id = $customerId;
                $defaultLocation->name = 'موقع افتراضي';
                $defaultLocation->address = 'عنوان افتراضي';
                $defaultLocation->city = 'المدينة';
                $defaultLocation->state = 'المنطقة';
                $defaultLocation->country = 'البلد';
                $defaultLocation->postal_code = '00000';
                $defaultLocation->contact_person = 'غير محدد';
                $defaultLocation->contact_phone = 'غير محدد';
                $defaultLocation->notes = 'موقع افتراضي تم إنشاؤه تلقائيًا';
                $defaultLocation->save();
            }

            $locationId = $defaultLocation->id;
        } else {
            $locationId = $request->location_id;
        }

        $elevator = Elevator::where('company_id', $company_id)->findOrFail($id);
        $elevator->customer_id = $request->customer_id;
        $elevator->location_id = $locationId;
        $elevator->serial_number = $request->serial_number;
        $elevator->model = $request->model;
        $elevator->manufacturer = $request->manufacturer;
        $elevator->installation_date = $request->installation_date;
        $elevator->warranty_end_date = $request->warranty_end_date;
        $elevator->free_maintenance_end_date = $request->free_maintenance_end_date;
        $elevator->control_warranty_end_date = $request->control_warranty_end_date;
        $elevator->machine_warranty_end_date = $request->machine_warranty_end_date;
        $elevator->delivery_date = $request->delivery_date;
        $elevator->capacity = $request->capacity;
        $elevator->floors_count = $request->floors_count;
        $elevator->speed = $request->speed;
        $elevator->price = $request->price;
        $elevator->type = $request->type;
        $elevator->status = $request->status;
        $elevator->specifications = $request->specifications;
        $elevator->notes = $request->notes;
        $elevator->save();

        return redirect()->route('elevators.index')
            ->with('success', 'تم تحديث بيانات المصعد بنجاح');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $user = Auth::user();
        $company_id = $user->company_id;

        $elevator = Elevator::where('company_id', $company_id)->findOrFail($id);

        // Check if elevator has maintenance contracts
        if ($elevator->maintenanceContracts()->count() > 0) {
            return redirect()->route('elevators.index')
                ->with('error', 'لا يمكن حذف المصعد لأنه مرتبط بعقود صيانة');
        }

        $elevator->delete();

        return redirect()->route('elevators.index')
            ->with('success', 'تم حذف المصعد بنجاح');
    }

    /**
     * Show the form for importing elevators from Excel.
     *
     * @return \Illuminate\Http\Response
     */
    public function importForm()
    {
        $user = Auth::user();
        $company_id = $user->company_id;

        // Obtener solo los clientes activos (no los prospectos o leads)
        $customers = Customer::where('company_id', $company_id)
            ->where('is_active', true)
            ->whereIn('status', ['active'])
            ->get();

        return view('elevators.import', compact('customers'));
    }

    /**
     * Import elevators from Excel file.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function import(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'file' => 'required|mimes:xlsx,xls,csv',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        try {
            \Log::info('--- Starting Elevator Import Session ---');
            \Log::info('User: ' . Auth::id() . ' (' . Auth::user()->email . ')');
            
            if (!$request->hasFile('file')) {
                return redirect()->back()->with('error', 'الرجاء اختيار ملف للاستيراد.');
            }

            $import = new ElevatorsImport;
            \Maatwebsite\Excel\Facades\Excel::import($import, $request->file('file'));

            \Log::info('Import Result - Imported: ' . $import->importedCount . ', Skipped: ' . $import->skippedCount . ', Errors Count: ' . count($import->errors));

            if ($import->importedCount === 0 && empty($import->errors)) {
                $message = "لم يتم استيراد أي بيانات. يرجى التأكد من أن الملف يحتوي على البيانات الصحيحة في الصفوف التالية لصف العناوين.";
                return redirect()->back()->with('warning', $message);
            }

            $message = "تم استيراد {$import->importedCount} مصعد بنجاح.";
            if ($import->duplicateCount > 0) {
                $message .= " تم تجاهل {$import->duplicateCount} مصعد مكرر.";
            }
            if ($import->skippedCount > 0) {
                $message .= " تم تخطي {$import->skippedCount} صف لوجود مشاكل.";
            }

            $response = redirect()->route('elevators.index')->with('success', $message);

            if (!empty($import->errors)) {
                \Log::info('Redirecting with ' . count($import->errors) . ' errors.');
                $response->withErrors($import->errors);
            }

            return $response;
        } catch (\Exception $e) {
            $errorMessage = $e->getMessage();
            \Log::error('Error during elevator import: ' . $errorMessage);
            \Log::error($e->getTraceAsString());
            
            // اظهر الخطأ الفني للمستخدم ليتمكن من معرفة سبب الفشل
            return redirect()->back()
                ->with('error', 'حدث خطأ تقني أثناء الاستيراد: ' . $errorMessage)
                ->withErrors([$errorMessage])
                ->withInput();
        }
    }

    /**
     * Download elevator import template in Excel format.
     *
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function downloadExcelTemplate()
    {
        // Create a simple Excel file with the same structure as the CSV template
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // Set headers
        $headers = [
            'customer_id',
            'customer_name',
            'location_id',
            'location_name',
            'serial_number',
            'model',
            'manufacturer',
            'installation_date',
            'warranty_end_date',
            'free_maintenance_end_date',
            'control_warranty_end_date',
            'machine_warranty_end_date',
            'delivery_date',
            'capacity',
            'floors_count',
            'speed',
            'price',
            'type',
            'status',
            'specifications',
            'notes'
        ];

        // Add headers to the first row
        foreach ($headers as $index => $header) {
            $sheet->setCellValueByColumnAndRow($index + 1, 1, $header);
        }

        // Add sample data
        $sampleData = [
            [1, 'شركة الأمل للتجارة', 1, 'الموقع الرئيسي', 'ELV-001', 'Model X', 'Otis', '2023-01-01', '2025-01-01', '2024-01-01', '2024-06-01', '2025-01-01', '2023-02-01', 1000, 10, 1.5, 50000, 'passenger', 'operational', 'Specifications here', 'Notes here'],
            [1, 'شركة الأمل للتجارة', 2, 'موقع الفرع', 'ELV-002', 'Model Y', 'Schindler', '2023-02-01', '2025-02-01', '2024-02-01', '2024-08-01', '2025-02-01', '2023-03-01', 800, 8, 1.2, 45000, 'freight', 'operational', 'Specifications here', 'Notes here']
        ];

        // Add sample data starting from row 2
        foreach ($sampleData as $rowIndex => $rowData) {
            foreach ($rowData as $columnIndex => $value) {
                $sheet->setCellValueByColumnAndRow($columnIndex + 1, $rowIndex + 2, $value);
            }
        }

        // Create a temporary file
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $tempFile = tempnam(sys_get_temp_dir(), 'elevators_import_template');
        $writer->save($tempFile);

        // Return the file as a download
        return response()->download(
            $tempFile,
            'elevators_import_template.xlsx',
            [
                'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'Content-Disposition' => 'attachment; filename="elevators_import_template.xlsx"',
            ]
        )->deleteFileAfterSend(true);
    }
}
