<?php

namespace App\Http\Controllers\API\V4;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Items;
use App\Categories;
use Illuminate\Support\Facades\Validator;
use App\Models\Stock;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class ProductController extends Controller
{

  //  private $imagePath = 'images/products';
    protected $imagePath = 'images/products/';

    /**
     * GET Itemss based on UserKey, have_stock and optional LastSyncTime
     * Example URL params:
     * UserKey=xxxx&have_stock=1&LastSyncTime=timestamp
     */
    public function getProducts(Request $request)
    {
        $key = $request->query('UserKey');
        $haveStock = $request->query('have_stock');
        $lastSyncTime = $request->query('LastSyncTime', null);

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

        // Find master user by phone_number stored in user's master field
        $masterUser = User::where('phone_number', $user->master)->first();
        if (!$masterUser) {
            return response()->json([
                'status' => 'true',
                'errCode' => '00',
                'msg' => 'Master User Not Found',
            ]);
        }

        $query = Items::where('user', $masterUser->phone_number);

        if ($lastSyncTime && $lastSyncTime > 1) {
            $query->where('updated_at_long', '>', $lastSyncTime);
        }

        // You may want to add the have_stock condition here if applicable:
        // if ($haveStock) { $query->where('have_stock', $haveStock); }

        $products = $query->get();

        if ($products->isEmpty()) {
            return response()->json([
                'status' => 'true',
                'errCode' => '02',
                'msg' => 'No Product Available',
            ]);
        }

        $response = [];

        foreach ($products as $product) {
            // Get category name
            $category = Categories::find($product->category_id);

            // Get stock for product or local_id in user's store
            $stock = Stock::where(function($q) use ($product) {
                $q->where('id_product', $product->id)
                  ->orWhere('id_product', $product->local_id);
            })
            ->where('id_store', $user->id_store)
            ->first();

            // Check if product has variables (products with id_master)
            $variableCount = Items::where('id_master', $product->id)
                            ->orWhere('id_master', $product->local_id)
                            ->count();

            $idMasterFlag = $variableCount > 0 ? "1" : "0";

            $stokValue = $stock && $stock->stock !== null ? $stock->stock : 0;

            $response[] = [
                'cloud_id' => $product->id,
                'local_id' => $product->local_id,
                'position' => true,
                'name' => $product->name,
                'unit' => $product->unit,
                'category_id' => $product->category_id,
                'id_master' => $product->id_master,
                'name_category' => $category ? $category->name : null,
                'codeproduct' => $product->codeproduct,
                'type' => $product->type,
                'available' => $product->available,
                'tax' => $product->tax,
                'purchase_price' => $product->purchase_price,
                'selling_price' => $product->selling_price,
                'stock' => $stokValue,
                'minstock' => $product->minimalstock,
                'discount' => $product->discount ?? 0,
                'online' => $product->online ?? 0,
                'havestok' => $product->have_stock ?? 0,
                'wholesale_price' => $product->wholesale_price,
                'online_price' => $product->price ?? 0,
                'minimum_purchase' => $product->minimum_purchase,
                'description' => $product->description,
                'showing' => $product->showing,
                'preorder' => $product->preorder,
                'user' => $masterUser->phone_number,
                'created_at' => $masterUser->created_at,
                'img' => url("images/products/{$product->image}_thumbnail.jpg"),
                'alertstock' => $product->alertstock ?? 0,
                'updated_at' => $product->updated_at_long,
            ];
        }

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

    /**
     * POST Product Sync - Insert or Update Product data
     */
    public function syncProduct(Request $request)
    {
        $key = $request->input('UserKey');
        $user = User::where('id_session', $key)->first();

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

         $validator = Validator::make($request->all(), [
            'local_id' => 'required|string',
        ]);

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

        $localId = $request->input('local_id');
        $cloudId = $request->input('cloud_id') ?: 0;

        $name = $request->input('name');
        $unit = $request->input('unit');
        $codeproduct = $request->input('codeproduct');
        $categoryId = $request->input('category_id');
        $sellingPrice = $request->input('selling_price');
        $purchasePrice = $request->input('purchase_price');
        $wholesalePrice = $request->input('online_price');
        $idMaster = $request->input('id_master');
        $stock = $request->input('stock');
        $minStock = $request->input('minstock');
        $description = $request->input('description');
        $discount = $request->input('discount');
        $haveStock = $request->input('havestok');
        $type = $request->input('type');
        $available = $request->input('available');
        $tax = $request->input('tax');
        $image = $request->file('img');
        $alertStock = $request->input('alertstock');
        $online = $request->input('online');
        $userPhone = $request->input('user');
        $showing = $request->input('showing');
        $createdAtInput = $request->input('created_at');
        $updatedAtLong = $request->input('updated_at');
        $minimumPurchase = $request->input('minimum_purchase', $request->input('available'));

        $newOnlinePrice = $wholesalePrice ?: $sellingPrice;

        $createdAt = $createdAtInput ?: now()->toDateTimeString();

        // Find existing product by local_id or cloud id
        $product = Items::where('local_id', $localId)
            ->orWhere('id', $cloudId)
            ->first();

        if ($product) {
            if ($product->updated_at_long !== null && $product->updated_at_long >= $updatedAtLong) {
                return response()->json([["status" => "success"]]);
            }

            // Only update image if a new one is uploaded
            if ($request->hasFile('img')) {
                $product->image = $this->saveImageVersions(
                    $this->imagePath,
                    $request->file('img'),
                    [
                        ['name' => 'large', 'w' => 590, 'h' => 400],
                        ['name' => 'medium', 'w' => 295, 'h' => 200],
                        ['name' => 'thumbnail', 'w' => 200, 'h' => 200],
                    ]
                );
            }

            $product->update([
                'name' => $name,
                'local_id' => $localId,
                'unit' => $unit,
                'category_id' => $categoryId,
                'purchase_price' => $purchasePrice,
                'codeproduct' => $codeproduct,
                'tax' => $tax,
                'selling_price' => $sellingPrice,
                'stock' => $stock,
                'alertstock' => $alertStock,
                'minimalstock' => $minStock,
                'online' => $online,
                'wholesale_price' => $newOnlinePrice,
                'price' => $newOnlinePrice,
                'minimum_purchase' => $minimumPurchase,
                'have_stock' => $haveStock,
                'description' => $description,
                'id_master' => $idMaster,
                'type' => $type,
                'available' => $available,
                'showing' => $showing,
                'updated_at_long' => $updatedAtLong,
                'user' => $userPhone,
                'created_at' => $createdAt,
            ]);
        } else {
            $imageName = null;
            if ($request->hasFile('img')) {
                $imageName = $this->saveImageVersions(
                    $this->imagePath,
                    $request->file('img'),
                    [
                        ['name' => 'large', 'w' => 590, 'h' => 400],
                        ['name' => 'medium', 'w' => 295, 'h' => 200],
                        ['name' => 'thumbnail', 'w' => 200, 'h' => 200],
                    ]
                );
            }

            Items::create([
                'name' => $name,
                'local_id' => $localId,
                'unit' => $unit,
                'category_id' => $categoryId,
                'purchase_price' => $purchasePrice,
                'codeproduct' => $codeproduct,
                'tax' => $tax,
                'selling_price' => $sellingPrice,
                'stock' => $stock,
                'alertstock' => $alertStock,
                'minimalstock' => $minStock,
                'online' => $online,
                'wholesale_price' => $newOnlinePrice,
                'price' => $newOnlinePrice,
                'minimum_purchase' => $minimumPurchase,
                'have_stock' => $haveStock,
                'description' => $description,
                'id_master' => $idMaster,
                'type' => $type,
                'available' => $available,
                'showing' => $showing,
                'updated_at_long' => $updatedAtLong,
                'user' => $userPhone,
                'created_at' => $createdAt,
                'image' => $imageName ?: 'imageno',
            ]);
        }

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

}