<?php

namespace App\Http\Controllers\API\V4;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Plans;
use Illuminate\Support\Facades\DB;
use App\Restorant;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\File;
use App\Models\Store;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Intervention\Image\Facades\Image;

class StoreController extends Controller
{
    // GET equivalent: fetch stores and stats for user by UserKey and optional LastSyncTime
    public function getStores(Request $request)
    {
        $key = $request->query('UserKey');
        $lastSyncTime = $request->query('LastSyncTime');

        $user = User::where('id_session', $key)->first();
        if (!$user) {
            return response()->json([
                'status' => 'true',
                'errCode' => '00',
                'msg' => 'User Not Found'
            ]);
        }

        $masterAccount = User::where('phone_number', $user->master)->first();
        $plan = Plans::find($masterAccount->plan_id);
        $onlineStore = Restorant::where('userz', $masterAccount->phone_number)->first();


        // Build store query based on user level
        $storeQuery = null;
        // $salesDataQuery = null;

        if ($user->level === 'master') {
            $storeQuery = Store::where('user', $user->phone_number)->where('status', '0');
           
        } else {
            $storeQuery = Store::where('id_store', $user->id_store)->where('status', '0');
           
        }

        // Apply LastSyncTime filter if given
        if ($lastSyncTime && strtotime($lastSyncTime) > 1) {
            $storeQuery->where('updated_at', '>', $lastSyncTime);
        }

        $stores = $storeQuery->get();

      

        if ($stores->count() > 0) {
            $response = [];
            foreach ($stores as $store) {
                $masterStore = Store::where('user', $user->master)->first();

                // limit is always exceeded? Original logic sets 'exceeded' always. Adjust if needed.
               // $limit = ($totalStores < $plan->limit_branch) ? 'exceeded' : 'exceeded';

                $subdomain = "https://{$onlineStore->subdomain}.ontrack.ng";

                $response[] = [
                    'id_store'        => $store->id_store,
                    'user'            => $masterAccount->phone_number,
                    'name_store'      => $store->name_store,
                    'number_store'    => $store->number_store,
                    'address'         => $store->address,
                    'email'           => $store->email,
                    'nohp'            => $store->nohp,
                    'tax'             => $store->tax,
                    'service_charge'  => $store->service_charge,
                    'currency'        => $store->currency,
                    'status'          => $store->status, 
                    'showing'         => $store->showing,
                   // 'created_at'      => $store->created_at,
                    'type'            => $store->type,
                    'folder'          => $store->folder,
                    'level'           => $user->level, 
                    'shift'           => $store->shift,
                   // 'updated_at'      => $store->updated_at,
                    'typestore'       => $store->typestore,
                    'decimals'        => $store->decimals,
                    'footer'          => $store->footer,
                    'img'             => url("uploads/restorants/{$store->img}"),
                    'websiteurl'      => $subdomain,
                ];
            }

            return response()->json($response);
        } else {
            return response()->json([
                'status' => 'true',
                'errCode' => '02',
                'msg' => 'no data'
            ]);
        }
    }

