<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class StockController extends Controller
{
    /**
     * Get stock data with filtering options
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getStockData(Request $request)
    {
        // Validate request parameters
        $validator = Validator::make($request->all(), [
            'branch_id' => 'nullable|string',
            'category_id' => 'nullable|integer',
            'search' => 'nullable|string|max:100',
            'page' => 'nullable|integer|min:1',
            'limit' => 'nullable|integer|min:1|max:100',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'message' => 'Invalid parameters',
                'errors' => $validator->errors()
            ], 400);
        }

        // Get parameters
        $branchId = $request->input('branch_id');
        $categoryId = $request->input('category_id');
        $search = $request->input('search');
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $offset = ($page - 1) * $limit;

        // Build query
        $query = DB::table('stock')
            ->join('item', 'stock.item_id', '=', 'item.id')
            ->join('tbl_branch', 'stock.branch_id', '=', 'tbl_branch.branch_id')
            ->leftJoin('category', 'item.category_id', '=', 'category.id')
            ->select([
                'stock.id as stock_id',
                'item.id as item_id',
                'item.name as item_name',
                'item.item_code',
                'item.barcode',
                'category.name as category_name',
                'category.id as category_id',
                'tbl_branch.branch_id',
                'tbl_branch.branch_name',
                'stock.quantity',
                'stock.reorder_level',
                'item.selling_price',
                'item.cost_price',
                'item.unit'
            ]);

        // Apply filters
        if ($branchId) {
            $query->where('tbl_branch.branch_id', $branchId);
        }

        if ($categoryId) {
            $query->where('item.category_id', $categoryId);
        }

        if ($search) {
            $query->where(function($q) use ($search) {
                $q->where('item.name', 'like', "%{$search}%")
                  ->orWhere('item.item_code', 'like', "%{$search}%")
                  ->orWhere('item.barcode', 'like', "%{$search}%");
            });
        }

        // Get total count for pagination
        $totalCount = $query->count();

        // Get paginated data
        $stockData = $query->orderBy('item.name')
            ->offset($offset)
            ->limit($limit)
            ->get();

        // Get all categories for filter dropdown
        $categories = DB::table('category')
            ->select(['id', 'name'])
            ->orderBy('name')
            ->get();

        // Get all branches for filter dropdown
        $branches = DB::table('tbl_branch')
            ->select(['branch_id', 'branch_name'])
            ->orderBy('branch_name')
            ->get();

        return response()->json([
            'status' => 'success',
            'data' => [
                'stock' => $stockData,
                'pagination' => [
                    'total' => $totalCount,
                    'page' => $page,
                    'limit' => $limit,
                    'total_pages' => ceil($totalCount / $limit)
                ],
                'filters' => [
                    'categories' => $categories,
                    'branches' => $branches
                ]
            ]
        ]);
    }
}
