<?php

namespace App\Http\Controllers;

use App\Models\Warehouse;
use App\Models\Branch;
use App\Models\Company;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class WarehouseController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $user = Auth::user();
        $company = $user->company;

        $warehouses = Warehouse::where('company_id', $company->id)
            ->with('branch')
            ->orderBy('name')
            ->get();

        return view('inventory.warehouses.index', compact('warehouses'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $user = Auth::user();
        $company = $user->company;

        $branches = Branch::where('company_id', $company->id)
            ->where('is_active', true)
            ->orderBy('name')
            ->get();

        return view('inventory.warehouses.create', compact('branches'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $user = Auth::user();
        $company = $user->company;

        // تحقق من تفرد الكود على مستوى الشركة
        $codeExists = Warehouse::where('company_id', $company->id)
            ->where('code', $request->code)
            ->exists();

        if ($codeExists) {
            return redirect()->back()
                ->withErrors(['code' => 'كود المستودع مستخدم بالفعل في شركتك'])
                ->withInput();
        }

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50',
            'branch_id' => 'nullable|exists:branches,id',
            'address' => 'nullable|string',
            'manager_name' => 'nullable|string|max:255',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'is_active' => 'boolean',
            'notes' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $warehouse = new Warehouse();
        $warehouse->company_id = $company->id;
        $warehouse->name = $request->name;
        $warehouse->code = $request->code;
        $warehouse->branch_id = $request->branch_id;
        $warehouse->address = $request->address;
        $warehouse->manager_name = $request->manager_name;
        $warehouse->phone = $request->phone;
        $warehouse->email = $request->email;
        $warehouse->is_active = $request->boolean('is_active');
        $warehouse->notes = $request->notes;
        $warehouse->save();

        return redirect()->route('inventory.warehouses.index')
            ->with('success', 'تم إنشاء المستودع بنجاح');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $user = Auth::user();
        $company = $user->company;

        $warehouse = Warehouse::where('company_id', $company->id)
            ->where('id', $id)
            ->with(['branch', 'inventory_stocks.item'])
            ->firstOrFail();

        return view('inventory.warehouses.show', compact('warehouse'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $user = Auth::user();
        $company = $user->company;

        $warehouse = Warehouse::where('company_id', $company->id)
            ->where('id', $id)
            ->firstOrFail();

        $branches = Branch::where('company_id', $company->id)
            ->where('is_active', true)
            ->orderBy('name')
            ->get();

        return view('inventory.warehouses.edit', compact('warehouse', 'branches'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $user = Auth::user();
        $company = $user->company;

        $warehouse = Warehouse::where('company_id', $company->id)
            ->where('id', $id)
            ->firstOrFail();

        // تحقق من تفرد الكود على مستوى الشركة
        $codeExists = Warehouse::where('company_id', $company->id)
            ->where('code', $request->code)
            ->where('id', '!=', $warehouse->id)
            ->exists();

        if ($codeExists) {
            return redirect()->back()
                ->withErrors(['code' => 'كود المستودع مستخدم بالفعل في شركتك'])
                ->withInput();
        }

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50',
            'branch_id' => 'nullable|exists:branches,id',
            'address' => 'nullable|string',
            'manager_name' => 'nullable|string|max:255',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'is_active' => 'boolean',
            'notes' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $warehouse->name = $request->name;
        $warehouse->code = $request->code;
        $warehouse->branch_id = $request->branch_id;
        $warehouse->address = $request->address;
        $warehouse->manager_name = $request->manager_name;
        $warehouse->phone = $request->phone;
        $warehouse->email = $request->email;
        $warehouse->is_active = $request->boolean('is_active');
        $warehouse->notes = $request->notes;
        $warehouse->save();

        return redirect()->route('inventory.warehouses.index')
            ->with('success', 'تم تحديث المستودع بنجاح');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $user = Auth::user();
        $company = $user->company;

        $warehouse = Warehouse::where('company_id', $company->id)
            ->where('id', $id)
            ->firstOrFail();

        // Check if warehouse has any stock
        $hasStock = $warehouse->inventory_stocks()->count() > 0;

        if ($hasStock) {
            return redirect()->back()
                ->with('error', 'لا يمكن حذف المستودع لأنه يحتوي على مخزون');
        }

        $warehouse->delete();

        return redirect()->route('inventory.warehouses.index')
            ->with('success', 'تم حذف المستودع بنجاح');
    }
}