    // POST equivalent: update or create store info, including image upload
    public function syncStore(Request $request)
    {
        // Validate request (adjust rules as needed)
        //     $validator = Validator::make($request->all(), [
        //         'UserKey'       => 'required|string',
        //         'id_store'      => 'required|integer',
        //         'name_store'    => 'required|string',
        //         'email'         => 'nullable|email',
        //         'address'       => 'nullable|string',
        //         'tax'           => 'nullable|string',
        //         'service_charge'=> 'nullable|string',
        //         'nohp'          => 'nullable|string',
        //         'currency'      => 'nullable|string',
        //         'footer'        => 'nullable|string',
        //         'shift'         => 'nullable|string',
        //         'updated_at'    => 'required',
        //         'img'           => 'nullable|image|max:2048', // optional image upload
        //     ]);

        //     if ($validator->fails()) {
        //         return response()->json(['status' => 'error', 'errors' => $validator->errors()], 422);
        //     }

        //     $user = User::where('id_session', $request->UserKey)->first();
        //     if (!$user) {
        //         return response()->json([
        //             'status' => 'true',
        //             'errCode' => '00',
        //             'msg' => 'User Not Found'
        //         ]);
        //     }

        //     $masterAccount = User::where('phone_number', $user->master)->first();

        //     $store = Store::where('id_store', $request->id_store)->first();

        //     // If updated_at on request <= current store updated_at, discard update
        //     if ($store && $store->updated_at >= $request->updated_at) {
        //         return response()->json(['status' => 'success', 'msg' => 'No update needed']);
        //     }

        //     // Prepare footer
        //     $footer = $request->footer ?: 'Thank you for business';

        //     // Handle image upload
        //     if ($request->hasFile('img')) {
        //         $file = $request->file('img');
        //         $filename = time() . '.' . $file->getClientOriginalExtension();
        //         $path = $file->storeAs('uploads/restorants', $filename, 'public');

        //         // Create thumbnail
        //         $thumbnailPath = storage_path('app/public/uploads/restorants/' . $filename . '_thumbnail.jpg');
        //         $img = Image::make($file->getRealPath());
        //         $img->resize(100, 100, function ($constraint) {
        //             $constraint->aspectRatio();
        //         })->save($thumbnailPath);
        //     } else {
        //         $filename = $store ? $store->img : null;
        //     }

        //     if (!$store) {
        //         // create new store
        //         $store = new Store();
        //         $store->id_store = $request->id_store;
        //         $store->user = $masterAccount->phone_number;
        //     }

        //     // Update fields
        //     $store->name_store      = $request->name_store;
        //     $store->email           = $request->email;
        //     $store->address         = $request->address;
        //     $store->tax             = $request->tax;
        //     $store->service_charge  = $request->service_charge;
        //     $store->nohp            = $request->nohp;
        //     $store->currency        = $request->currency;
        //     $store->footer          = $footer;
        //     $store->shift           = $request->shift;
        //    // $store->updated_at      = $request->updated_at;
        //     if ($filename) {
        //         $store->img = $filename;
        //     }

        //     $store->save();

       // return response()->json(['status' => 'success', 'msg' => 'Store updated successfully']);
        return response()->json([["status" => "success"]]);
        
    }



public function getStoresBySessionKey(Request $request)
{
    $key = $request->query('key');

    $user = User::where('id_session', $key)->first();

    if (!$user) {
        return response()->json([
            'status' => 'true',
            'errCode' => '00',
            'msg' => 'User Not Found',
        ]);
    }

    $master = User::where('phone_number', $user->master)->first();
    $plan = Plans::find($master->plan_id);

    $userStores = Store::where('user', $user->phone_number)
        ->where('status', '0')
        ->get();
    $totalStores = $userStores->count();

    $stores = Store::where('user', $master->phone_number)
        ->where('status', '0')
        ->get();

    if ($stores->isEmpty()) {
        return response()->json([
            'status' => 'true',
            'errCode' => '02',
            'msg' => 'no data',
        ]);
    }

    $response = [
        'status' => 'true',
        'errCode' => '01',
        'msg' => 'Success',
        'data' => [],
    ];

    foreach ($stores as $store) {
        $imgUrl = $store->img
            ? url("uploads/restorants/{$store->img}")
            : "";

        $limitStatus = $totalStores < $plan->limit_branch ? 'premium' : 'exceeded';

        $response['data'][] = [
            'id_store'       => $store->id_store,
            'name_store'     => $store->name_store,
            'number_store'   => $store->number_store,
            'address'        => $store->address,
            'email'          => $store->email,
            'nohp'           => $store->nohp,
            'tax'            => $store->tax,
            'type'           => $store->type,
            'service_charge' => $store->service_charge,
            'province'       => $store->province,
            'city'           => $store->city,
            'shift'          => $store->shift,
            'currency'       => $store->currency,
            'footer'         => $store->footer,
            'img'            => $imgUrl,
            'limit'          => $limitStatus,
        ];
    }

    return response()->json($response);
}

public function updateStore(Request $request)
{
    $request->validate([
        'key' => 'required|string',
        'name_store' => 'required|string',
        'email' => 'nullable|email',
        'address' => 'nullable|string',
        'tax' => 'nullable|string',
        'service_charge' => 'nullable|string',
        'nohp' => 'nullable|string',
        'id' => 'required|integer',
        'currency' => 'nullable|string',
        'footer' => 'nullable|string',
        'shift' => 'nullable|string',
        'img' => 'nullable|image|max:2048',
    ]);

    $user = User::where('id_session', $request->key)->first();

    if (!$user) {
        return response()->json([
            'status' => 'true',
            'errCode' => '00',
            'msg' => 'User Not Found'
        ]);
    }

    $master = User::where('phone_number', $user->master)->first();

    $store = Store::where('id_store', $request->id)->first();

    if (!$store) {
        return response()->json([
            'status' => 'true',
            'errCode' => '03',
            'msg' => 'Store Not Found'
        ]);
    }

   

     // Handle image upload to public directory
    if ($request->hasFile('img')) {
        $file = $request->file('img');
        $filename = 'small_' . rand(1, 99) . '_' . Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)) . '.' . $file->getClientOriginalExtension();
        $destinationPath = public_path('uploads/restorants');

        // Create directory if it doesn't exist
        if (!File::exists($destinationPath)) {
            File::makeDirectory($destinationPath, 0755, true);
        }

