<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Http\Requests\RegisterRequest;
use App\Models\BasicSettings;
use App\Models\Branch;
use App\Models\Category;
use App\Models\Client;
use App\Models\OuterClient;
use App\Models\Supplier;
use App\Models\Unit;
use App\Models\ClientProfile;
use App\Models\Company;
use App\Models\EmailSettings;
use App\Models\ExtraSettings;
use App\Models\Fiscal;
use App\Models\PreSettings;
use App\Models\Safe;
use App\Models\Screen;
use App\Models\Store;
use App\Models\Subscription;
use App\Models\Type;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redirect;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

Carbon::setLocale('ar');

class CompanyController extends Controller
{
    public function store(RegisterRequest $request)
    {

        $data = $request->all();
        $data['currency'] = "";
        $data['company_owner'] = $request->name;
        // $data['phone_number'] = $request->phone_number;

        $company = Company::create($data);

        if ($request->hasFile('company_logo')) {
            $image = $request->file('company_logo');
            $fileName = $image->getClientOriginalName();
            $uploadDir = 'uploads/companies/logos/' . $company->id;
            $image->move($uploadDir, $fileName);
            $company->company_logo = $uploadDir . '/' . $fileName;
            $company->save();
        }

        $basic_settings = BasicSettings::create([
            'header' => '',
            'footer' => '',
            'electronic_stamp' => '',
            'company_id' => $company->id
        ]);

        $email_settings = EmailSettings::create([
            'mail_host' => '',
            'mail_user' => '',
            'mail_pass' => '',
            'mail_port' => '',
            'sender_name' => '',
            'company_id' => $company->id
        ]);

        $extra_settings = ExtraSettings::create([
            'timezone' => '',
            'currency' => $data['currency'] ,
            'company_id' => $company->id,
            'font_size' => '13'
        ]);
        $pre_settings = PreSettings::create([
            'pre_category' => '1',
            'pre_orders' => '1',
            'pre_bill' => '1',
            'pre_buy_bill' => '1',
            'pre_cash' => '1',
            'pre_buy_cash' => '1',
            'pre_expenses' => '1',
            'pre_fast_sell' => '1',
            'pre_clients' => '1',
            'pre_suppliers' => '1',
            'pre_return' => '1',
            'pre_buy_return' => '1',
            'pre_fast_return' => '1',
            'pre_quotation' => '1',
            'pre_purchase_order' => '1',
            'company_id' => $company->id
        ]);
        $screens = Screen::create([
            'products' => 1,
            'dept' => 1,
            'banks_safes' => 1,
            'sales' => 1,
            'sales_type' => 1,
            'purchases' => 1,
            'finance' => 1,
            'marketing' => 1,
            'accounting' => 1,
            'reports' => 1,
            'settings' => 1,
            'company_id' => $company->id
        ]);
        $unit = Unit::create([
            'unit_name' => 'وحدة',
            'company_id' => $company->id,
            'primary_unit' => 1,
        ]);

        $company_id = $company->id;
       
        $company_id = $company->id;
        $company = Company::FindOrFail($company_id);
        $have_branches = $request->have_branches;
        $check = Fiscal::where('company_id', $company_id)
            ->where('fiscal_year', date('Y'))
            ->where('start_date', date('Y-01-01'))
            ->where('end_date', date('Y-12-31'))
            ->first();
        if (empty($check)) {
            $fiscal = Fiscal::create([
            'fiscal_year'=> date('Y'),
            'start_date'=> date('Y-01-01'),
            'end_date'=> date('Y-12-31'),
            'company_id'=>$company->id
            ]);
        }
        if (empty($have_branches)) {
            // no branches
            $branch = Branch::create([
                'company_id' => $company_id,
                'branch_name' => 'الفرع الرئيسى',
                'branch_phone' => '',
                'branch_address' => ''
            ]);
            $store = Store::create([
                'company_id' => $company_id,
                'branch_id' => $branch->id,
                'store_name' => 'المخزن الرئيسى'
            ]);
            $safe = Safe::create([
                'company_id' => $company_id,
                'branch_id' => $branch->id,
                'safe_name' => 'الخزنة الرئيسية',
                'balance' => 0,
                'balance_start'=>0,
            ]);

            $category = Category::create([
                'company_id' => $company_id,
                'category_name' => 'منتجات',
                'category_type' => 'مخزونية'
            ]);

            $category = Category::create([
                'company_id' => $company_id,
                'category_name' => 'خدمات',
                'category_type' => 'خدمية'
            ]);
        } 
    


        $password = $request->password;
        $company_id = $company->id;
        $data = $request->all();
        $email = $request->email;
        $data['company_id'] = $company_id;
        $data['Status'] = "active";
        $phone_number = $request->phone_number;
        $data['password'] = Hash::make($data['password']);
        $data['role_name'] = ["مدير النظام"];
        $data['founder'] = 1 ;
            $client = Client::create($data);
            $client->Status = "active";
            $client->save();

            // $outer_client = OuterClient::create([
            //     'company_id' => $company_id,
            //     'client_name' => 'Cash',
            //     'client_category' => 'جملة',
            //     'balance' => '0',
            // ]);
            // $supplier = Supplier::create([
            //     'company_id' => $company_id,
            //     'supplier_name' => 'Cash',
            //     'supplier_category' => 'جملة',
            //     'balance' => '0',
            // ]);
            $check = Role::where('company_id',$company->id)->where('name', 'مدير النظام')->where('guard_name', 'client-web')->first();
            if (empty($check)) {
                $role = Role::create([
                    'name' => 'مدير النظام',
                    'guard_name' => 'client-web',
                    'company_id' => $company_id
                ]);
                $permissions = Permission::pluck('id', 'id')->all();
                $role->syncPermissions($permissions);
                $client->assignRole($role->id);

                $role = Role::create([
                    'name' => 'محاسب',
                    'guard_name' => 'client-web',
                    'company_id' => $company_id
                ]);
                $role->syncPermissions($permissions);

                // other  roles and permissions
                $role = Role::create([
                    'name' => 'مستخدم',
                    'guard_name' => 'client-web',
                    'company_id' => $company_id
                ]);
                $role->syncPermissions([101,133,18,28,544,560]);



            } else {
                $client->assignRole($request->input('role_name'));
            }

            $profile = ClientProfile::create([
                'city_name' => '',
                'age' => '',
                'gender' => '',
                'profile_pic' => 'images/guest.png',
                'client_id' => $client->id,
                'company_id' => $company_id
            ]);

             Auth::guard('client-web')->login($client);

            return response()->json(['message' => 'تم التسجيل بنجاح', 'status' => true]);
        
            

    }

  
 


}
