<?php

namespace App\Http\Controllers\API\V4;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Stock;
use App\Models\HistoryStock;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class InventoryController extends Controller
{
    /**
     * Get stock records with optional LastSyncTime filtering
     */
    public function getStockUpdates(Request $request)
    {
        $userKey = $request->query('UserKey');
        $lastSyncTime = $request->query('LastSyncTime');

        // Validate presence of UserKey
        if (!$userKey) {
            return response()->json([
                'status' => false,
                'errCode' => '01',
                'msg' => 'UserKey is required',
            ], 400);
        }

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

        if (!$user) {
            return response()->json([
                'status' => false,
                'errCode' => '03',
                'msg' => 'Invalid UserKey',
            ], 401);
        }

        // Optional: fetch master user if needed (not used in this example)
        $masterUser = User::where('phone_number', $user->master)->first();

        $stockQuery = Stock::where('id_store', $user->id_store);

         if ($lastSyncTime && $lastSyncTime > 1) {
            $stockQuery->where('updated_at', '>', $lastSyncTime);
        }

        $stocks = $stockQuery->orderByDesc('id_stock')->get();

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

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

    /**
     * Insert or update stock record
     */
    public function syncStock(Request $request)
    {
        $userKey = $request->query('UserKey');

        if (!$userKey) {
            return response()->json([
                'status' => false,
                'errCode' => '01',
                'msg' => 'UserKey is required',
            ], 400);
        }

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

        if (!$user) {
            return response()->json([
                'status' => false,
                'errCode' => '03',
                'msg' => 'Invalid UserKey',
            ], 401);
        }

        $validator = Validator::make($request->all(), [
            'local_id_stock' => 'required|string',
            'id_stock' => 'nullable|numeric',
            'id_product' => 'required',
            'id_store' => 'required|numeric',
            'stock' => 'required|numeric',
            'cost' => 'nullable|numeric',
            'user' => 'nullable|string',
            'session' => 'nullable|string',
            'updated_at' => 'nullable',
        ]);

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

        $data = $validator->validated();

        $cloudId = $data['id_stock'] ?? 0;
        $cost = $data['cost'] ?? 0;
        $updatedAt = $data['updated_at'] ?? null;

        // Find existing stock by id_product
        $existingStock = Stock::where('id_product', $data['id_product'])->first();

        if ($existingStock) {
            // Check updated_at to decide if update is needed
            if ($updatedAt && $existingStock->updated_at >= $updatedAt) {
                // Existing is more recent or equal, discard update
                return response()->json([["status" => "success"]]);
            }

            // Update existing stock record
            $existingStock->local_id_stock = $data['local_id_stock'];
          //  $existingStock->stock = $data['stock'];
            $existingStock->cost = $cost;
            $existingStock->id_product = $data['id_product'];
            $existingStock->updated_at = $updatedAt ?? $existingStock->updated_at;
            $existingStock->save();

            return response()->json([["status" => "success"]]);
        }

        // Insert new stock record
        Stock::create([
            'local_id_stock' => $data['local_id_stock'],
            'id_product' => $data['id_product'],
            'id_store' => $data['id_store'],
           // 'stock' => $data['stock'],
            'cost' => $cost,
            'user' => $data['user'] ?? null,
            'session' => $data['session'] ?? null,
            'updated_at' => $updatedAt,
        ]);

        return response()->json([["status" => "success"]]);
    }

    /**
     * Get stock history records with optional LastSyncTime filtering
     */
    public function getHistoryUpdates(Request $request)
{
    $userKey = $request->query('UserKey');
    $lastSyncTime = $request->query('LastSyncTime');

    if (!$userKey) {
        return response()->json([ 
            'status' => false,
            'errCode' => '01',
            'msg' => 'UserKey is required',
        ], 400);
    }

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

    if (!$user) {
        return response()->json([
            'status' => false,
            'errCode' => '03',
            'msg' => 'Invalid UserKey',
        ], 401);
    }

    $historyQuery = HistoryStock::where('id_store', $user->id_store);

    if ($lastSyncTime && $lastSyncTime > 1) {
        // Assuming 'updated_at' is a Unix timestamp (like in your sample)
        $historyQuery->where('updated_at', '>', $lastSyncTime);
    }

    $historyStocks = $historyQuery->get();

    // return response()->json([
    //     'status' => true,
    //     'errCode' => $historyStocks->isEmpty() ? '02' : '00',
    //     'msg' => $historyStocks->isEmpty() ? 'No Stock History' : 'Success',
    //     'data' => $historyStocks
    // ]);
   //  $stocks = $stockQuery->orderByDesc('id_stock')->get();

        if ($historyStocks->isEmpty()) {
            return response()->json([
                'status' => true,
                'errCode' => '02',
                'msg' => 'No Stock History Found',
                'data' => []
            ]);
        }

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


    /**
     * Insert or update stock history record
     */
    public function syncHistory(Request $request)
    {
        $userKey = $request->query('UserKey');

        if (!$userKey) {
            return response()->json([
                'status' => false,
                'errCode' => '01',
                'msg' => 'UserKey is required',
            ], 400);
        }

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

        if (!$user) {
            return response()->json([
                'status' => false,
                'errCode' => '03',
                'msg' => 'Invalid UserKey',
            ], 401);
        }

        $validator = Validator::make($request->all(), [
            'local_id_history_stock' => 'required|string',
            'id_history_stock' => 'nullable|numeric',
            'user' => 'nullable|string',
            'id_product' => 'required',
            'id_store' => 'required|numeric',
            'detail' => 'nullable|string',
            'status' => 'required|in:1,0',
            'stock' => 'required|numeric|min:0',
            'date' => 'nullable|date',
            'updated_at' => 'nullable',
        ]);

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

        $data = $validator->validated();

        try {
            DB::beginTransaction();

            $updatedAt = $data['updated_at'] ?? now();

            // Find by local_id or cloud id
            $history = HistoryStock::where('local_id_history_stock', $data['local_id_history_stock'])
                ->orWhere('id_history_stock', $data['id_history_stock'] ?? 0)
                ->lockForUpdate()
                ->first();

            if ($history) {
                // If existing is newer, skip update
                if ($history->updated_at >= $updatedAt) {
                    DB::commit();
                    return response()->json([["status" => "success"]]);
                }

                $history->fill($data);
            } else {
                // Create new history record
                $history = new HistoryStock($data);
                $history->detail = $data['detail'] ?? '';
                $history->date = $data['date'] ?? now();
                $history->stock_applied = false;
            }

            // Apply stock if not already applied
            if (!$history->stock_applied) {
                $stock = Stock::where('id_product', $data['id_product'])
                    ->where('id_store', $data['id_store'])
                    ->lockForUpdate()
                    ->first();

                if (!$stock) {
                    $stock = Stock::create([
                        'local_id_stock' => $data['local_id_stock'],
                        'id_product' => $data['id_product'],
                        'id_store' => $data['id_store'],
                        'stock' => $data['stock'],
                        'cost' => $cost,
                        'user' => $data['user'] ?? null,
                        'session' => $data['session'] ?? null,
                        'updated_at' => $updatedAt,
                    ]);
                }

                if ($data['status'] === '0') {
                    $stock->stock += $data['stock'];
                } elseif ($data['status'] === '1') {
                    $stock->stock = max(0, $stock->stock - $data['stock']);
                }

                $stock->save();
                $history->stock_applied = true;
            }

            $history->updated_at = $updatedAt;
            $history->save();

            DB::commit();

            return response()->json([["status" => "success"]]);
        } catch (\Throwable $e) {
            DB::rollBack();

            Log::error('Failed to sync history stock', [
                'error' => $e->getMessage(),
                'data' => $request->all(),
            ]);

            return response()->json([
                'status' => 'error',
                'message' => 'Failed to sync history stock.',
            ], 500);
        }
    }

}

