<?php

namespace App\Http\Controllers;

use App\Models\Tenant;
use App\Models\User;
use App\Models\SubscriptionPlan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use DB;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;

class TenantController extends Controller
{
    public function create()
    {
        if (Auth::check()) {
            return redirect('/dashboard');
        }

        $plans = SubscriptionPlan::all();
        return view('tenants.register', compact('plans'));
    }

    public function store(Request $request)
    {

        $request->validate([
            'name' => 'required|unique:tenants,name',
            'email' => 'required|email|unique:tenants,email',
            'subscription_plan_id' => 'required|exists:subscription_plans,id',
            'admin_name' => 'required',
            'admin_email' => 'required|email|unique:users,email',
            'admin_password' => 'required|min:6',
            'timezone' => 'required|string'
        ]);

        DB::beginTransaction();

try {
    $tenant = Tenant::create([
        'name' => $request->name,
        'email' => $request->email,
        'phone' => $request->phone,
        'subscription_plan_id' => $request->subscription_plan_id,
        'expires_at' => now()->addMonth(),
        'timezone' => $request->timezone, // حفظ التايم زون
    ]);

    $user = User::create([
        'name' => $request->admin_name,
        'email' => $request->admin_email,
        'password' => Hash::make($request->admin_password),
        'tenant_id' => $tenant->id,
        'role' => 'administrateur',
    ]);

    $user_user = User::create([
        'name' => "user",
        'email' => "user_{$tenant->id}_" . time() . "@app.local",
        'password' => Hash::make(Str::password()),
        'tenant_id' => $tenant->id,
        'role' => 'user',
    ]);

    $permissionIds = DB::table('permission_plan')
        ->where('plan_id', $tenant->subscription_plan_id)
        ->pluck('permission_id');

    $permissionIds_user = [1,6,8,9,10,11,12,31];

    $roleAdmin = DB::table('roles')->insertGetId([
        'tenant_id' => $tenant->id,
        'name' => "administrateur",
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $roleUser = DB::table('roles')->insertGetId([
        'tenant_id' => $tenant->id,
        'name' => "user",
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $roleUserAdminId = DB::table('role_user')->insertGetId([
        'user_id' => $user->id,
        'role_id' => $roleAdmin,
        'tenant_id' => $tenant->id,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $roleUserUserId = DB::table('role_user')->insertGetId([
        'user_id' => $user_user->id,
        'role_id' => $roleUser,
        'tenant_id' => $tenant->id,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $dataAdmin = $permissionIds->map(function ($id) use ($roleUserAdminId) {
        return [
            'role_id' => $roleUserAdminId, // 👈 id من role_user
            'permission_id' => $id,
            'created_at' => now(),
            'updated_at' => now(),
        ];
    })->toArray();

    $dataUser = collect($permissionIds_user)->map(function ($id) use ($roleUserUserId) {
        return [
            'role_id' => $roleUserUserId, // 👈 id من role_user
            'permission_id' => $id,
            'created_at' => now(),
            'updated_at' => now(),
        ];
    })->toArray();

    DB::table('permission_role')->insert(array_merge($dataAdmin, $dataUser));

    DB::commit();

    auth()->login($user);

    return redirect('/settings')->with('success', 'تم إنشاء العيادة بنجاح');

} catch (\Exception $e) {
    DB::rollBack();
    throw $e;
}
    }


    public function store2(Request $request)
    {
        $request->validate([
            'name' => 'required|unique:tenants,name',
            'email' => 'required|email|unique:tenants,email',
            'subscription_plan_id' => 'required|exists:subscription_plans,id',
            'admin_name' => 'required',
            'admin_email' => 'required|email|unique:users,email',
            'admin_password' => 'required|min:6',
        ]);

        $tenant = Tenant::create([
            'name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
            'subscription_plan_id' => $request->subscription_plan_id,
            'expires_at' => now()->addMonth(),
        ]);

        $user = User::create([
            'name' => $request->admin_name,
            'email' => $request->admin_email,
            'password' => Hash::make($request->admin_password),
            'tenant_id' => $tenant->id,
            'role' => 'administrateur',
        ]);

        $faker = \Faker\Factory::create();

        $user_user = User::create([
            'name' => "user",
            'email' => $faker->unique()->safeEmail,
            'password' => Hash::make(Str::password()),
            'tenant_id' => $tenant->id,
            'role' => 'user',
        ]);

            // 3. جلب الصلاحيات الخاصة بالباقة
            $permissionIds = DB::table('permission_plan')
            ->where('plan_id', $tenant->subscription_plan_id)
            ->pluck('permission_id');

            $permissionIds_user = [1,6,8,9,10,11,12,31];

            // اضافة دور الأدمين
            $role_id = DB::table('roles')->insertGetId([
                'tenant_id' => $tenant->id,
                'name' => "administrateur",
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            $role_crt = DB::table('role_user')->insertGetId([
                'user_id' => $user->id,
                'role_id' => $role_id,
                'tenant_id' => $tenant->id,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

           // اضافة دور مستخدم
           $role_user_id = DB::table('roles')->insertGetId([
            'tenant_id' => $tenant->id,
            'name' => "user",
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $role_user_crt = DB::table('role_user')->insertGetId([
            'user_id' => $user_user->id,
            'role_id' => $role_user_id,
            'tenant_id' => $tenant->id,
            'created_at' => now(),
            'updated_at' => now(),
        ]);



        // 4. ربط هذه الصلاحيات بالأدمن
        foreach ($permissionIds as $permissionId) {
            DB::table('permission_role')->insert([
                'role_id' => $role_crt,
                'permission_id' => $permissionId,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

       // ربط الصلاحيات مستخدم
       $data = collect($permissionIds_user)->map(function ($id) use ($role_user_crt) {
        return [
            'role_id' => $role_user_crt,
            'permission_id' => $id,
            'created_at' => now(),
            'updated_at' => now(),
        ];
    })->toArray();

    DB::table('permission_role')->insert($data);

        DB::commit();



        auth()->login($user);

        return redirect('/dashboard')->with('success', 'تم إنشاء العيادة بنجاح');
    }



}
