<?php

namespace App\Http\Controllers\Inventory;

use App\Http\Controllers\Controller;
use App\Models\Warehouse;
use App\Models\ChartOfAccount;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class WarehouseController extends Controller
{
    /**
     * عرض قائمة المخازن
     */
    public function index()
    {
        $this->authorize('inventory.warehouses.view');

        $warehouses = Warehouse::where('company_id', session('company_id'))
            ->orderBy('name')
            ->paginate(10);

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

    /**
     * عرض نموذج إنشاء مخزن جديد
     */
    public function create()
    {
        $this->authorize('inventory.warehouses.create');

        return view('inventory.warehouses.create');
    }

    /**
     * حفظ مخزن جديد
     */
    public function store(Request $request)
    {
        $this->authorize('inventory.warehouses.create');

        $companyId = session('company_id');

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'code' => 'nullable|string|max:50',
            'address' => 'nullable|string',
            'phone' => 'nullable|string|max:20',
            'manager' => 'nullable|string|max:255',
            'notes' => 'nullable|string',
        ]);

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

        if (Warehouse::where('company_id', $companyId)->where('name', $request->name)->exists()) {
            return redirect()->back()
                ->withErrors(['name' => 'لا يمكن تسجيل مخزن بنفس الاسم. يوجد مخزن بنفس الاسم في هذه الشركة بالفعل.'])
                ->withInput();
        }

        try {
            DB::transaction(function () use ($request, $companyId) {
                $parentAccount = ChartOfAccount::where('company_id', $companyId)
                    ->where('code', '1150')
                    ->first();

                if (!$parentAccount) {
                    throw new \Exception('الحساب الأب 1150 (المخزون) غير موجود في دليل الحسابات');
                }

                $existingAccount = ChartOfAccount::where('company_id', $companyId)
                    ->where('name', $request->name)
                    ->where('parent_id', $parentAccount->id)
                    ->first();

                $chartOfAccountId = null;

                if (!$existingAccount) {
                    $subAccount = ChartOfAccount::create([
                        'company_id' => $companyId,
                        'parent_id' => $parentAccount->id,
                        'name' => $request->name,
                        'code' => $this->generateAccountCode($companyId, $parentAccount->code),
                        'account_type' => 'asset',
                        'balance_type' => 'debit',
                        'is_parent' => false,
                        'is_active' => true,
                        'description' => 'حساب فرعي للمخزن: ' . $request->name,
                    ]);
                    $chartOfAccountId = $subAccount->id;
                } else {
                    $chartOfAccountId = $existingAccount->id;
                }

                $warehouse = new Warehouse();
                $warehouse->company_id = $companyId;
                $warehouse->chart_of_account_id = $chartOfAccountId;
                $warehouse->name = $request->name;
                $warehouse->code = $request->code;
                $warehouse->address = $request->address;
                $warehouse->phone = $request->phone;
                $warehouse->manager = $request->manager;
                $warehouse->is_active = $request->has('is_active');
                $warehouse->notes = $request->notes;
                $warehouse->save();
            });

            return redirect()->route('inventory.warehouses')
                ->with('success', 'تم إنشاء المخزن وحسابه الفرعي بنجاح');
        } catch (\Exception $e) {
            Log::error('خطأ في إنشاء المخزن: ' . $e->getMessage());
            return redirect()->back()
                ->with('error', 'حدث خطأ أثناء إنشاء المخزن: ' . $e->getMessage())
                ->withInput();
        }
    }

    /**
     * عرض تفاصيل المخزن
     */
    public function show(Warehouse $warehouse)
    {
        $this->authorize('inventory.warehouses.view');

        // التحقق من أن المخزن ينتمي للشركة الحالية
        if ($warehouse->company_id != session('company_id')) {
            abort(403);
        }

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

    /**
     * عرض نموذج تعديل المخزن
     */
    public function edit(Warehouse $warehouse)
    {
        $this->authorize('inventory.warehouses.edit');

        // التحقق من أن المخزن ينتمي للشركة الحالية
        if ($warehouse->company_id != session('company_id')) {
            abort(403);
        }

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

    /**
     * تحديث بيانات المخزن
     */
    public function update(Request $request, Warehouse $warehouse)
    {
        $this->authorize('inventory.warehouses.edit');

        $companyId = session('company_id');

        if ($warehouse->company_id != $companyId) {
            abort(403);
        }

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'code' => 'nullable|string|max:50',
            'address' => 'nullable|string',
            'phone' => 'nullable|string|max:20',
            'manager' => 'nullable|string|max:255',
            'notes' => 'nullable|string',
        ]);

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

        if ($warehouse->name !== $request->name) {
            if (Warehouse::where('company_id', $companyId)
                ->where('name', $request->name)
                ->where('id', '!=', $warehouse->id)
                ->exists()) {
                return redirect()->back()
                    ->withErrors(['name' => 'لا يمكن استخدام هذا الاسم. يوجد مخزن بنفس الاسم في هذه الشركة بالفعل.'])
                    ->withInput();
            }

            if ($warehouse->chartOfAccount) {
                $warehouse->chartOfAccount->update(['name' => $request->name]);
            }
        }

        $warehouse->name = $request->name;
        $warehouse->code = $request->code;
        $warehouse->address = $request->address;
        $warehouse->phone = $request->phone;
        $warehouse->manager = $request->manager;
        $warehouse->is_active = $request->has('is_active');
        $warehouse->notes = $request->notes;
        $warehouse->save();

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

    /**
     * حذف المخزن
     */
    public function destroy(Warehouse $warehouse)
    {
        $this->authorize('inventory.warehouses.delete');

        // التحقق من أن المخزن ينتمي للشركة الحالية
        if ($warehouse->company_id != session('company_id')) {
            abort(403);
        }

        // التحقق من عدم وجود أرصدة مخزون مرتبطة بالمخزن
        if ($warehouse->inventoryBalances()->count() > 0) {
            return redirect()->route('inventory.warehouses')
                ->with('error', 'لا يمكن حذف المخزن لوجود أرصدة مخزون مرتبطة به');
        }

        // التحقق من عدم وجود مستندات مخزون مرتبطة بالمخزن
        if ($warehouse->sourceDocuments()->count() > 0 || $warehouse->destinationDocuments()->count() > 0) {
            return redirect()->route('inventory.warehouses')
                ->with('error', 'لا يمكن حذف المخزن لوجود مستندات مخزون مرتبطة به');
        }

        // التحقق من عدم وجود عمليات جرد مرتبطة بالمخزن
        if ($warehouse->inventoryCounts()->count() > 0) {
            return redirect()->route('inventory.warehouses')
                ->with('error', 'لا يمكن حذف المخزن لوجود عمليات جرد مرتبطة به');
        }

        $warehouse->delete();

        return redirect()->route('inventory.warehouses')
            ->with('success', 'تم حذف المخزن بنجاح');
    }

    /**
     * توليد رمز حساب فريد للمخزن الجديد
     */
    private function generateAccountCode($companyId, $parentCode)
    {
        $maxSubCode = ChartOfAccount::where('company_id', $companyId)
            ->where('code', 'like', $parentCode . '%')
            ->where('code', '!=', $parentCode)
            ->get()
            ->map(function ($account) use ($parentCode) {
                $code = str_replace($parentCode, '', $account->code);
                return intval($code);
            })
            ->max();

        $newSubNumber = ($maxSubCode ?? 0) + 1;
        return $parentCode . str_pad($newSubNumber, 2, '0', STR_PAD_LEFT);
    }
}