        $file->move($destinationPath, $filename);

        $user->img = $filename;
        // Optional: delete the old image if needed
         Storage::delete('public/uploads/restorants/' . $user->img);
     // Update logo in companies table
        Restorant::where('userz', $user->master)->update([
            'logo' => $filename,
            'currency' => $request->currency
        ]);
    } else {
        // Only update currency in companies if no image was uploaded
        Restorant::where('userz', $user->master)->update([
            'currency' => $request->currency
        ]);
    }

    // Update the store
    DB::table('store')
    ->where('id_store', $request->id)
    ->update([
        'name_store' => $request->name_store,
        'address' => $request->address,
        'email' => $request->email,
        'tax' => $request->tax,
        'service_charge' => $request->service_charge,
        'currency' => $request->currency,
        'footer' => $request->footer,
        'shift' => $request->shift,
        'nohp' => $request->nohp,
        'img' => $filename ?? $store->img, // Use existing image if not updated
        'updated_at' => now(),
    ]);


    return response()->json([
        'status' => 'true',
        'errCode' => '01',
        'msg' => 'Success'
    ]);
}

public function createStore(Request $request)
{
    // Validate input
    $validator = Validator::make($request->all(), [
        'key' => 'required|string',
        'name_store' => 'required|string',
        'email' => 'nullable|email',
        'tax' => 'nullable|numeric',
        'service_charge' => 'nullable|numeric',
        'nohp' => 'nullable|string',
        'currency' => 'nullable|string',
        'address' => 'nullable|string',
        'footer' => 'nullable|string',
    ]);

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

    $key = $request->key;

    // Find user by session key
    $user = User::where('id_session', $key)->first();

    if (!$user) {
        return response()->json([
            'status' => 'true',
            'errCode' => '00',
            'msg' => 'User Not Found'
        ]);
    }

    // Get master account
    $master = User::where('phone_number', $user->master)->first();

    if (!$master) {
        return response()->json([
            'status' => 'true',
            'errCode' => '02',
            'msg' => 'Master account not found'
        ]);
    }

    // Get the number_store from one of the master user's stores
    $storeData = Store::where('user', $master->phone_number)->first();
    $numberStore = $storeData ? $storeData->number_store : 'BR001'; // Default if not found

    // Set default values
    $tax = $request->filled('tax') ? $request->tax : 0.0;
    $serviceCharge = $request->filled('service_charge') ? $request->service_charge : 0.0;
    $footer = $request->filled('footer') ? $request->footer : 'Thank you for business';

    // Create the new store
    $store = new Store();
    $store->name_store = $request->name_store;
    $store->number_store = $numberStore;
    $store->email = $request->email;
    $store->nohp = $request->nohp;
    $store->address = $request->address;
    $store->tax = $tax;
    $store->currency = $request->currency;
    $store->footer = $footer;
    $store->service_charge = $serviceCharge;
    $store->type = 'branch';
    $store->user = $master->phone_number;

    if ($store->save()) {
        return response()->json([
            'status' => 'true',
            'errCode' => '01',
            'msg' => 'Success'
        ]);
    } else {
        return response()->json([
            'status' => 'false',
            'errCode' => '98',
            'msg' => 'Failed to create store'
        ]);
    }
}

public function deleteStore(Request $request)
{
    $request->validate([
        'key' => 'required|string',
        'id' => 'required|string',
    ]);

    $user = User::where('id_session', $request->key)->first();

    if (!$user) {
        return response()->json([
            'status' => 'true',
            'errCode' => '00',
            'msg' => 'User Not Found'
        ]);
    }

    $master = User::where('phone_number', $user->master)->first();

    $store = Store::where('id_store', $request->id)->first();

    if (!$store) {
        return response()->json([
            'status' => 'true',
            'errCode' => '03',
            'msg' => 'Store Not Found'
        ]);
    }

    // Delete the store
    DB::table('store')
    ->where('id_store', $request->id)
    ->update([
        'status' => '1',
        'updated_at' => now(),
    ]);


    return response()->json([
        'status' => 'true',
        'errCode' => '01',
        'msg' => 'Success'
    ]);
}



public function getCurrencies()
{
    // Fetch currencies from the database
    $currencies = DB::table('currencies')->get();

    if ($currencies->isNotEmpty()) {
        $response = [ 
            'status' => 'true',
            'errCode' => '01',
            'msg' => 'Success',
            'data' => [] 
        ];

        foreach ($currencies as $currency) {
            $response['data'][] = [
                'id_currency'   => $currency->id_currencies,
                'code_currency' => $currency->code
            ];
        }

        return response()->json($response);
    } else {
        return response()->json([
            'status' => 'true',
            'errCode' => '02',
            'msg' => 'No Currency'
        ]);
    }
}

}
