<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Company;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;

class CompanyController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $user = Auth::user();

        // If user has a company_id, they can only see their own company
        // Only users with no company_id (null) can see all companies
        if ($user->company_id === null) {
            $companies = Company::latest()->paginate(10);
        } else {
            // All users with a company_id can only see their company
            $companies = Company::where('id', $user->company_id)->paginate(10);
        }

        return view('companies.index', compact('companies'));
    }

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

        // Check if this is first-time setup (user has no company)
        $isFirstTimeSetup = !$user->company_id;

        // Only users with super_admin position can create companies, OR users without company (first-time setup)
        if (!$isFirstTimeSetup && $user->position != 'super_admin') {
            return redirect()->route('companies.index')
                ->with('error', 'ليس لديك صلاحية لإنشاء شركات جديدة. فقط مستخدمي سوبر أدمن أو المستخدمين الجدد يمكنهم إنشاء شركات.');
        }

        return view('companies.create', compact('isFirstTimeSetup'));
    }

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

        // Check if this is first-time setup (user has no company)
        $isFirstTimeSetup = !$user->company_id;

        // Only users with super_admin position can create companies, OR users without company (first-time setup)
        if (!$isFirstTimeSetup && $user->position != 'super_admin') {
            return redirect()->route('companies.index')
                ->with('error', 'ليس لديك صلاحية لإنشاء شركات جديدة. فقط مستخدمي سوبر أدمن أو المستخدمين الجدد يمكنهم إنشاء شركات.');
        }

        // If first-time setup, check if user already created a company
        if ($isFirstTimeSetup) {
            $existingCompany = Company::whereHas('users', function ($query) use ($user) {
                $query->where('users.id', $user->id);
            })->first();

            if ($existingCompany) {
                return redirect()->route('dashboard')
                    ->with('error', 'لقد قمت بإنشاء شركة بالفعل.');
            }
        }

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'name_en' => 'nullable|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'nullable|string|max:20',
            'mobile' => 'nullable|string|max:20',
            'website' => 'nullable|string|max:255|url',
            'address' => 'nullable|string|max:255',
            'address_en' => 'nullable|string|max:255',
            'city' => 'nullable|string|max:100',
            'state' => 'nullable|string|max:100',
            'country' => 'nullable|string|max:100',
            'postal_code' => 'nullable|string|max:20',
            'cr_number' => 'nullable|string|max:50',
            'vat_number' => 'nullable|string|max:50',
            'tax_number' => 'nullable|string|max:50',
            'currency' => 'required|string|size:3',
            'tax_rate' => 'required|numeric|min:0|max:100',
            'vat_rate' => 'nullable|numeric|min:0|max:100',
            'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'notes' => 'nullable|string',
        ]);

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

        // Generate slug and database prefix
        $slug = Str::slug($request->name);
        $databasePrefix = strtolower(substr(preg_replace('/[^a-zA-Z0-9]/', '', $request->name), 0, 10)) . '_';

        // Handle logo upload
        $logoPath = null;
        if ($request->hasFile('logo')) {
            $logoPath = $request->file('logo')->store('company_logos', 'public');
        }

        // Create company
        $company = Company::create([
            'name' => $request->name,
            'name_en' => $request->name_en,
            'slug' => $slug,
            'domain' => $request->domain,
            'database_prefix' => $databasePrefix,
            'cr_number' => $request->cr_number,
            'vat_number' => $request->vat_number,
            'logo' => $logoPath,
            'email' => $request->email,
            'phone' => $request->phone,
            'mobile' => $request->mobile,
            'website' => $request->website,
            'address' => $request->address,
            'address_en' => $request->address_en,
            'city' => $request->city,
            'state' => $request->state,
            'country' => $request->country,
            'postal_code' => $request->postal_code,
            'tax_number' => $request->tax_number,
            'currency' => $request->currency,
            'tax_rate' => $request->tax_rate,
            'vat_rate' => $request->vat_rate ?? 15.00, // Default VAT rate in Saudi Arabia
            'is_active' => true,
            'notes' => $request->notes,
            'subscription_plan' => 'basic',
        ]);

        // If first-time setup, link user to company and assign manager role
        if ($isFirstTimeSetup) {
            // Update user's company_id
            $user->company_id = $company->id;
            $user->save();

            // Assign company_manager role to user
            $managerRole = \App\Models\Role::where('slug', 'company_manager')->first();
            if (!$managerRole) {
                // If company_manager doesn't exist, try admin role
                $managerRole = \App\Models\Role::where('slug', 'admin')->first();
            }

            if ($managerRole && !$user->roles->contains($managerRole->id)) {
                $user->roles()->attach($managerRole->id);
            }

            // منح المستخدم صلاحيات إدارة المستخدمين والأدوار والصلاحيات
            $permissions = [
                'manage_users',
                'manage_roles',
                'manage_permissions',
                'view_users',
                'create_users',
                'edit_users',
                'delete_users',
                'view_roles',
                'create_roles',
                'edit_roles',
                'delete_roles'
            ];

            foreach ($permissions as $permissionSlug) {
                $permission = \App\Models\Permission::where('slug', $permissionSlug)->first();
                if ($permission && !$user->permissions->contains($permission->id)) {
                    $user->permissions()->attach($permission->id, [
                        'granted' => true,
                        'source' => 'company_creation'
                    ]);
                }
            }

            return redirect()->route('dashboard')
                ->with('success', 'تم إنشاء الشركة بنجاح! مرحباً بك في نظام إدارة المصاعد.');
        }

        return redirect()->route('companies.show', $company->id)
            ->with('success', 'تم إنشاء الشركة بنجاح.');
    }

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

        // جميع المستخدمين يمكنهم رؤية جميع الشركات

        // Get company statistics
        $statistics = [
            'branches_count' => 0,
            'users_count' => 0,
            'customers_count' => 0,
            'elevators_count' => 0,
            'contracts_count' => 0,
            'invoices_count' => 0,
        ];

        try {
            $statistics['branches_count'] = $company->branches()->count();
        } catch (\Exception $e) {
        }

        try {
            $statistics['users_count'] = $company->users()->count();
        } catch (\Exception $e) {
        }

        try {
            $statistics['customers_count'] = $company->customers()->count();
        } catch (\Exception $e) {
        }

        try {
            $statistics['elevators_count'] = $company->elevators()->count();
        } catch (\Exception $e) {
        }

        try {
            if (Schema::hasTable('maintenance_contracts')) {
                $statistics['contracts_count'] = $company->maintenance_contracts()->count();
            }
        } catch (\Exception $e) {
        }

        try {
            if (Schema::hasTable('invoices')) {
                $statistics['invoices_count'] = $company->invoices()->count();
            }
        } catch (\Exception $e) {
        }

        return view('companies.show', compact('company', 'statistics'));
    }

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

        // جميع المستخدمين يمكنهم تعديل جميع الشركات

        // الحصول على جميع المستخدمين بغض النظر عن انتمائهم لشركة
        // نضيف تعليق في السجل لمعرفة عدد المستخدمين
        $availableUsers = User::all();
        \Log::info('عدد المستخدمين المتاحين: ' . $availableUsers->count());
        foreach ($availableUsers as $user) {
            \Log::info('المستخدم: ' . $user->name . ' (ID: ' . $user->id . ', شركة: ' . $user->company_id . ')');
        }

        return view('companies.edit', compact('company', 'availableUsers'));
    }

    /**
     * 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 = Company::findOrFail($id);

        // جميع المستخدمين يمكنهم تحديث جميع الشركات

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'name_en' => 'nullable|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'nullable|string|max:20',
            'mobile' => 'nullable|string|max:20',
            'website' => 'nullable|string|max:255|url',
            'address' => 'nullable|string|max:255',
            'address_en' => 'nullable|string|max:255',
            'city' => 'nullable|string|max:100',
            'state' => 'nullable|string|max:100',
            'country' => 'nullable|string|max:100',
            'postal_code' => 'nullable|string|max:20',
            'cr_number' => 'nullable|string|max:50',
            'vat_number' => 'nullable|string|max:50',
            'tax_number' => 'nullable|string|max:50',
            'currency' => 'required|string|size:3',
            'tax_rate' => 'required|numeric|min:0|max:100',
            'vat_rate' => 'nullable|numeric|min:0|max:100',
            'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'is_active' => 'boolean',
            'notes' => 'nullable|string',
            'primary_user_id' => 'nullable|exists:users,id',
        ]);

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

        // Handle logo upload
        if ($request->hasFile('logo')) {
            $logoPath = $request->file('logo')->store('company_logos', 'public');
            $company->logo = $logoPath;
        }

        // Update company
        $company->name = $request->name;
        $company->name_en = $request->name_en;
        $company->email = $request->email;
        $company->phone = $request->phone;
        $company->mobile = $request->mobile;
        $company->website = $request->website;
        $company->address = $request->address;
        $company->address_en = $request->address_en;
        $company->city = $request->city;
        $company->state = $request->state;
        $company->country = $request->country;
        $company->postal_code = $request->postal_code;
        $company->cr_number = $request->cr_number;
        $company->vat_number = $request->vat_number;
        $company->tax_number = $request->tax_number;
        $company->currency = $request->currency;
        $company->tax_rate = $request->tax_rate;
        $company->vat_rate = $request->vat_rate;
        $company->notes = $request->notes;

        // Only super admin, admin, or users with super_admin position can update these fields
        if ($user->hasRole('super_admin') || $user->hasRole('admin') || $user->position == 'super_admin' || $user->email == 'manager3@manager3.com') {
            $company->is_active = $request->has('is_active');
            $company->domain = $request->domain;
            $company->subscription_plan = $request->subscription_plan;

            // تسجيل قيمة primary_user_id للتحقق
            \Log::info('قيمة primary_user_id المرسلة: ' . $request->primary_user_id);

            $company->primary_user_id = $request->primary_user_id;

            if ($request->filled('subscription_ends_at')) {
                $company->subscription_ends_at = $request->subscription_ends_at;
            }
        }

        $company->save();

        return redirect()->route('companies.show', $company->id)
            ->with('success', 'Company updated successfully.');
    }

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

        // Only super admin or users with super_admin position can delete companies
        if (!$user->hasRole('super_admin') && $user->position != 'super_admin' && $user->email != 'manager3@manager3.com') {
            return redirect()->route('companies.index')
                ->with('error', 'ليس لديك صلاحية لحذف الشركات.');
        }

        $company = Company::findOrFail($id);

        // Soft delete the company
        $company->delete();

        return redirect()->route('companies.index')
            ->with('success', 'Company deleted successfully.');
    }

    /**
     * Display financial report for the company.
     *
     * @param  int  $id
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function financialReport($id, Request $request)
    {
        $user = Auth::user();
        $company = Company::findOrFail($id);

        // تحقق من صلاحية المستخدم لعرض التقرير المالي - فقط المستخدمون غير المرتبطين بشركة أو المرتبطين بهذه الشركة يمكنهم الوصول
        if ($user->company_id !== null && $user->company_id != $company->id) {
            return redirect()->route('companies.index')
                ->with('error', 'ليس لديك صلاحية لعرض التقرير المالي لهذه الشركة.');
        }

        // تحديد الفترة الزمنية للتقرير
        $startDate = $request->has('start_date')
            ? \Carbon\Carbon::parse($request->start_date)
            : \Carbon\Carbon::now()->subMonths(6)->startOfMonth();

        $endDate = $request->has('end_date')
            ? \Carbon\Carbon::parse($request->end_date)
            : \Carbon\Carbon::now()->endOfMonth();

        // بيانات الفواتير
        $invoices = $company->invoices()
            ->whereBetween('invoice_date', [$startDate, $endDate])
            ->get();

        $paidInvoices = $invoices->where('status', 'paid');
        $unpaidInvoices = $invoices->where('status', 'unpaid');
        $partiallyPaidInvoices = $invoices->where('status', 'partially_paid');

        $paidInvoicesCount = $paidInvoices->count();
        $paidInvoicesAmount = $paidInvoices->sum('total_amount');

        $unpaidInvoicesCount = $unpaidInvoices->count();
        $unpaidInvoicesAmount = $unpaidInvoices->sum('total_amount');

        $partiallyPaidInvoicesCount = $partiallyPaidInvoices->count();
        $partiallyPaidInvoicesAmount = $partiallyPaidInvoices->sum('total_amount');

        $totalInvoicesCount = $invoices->count();
        $totalInvoicesAmount = $invoices->sum('total_amount');

        // بيانات العقود
        $contracts = $company->maintenance_contracts()
            ->whereBetween('start_date', [$startDate, $endDate])
            ->orWhereBetween('end_date', [$startDate, $endDate])
            ->get();

        $now = \Carbon\Carbon::now();
        $activeContracts = $contracts->filter(function ($contract) use ($now) {
            return $contract->start_date <= $now && $contract->end_date >= $now;
        });

        $expiredContracts = $contracts->filter(function ($contract) use ($now) {
            return $contract->end_date < $now;
        });

        $expiringContracts = $contracts->filter(function ($contract) use ($now) {
            return $contract->start_date <= $now && $contract->end_date >= $now && $contract->end_date <= $now->copy()->addMonths(1);
        });

        $activeContractsCount = $activeContracts->count();
        $activeContractsAmount = $activeContracts->sum('total_amount');

        $expiredContractsCount = $expiredContracts->count();
        $expiredContractsAmount = $expiredContracts->sum('total_amount');

        $expiringContractsCount = $expiringContracts->count();
        $expiringContractsAmount = $expiringContracts->sum('total_amount');

        $totalContractsCount = $contracts->count();
        $totalContractsAmount = $contracts->sum('total_amount');

        // إجماليات مالية
        $totalRevenue = $paidInvoicesAmount + $partiallyPaidInvoices->sum('paid_amount');
        $totalExpenses = 0; // يمكن إضافة المصروفات لاحقاً
        $netProfit = $totalRevenue - $totalExpenses;

        // بيانات الرسم البياني للإيرادات الشهرية
        $monthlyRevenueData = [];
        $monthlyRevenueLabels = [];

        $currentDate = $startDate->copy();
        while ($currentDate <= $endDate) {
            $monthYear = $currentDate->format('Y-m');
            $monthName = $currentDate->translatedFormat('F Y');

            $monthlyRevenue = $invoices
                ->filter(function ($invoice) use ($currentDate) {
                    return $invoice->invoice_date->format('Y-m') == $currentDate->format('Y-m');
                })
                ->sum(function ($invoice) {
                    return $invoice->status == 'paid' ? $invoice->total_amount : ($invoice->status == 'partially_paid' ? $invoice->paid_amount : 0);
                });

            $monthlyRevenueData[] = $monthlyRevenue;
            $monthlyRevenueLabels[] = $monthName;

            $currentDate->addMonth();
        }

        return view('companies.financial_report', compact(
            'company',
            'startDate',
            'endDate',
            'paidInvoicesCount',
            'paidInvoicesAmount',
            'unpaidInvoicesCount',
            'unpaidInvoicesAmount',
            'partiallyPaidInvoicesCount',
            'partiallyPaidInvoicesAmount',
            'totalInvoicesCount',
            'totalInvoicesAmount',
            'activeContractsCount',
            'activeContractsAmount',
            'expiredContractsCount',
            'expiredContractsAmount',
            'expiringContractsCount',
            'expiringContractsAmount',
            'totalContractsCount',
            'totalContractsAmount',
            'totalRevenue',
            'totalExpenses',
            'netProfit',
            'monthlyRevenueData',
            'monthlyRevenueLabels'
        ));
    }
}
