<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\SkuMaster as Sku;
use App\Models\CustomerVendor;
use Illuminate\Support\Facades\Validator;
use App\Models\SkuApproval;
use App\Models\SkuMaster;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Carbon;
use App\Models\SkuMovement;

class SKUController extends Controller
{
    public function skuMaster()
    {
        return view('admin.sku.skumaster');
    }

    // For DataTables AJAX
    public function skuData()
    {
        $skus = Sku::all();

        $data = [];
        foreach ($skus as $i => $sku) {
            $data[] = [
                'slno' => $i + 1,
                'item_name' => $sku->item_name,
                'category' => $sku->category,
                'uom' => $sku->uom,
                'current_stock' => $sku->current_stock,
                'default_price' => $sku->default_price,
                'stock_status' => $sku->current_stock > 0 ? 'In Stock' : 'Out of Stock',
                'min_order_level' => $sku->min_order_level,
                'max_order_level' => $sku->max_order_level,
                'actions' => view('admin.sku.partials.actions', compact('sku'))->render(),
            ];
        }

        return response()->json(['data' => $data]);
    }

    // Store new SKU
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'item_name' => 'required|string|max:255',
            'category' => 'required|string|max:255',
            'uom' => 'required|string|max:255',
            'tax_rate' => 'required|numeric',
            'current_stock' => 'required|integer',
            'default_price' => 'required|numeric',
            'min_order_level' => 'required|integer',
            'max_order_level' => 'required|integer',
        ]);
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }
        Sku::create($request->all());
        return response()->json(['success' => 'SKU added successfully!']);
    }

    // Show details for edit
    public function edit($id)
    {
        $sku = Sku::findOrFail($id);
        return response()->json($sku);
    }

    // Update SKU
    public function update(Request $request, $id)
    {
        $sku = Sku::findOrFail($id);

        $validator = Validator::make($request->all(), [
            'item_name' => 'required|string|max:255',
            'category' => 'required|string|max:255',
            'uom' => 'required|string|max:255',
            'tax_rate' => 'required|numeric',
            'current_stock' => 'required|integer',
            'default_price' => 'required|numeric',
            'min_order_level' => 'required|integer',
            'max_order_level' => 'required|integer',
        ]);
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }
        $sku->update($request->all());
        return response()->json(['success' => 'SKU updated successfully!']);
    }

    // Delete SKU
    public function destroy($id)
    {
        $sku = Sku::findOrFail($id);
        $sku->delete();
        return response()->json(['success' => 'SKU deleted successfully!']);
    }

    // SKU Approval Page
    public function skuApproval()
    {
        // Fetch customers with role 'Customer'
        $customers = Customervendor::where('company_role', 'Customer')->pluck('company', 'id');
        // Fetch all items from SKU master
        $items = Sku::pluck('item_name', 'id');
        return view('admin.sku.skuapproval', compact('customers', 'items'));
    }

    // SKU Approval DataTable
    public function skuApprovalList()
    {
        $approvals = SkuApproval::with('customer')->orderBy('id', 'desc')->get();
        $allSkus = Sku::pluck('item_name', 'id'); // [id => name]

        $data = [];
        foreach ($approvals as $approval) {
            // Prepare item names from CSV IDs
            $itemIds = is_array($approval->items) ? $approval->items : explode(',', $approval->items);
            $itemNames = [];
            foreach ($itemIds as $id) {
                $id = trim($id);
                if (isset($allSkus[$id])) $itemNames[] = $allSkus[$id];
            }

            $data[] = [
                'id' => $approval->id,
                'customer' => $approval->customer ? $approval->customer->company : '', // <-- This is safe!
                'items' => implode(', ', $itemNames),
                'date' => $approval->date ? $approval->date->format('d-m-Y') : '',
                'approved_date' => $approval->approved_date ? $approval->approved_date->format('d-m-Y') : '',
                'status' => $approval->status,
                'action_date' => $approval->action_date ? $approval->action_date->format('d-m-Y') : '',
                'action_by' => $approval->action_by,
                'created_by' => $approval->created_by,
                'stock_status' => $approval->stock_status,
            ];
        }

        return response()->json(['data' => $data]);
    }



    // SKU Approval Create
    public function skuApprovalStore(Request $request)
{
    $validator = Validator::make($request->all(), [
        'customer' => 'required', // Not 'customer_id'
        'items' => 'required|string',
        'date' => 'required|date',
        'approved_date' => 'nullable|date',
        'status' => 'required|string|max:50',
        'action_date' => 'nullable|date',
        'action_by' => 'nullable|string|max:255',
        'created_by' => 'required|string|max:255',
        'stock_status' => 'required|string|max:50',
    ]);
    if ($validator->fails()) {
        return response()->json($validator->errors(), 422);
    }

    // Map 'customer' field to 'customer_id'
    $data = $request->all();
    $data['customer_id'] = $data['customer'];
    unset($data['customer']); // Remove 'customer' so it doesn't try to insert a non-existent column

    SkuApproval::create($data);
    return response()->json(['success' => true]);
}
    // SKU Approval Show/Edit
    public function skuApprovalShow($id)
    {
        $approval = SkuApproval::with('customer')->findOrFail($id);

        return response()->json([
            'id' => $approval->id,
            'customer_id' => $approval->customer_id,
            'customer_name' => $approval->customer ? $approval->customer->company : '',
            'items' => $approval->items,
            'date' => $approval->date ? date('Y-m-d', strtotime($approval->date)) : '',
            'approved_date' => $approval->approved_date ? date('Y-m-d', strtotime($approval->approved_date)) : '',
            'status' => $approval->status,
            'action_date' => $approval->action_date ? date('Y-m-d', strtotime($approval->action_date)) : '',
            'action_by' => $approval->action_by,
            'created_by' => $approval->created_by,
            'stock_status' => $approval->stock_status
        ]);
    }

    // SKU Approval Update
    public function skuApprovalUpdate(Request $request, $id)
    {
        $approval = SkuApproval::findOrFail($id);
        $validator = Validator::make($request->all(), [
            'customer' => 'required|string|max:255',
            'items' => 'required|string',
            'date' => 'required|date',
            'approved_date' => 'nullable|date',
            'status' => 'required|string|max:50',
            'action_date' => 'nullable|date',
            'action_by' => 'nullable|string|max:255',
            'created_by' => 'required|string|max:255',
            'stock_status' => 'required|string|max:50',
        ]);
        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }
        $approval->update($request->all());
        return response()->json(['success' => true]);
    }

    // SKU Approval Delete
    public function skuApprovalDestroy($id)
    {
        $approval = SkuApproval::findOrFail($id);
        $approval->delete();
        return response()->json(['success' => true]);
    }

    // In adminSKUController

    public function skuMovement()
    {
        // Pass SKUs and Locations for dropdowns
        $skus = SkuMaster::all(); // or pluck('item_name', 'id')
        $locations = ['Warehouse A', 'Warehouse B', 'Store 1', 'Store 2'];
        return view('admin.sku.skumovement', compact('skus', 'locations'));
    }

    public function skuMovementList(Request $request)
{
    $query =SkuMovement::query()
        ->leftJoin('skumaster', 'sku_movements.sku_id', '=', 'skumaster.id')
        ->select(
    'sku_movements.*',
    'skumaster.item_name as item_name'
);

    // Filtering
    if ($request->status) $query->where('sku_movements.status', $request->status);
    if ($request->type) $query->where('sku_movements.type', $request->type);
    if ($request->date) $query->whereDate('sku_movements.date', $request->date);
    if ($request->search) {
        $search = $request->search;
        $query->where(function ($q) use ($search) {
            $q->where('sku_movements.reference', 'like', "%$search%")
                ->orWhere('sku_movements.from_location', 'like', "%$search%")
                ->orWhere('sku_movements.to_location', 'like', "%$search%")
                ->orWhere('skumaster.item_name', 'like', "%$search%");
        });
    }
\Log::info($query->toSql());
    $movements = $query->orderBy('sku_movements.date', 'desc')->get();

    return response()->json(['data' => $movements]);
}
   

    public function skuMovementStore(Request $request)
    {
        Log::info('SKUMOVE SUBMIT:', $request->all());
        $data = $request->validate([
            'reference' => 'required|unique:sku_movements,reference,' . $request->id,
            'sku_id' => 'required|exists:skumaster,id',
            'type' => 'required',
            'quantity' => 'required|integer|min:1',
            'from_location' => 'nullable|string',
            'to_location' => 'nullable|string',
            'date' => 'required|date',
            'status' => 'required',
            'notes' => 'nullable|string'
        ]);

        if ($request->id) {
            $movement = SkuMovement::findOrFail($request->id);
            $movement->update($data);
        } else {
            $movement = SkuMovement::create($data);
        }

        return response()->json(['success' => true]);
    }

    public function skuMovementDelete($id)
    {
        SkuMovement::findOrFail($id)->delete();
        return response()->json(['success' => true]);
    }

    public function skuMovementShow($id)
    {
        $movement = SkuMovement::findOrFail($id);
        return response()->json($movement);
    }
}
