<?php

namespace App\Http\Controllers\API\V4\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;
use App\Models\User;
use Illuminate\Support\Str;
use App\Models\Store;
use App\Restorant;
use App\Hours;
use App\Notifications\WelcomeMail;


class AuthController extends Controller
{
    public function login(Request $request)
    {
        // ✅ Validate request input
        $request->validate([
            'user' => 'required|string',
            'password' => 'required|string',
        ]);

        $username = $request->input('user');
        $password = $request->input('password');
        $fcm_token = $request->input('token');

        // ✅ Fetch user by phone or email, ensuring not blocked
        // $user = DB::table('users')
        //     ->where(function ($query) use ($username) { 
        //         $query->where('phone_number', $username)
        //               ->orWhere('email', $username);
        //     })
        //     ->where('blokir', 'N')
        //     ->first();

            $user = User::where(function ($query) use ($username) {
                $query->where('phone_number', $username)
                    ->orWhere('email', $username);
            })
            ->where('blokir', 'N')
            ->first();


        // ✅ Handle missing user
        if (!$user) {
            return response()->json([
                'status' => 'true',
                'errCode' => '02',
                'msg' => 'Wrong login or inactive account',
            ]);
        }

        // ✅ Password verification (assumes passwords are hashed using bcrypt)
        if (!Hash::check($password, $user->password)) {
            return response()->json([
                'status' => 'true',
                'errCode' => '03',
                'msg' => 'Incorrect password',
            ]);
        }

        // ✅ Generate session ID
        $sessionId = $user->id_session ?: md5($username . gmdate('dHi'));

        // ✅ Optional: Update session ID in DB (uncomment if needed)
        // DB::table('users')->where('id', $user->id)->update(['id_session' => $sessionId]);

        // ✅ Insert attendance only if not already present for today
        $today = gmdate('Y-m-d');
        $time = gmdate('H:i');

        // $attendanceExists = DB::table('attendance')
        //     ->where('staff', $user->phone_number)
        //     ->where('date', $today)
        //     ->exists();

        // if (!$attendanceExists) {
        //     DB::table('attendance')->insert([
        //         'staff' => $user->phone_number,
        //         'date' => $today,
        //         'hour' => $time,
        //         'device' => $sessionId,
        //         'name_attendance' => 'login',
        //         'user' => $user->master,
        //     ]);
        // }

         // Save/update FCM token
        if ($fcm_token) {
            $user->fcm_token = $fcm_token;
            $user->save();
        }


        // ✅ Retrieve related store and plan info
        $store = DB::table('store')->where('id_store', $user->id_store)->first();
        $plan = DB::table('plan')->where('id', $user->plan_id)->first();
        $setting = DB::table('setting')->first();

        // ✅ Build response
        return response()->json([
            'status' => 'true',
            'errCode' => '01',
            'msg' => 'Success',
            'data' => [[
                'key' => $sessionId,
                'currency' => "",
                'user' => $user->phone_number,
                'level' => $user->level,
                'master' => $user->master,
                'packages' => $plan->id ?? null,
                'typestore' => $store->typestore ?? null,
                'decimal' => $store->decimals ?? null,
                'id_store' => $user->id_store,
                'system_point' => $setting->point_system ?? null,
            ]],
        ]);
    }


    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email'        => 'required|email|unique:users,email',
            'phone_number' => 'required|unique:users,phone_number',
            'password'     => 'required|min:6',
            'name_store'   => 'required|string',
            'currency'     => 'required|string',
            'full_name'    => 'required|string',
            'typestore'    => 'required|string',
            'address'      => 'nullable|string',
            'referal'      => 'nullable|string',
            'decimal'      => 'nullable|numeric',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status'  => 'false',
                'errCode' => '02',
                'msg'     => $validator->errors()->first()
            ]);
        }

        DB::beginTransaction();

        try {
            $email        = $request->email;
            $phone        = $request->phone_number;
            $password     = $request->password;
            $nameStore    = $request->name_store;
            $currency     = $request->currency;
            $fullName     = $request->full_name;
            $address      = $request->address ?? '';
            $referralCode = $request->referal ?? '';
            $typeStore    = $request->typestore;
            $decimal      = $request->decimal ?? 2;

            $sessionId = md5($phone);
            $storeCode = strtoupper(collect(explode(' ', $nameStore))->map(fn($word) => $word[0])->implode(''));
            $subdomain = explode(' ', trim($nameStore))[0];

            $settings = DB::table('setting')->first();
            $upline   = DB::table('users')->where('afiliasi', $referralCode)->first();
            $referral = ($phone == '000') ? null : optional($upline)->phone_number;

            
             //Create the user
            $ids=md5(strip_tags($request->phone_number));
            $userPassword = strip_tags($request->password); //Str::random(10);
            $owner = new User;
            $owner->name = strip_tags($request->full_name);
            $owner->email = strip_tags($request->email);
            $owner->phone = strip_tags($request->phone_number) | '';
            $owner->master = strip_tags($request->phone_number);
            $owner->address = strip_tags($request->address);
            $owner->level = 'master';
            $owner->id_session = $ids;
            $owner->packages = 0;
            $owner->nominal_upgrade = 0;
            $owner->img = 'avatar.png';
            $owner->afiliasi = Str::random(10);
            $owner->referal = $referral;
            $owner->id_store = null; // This will be updated later
            $owner->restaurant_id = null; 
            $owner->phone = strip_tags($request->phone_number);
            $owner->phone_number = strip_tags($request->phone_number);
            $owner->api_token = Str::random(80);

            $owner->password = password_hash($userPassword, PASSWORD_DEFAULT, ['cost' => 13]);
            $owner->save();

            // Insert store
            $store = Store::create([
                'name_store'   => $nameStore,
                'currency'     => $currency,
                'number_store' => "$storeCode-$owner->id",
                'user'         => $phone,
                'email'        => $email,
                'nohp'         => $phone,
                'type'         => 'master',
                'address'      => $address,
                'decimals'     => $decimal,
                'typestore'    => $typeStore,
            ]);

            // Insert company
            $company = new Restorant;
            $company->name =  $nameStore;
            $company->currency =  $currency;
            $company->color_store =  'Blue';
            $company->userz =  $phone;
            $company->whatsapp_phone =  $phone;
            $company->operational_hour =  '8am-5pm';
            $company->linkinstagram =  'https://instagram.com';
            $company->phone =  $phone;
            $company->subdomain =  $subdomain . $owner->id;
            $company->address =  $address;
            $company->typestore =  $typeStore;
            $company->user_id =  null;
            $company->save();

            // if (!$company->id) {
            //     throw new \Exception('One of the required IDs is missing: owner, store, or company.');
            // }


            // Update user & company with each other
            $owner->update(['id_store' => $store->id, 'restaurant_id' => $company->id]);
            $company->update(['user_id' => $owner->id]);

            // Assign role
            DB::table('model_has_roles')->insert([
                'role_id'    => 2,
                'model_type'=> 'App\\User',
                'model_id'  => $owner->id,
            ]);

            // Insert default hours

             $hours = new Hours();
        $hours->restorant_id = $company->id;

        //$shift="_shift".$request->shift_id;
        
        $hours->{'0_from'} = config('settings.time_format') == "AM/PM" ? "12:01 AM" : "12:01";
        $hours->{'0_to'} = config('settings.time_format') == "AM/PM" ? "11:59 PM" : "23:59";
        $hours->{'1_from'} = config('settings.time_format') == "AM/PM" ? "12:01 AM" : "12:01";
        $hours->{'1_to'} = config('settings.time_format') == "AM/PM" ? "11:59 PM" : "23:59";
        $hours->{'2_from'} = config('settings.time_format') == "AM/PM" ? "12:01 AM" : "12:01";
        $hours->{'2_to'} = config('settings.time_format') == "AM/PM" ? "11:59 PM" : "23:59";
        $hours->{'3_from'} = config('settings.time_format') == "AM/PM" ? "12:01 AM" : "12:01";
        $hours->{'3_to'} = config('settings.time_format') == "AM/PM" ? "11:59 PM" : "23:59";
        $hours->{'4_from'} = config('settings.time_format') == "AM/PM" ? "12:01 AM" : "12:01";
        $hours->{'4_to'} = config('settings.time_format') == "AM/PM" ? "11:59 PM" : "23:59";
        $hours->{'5_from'} = config('settings.time_format') == "AM/PM" ? "12:01 AM" : "12:01";
        $hours->{'5_to'} = config('settings.time_format') == "AM/PM" ? "11:59 PM" : "23:59";
        $hours->{'6_from'} = config('settings.time_format') == "AM/PM" ? "12:01 AM" : "12:01";
        $hours->{'6_to'} = config('settings.time_format') == "AM/PM" ? "11:59 PM" : "23:59";
        
        $hours->save();
       

            DB::commit();

            // Send welcome email
            Mail::to($email)->send(new WelcomeMail($fullName, $password));

            return response()->json([
                'status'  => 'true',
                'errCode' => '01',
                'msg'     => 'Success, Registration Successful. Please Login Now'
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'status'  => 'false',
                'errCode' => '99',
                'msg'     => 'Registration Failed. Please try again.',
                 'error' => $e->getMessage()
            ]);
        }
    }
}
