<?php

namespace App\Http\Controllers;

use App\Helpers\UserHelper;
use App\Http\Services\FactoryServices;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class FactoryController extends Controller
{
    function __construct(protected FactoryServices $factory) {}

    public function getFactory($id)
    {
        $user = auth()->user();
        $findFactory = $this->factory->findFactory($id);
        if ($findFactory->company_id !== $user->belongs_parent && $findFactory->company_id !== $user->id) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }
        $data = $this->factory->getFactory($id);
        return response()->json($data);
    }

    public function getFactoryAll()
    {
        $data = $this->factory->getFactoryAll();
        return response()->json($data);
    }

    public function factoryStore(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'city' => 'nullable|string|max:255',
            'city_area' => 'nullable|string|max:255',
            'city_address' => 'nullable|string|max:255',
            'phone'=>'nullable|string|max:20',
            'venderNo'=>'nullable|string|max:30',
            'f_id' => 'nullable|integer',
        ]);

        $id = Auth::user()->id;
        $company_id = UserHelper::getCompanyId();

        $city = isset($validatedData['city']) ? trim($validatedData['city']) : null;
        $city_area = isset($validatedData['city_area']) ? trim($validatedData['city_area']) : null;
        $city_address = isset($validatedData['city_address']) ? trim($validatedData['city_address']) : null;
        $phone = isset($validatedData['phone']) ? trim($validatedData['phone']) : null;
        $venderNo = isset($validatedData['venderNo']) ? trim($validatedData['venderNo']) : null;
        $data = [
            'name' => trim($validatedData['name']),
            'city' => $city,
            'city_area' => $city_area,
            'city_address' => $city_address,
            'created_user' => $id,
            'company_id' => $company_id,
            'phone'=>$phone,
            'venderNo'=>$venderNo,
            'updated_user' => $id
        ];
            if ($request->f_id) {
                $f_id = $request->f_id;
                if ($this->factory->getFactory($f_id)) {
                    $data['updated_user'] = $id;
                    unset($data['created_user']);
                    $updateData = $this->factory->factoryUpdate($data, $f_id);
                    return response()->json([
                        'message' => '修改成功',
                        'f_id' => $updateData
                    ]);
                }
            } else {
                $createData = $this->factory->factoryStore($data);
                return response()->json([
                    'message' => '建立成功',
                    'f_id' => $createData
                ]);
            }
    }

    public function bdingStore(Request $request)
    {
        $id = Auth::user()->id;
        $company_id = UserHelper::getCompanyId();
        $f_id = $request->id;


        $data = [
            'f_id' => $f_id,
            'name' => trim($request->name),
            'created_user' => $id,
            'company_id' => $company_id,
            'updated_user' => $id
        ];
        $createData = $this->factory->bdingStore($data);

        return response()->json([
            'message' => '建立成功',
            'f_id' => $f_id
        ]);
    }
    public function bdingUpdate(Request $request)
    {
        $id = $request->id;
        $data = [
            'name' => trim($request->name),
            'f_id' =>$request->f_id,
            'updated_user' => Auth::user()->id
        ];
        $bdId = $this->factory->bdingUpdate($data, $id);
        return response()->json([
            'message' => '修改成功',
            'f_id' => $bdId
        ]);
    }
    public function bdingDestory($id)
    {
        $f_id = $this->factory->bdingDstory($id);

        return response()->json([
            'message' => '刪除成功',
            'f_id' => $f_id
        ]);
    }

    public function areaStore(Request $request)
    {
        $id = Auth::user()->id;
        $company_id = $request->company_id ?? $id;
        $f_id = $request->f_id;
        $b_id = $request->b_id;
        $file = $request->file('file');

        if ($this->factory->checkAreaName(trim($request->name),$f_id,$b_id)) {
            return response()->json(['message' => '名稱已存在'], 409);
        }
        if ($file) {
            $fileName = $file->getClientOriginalName();
            $nfileName = time() . '_' . uniqid();
            $filePath = $file->storeAs('public/areaPic/' . $f_id . '/' . $b_id . '_' . $nfileName . '.' . $file->getClientOriginalExtension());
        }
        $data = [
            'name' => $request->name,
            'floor' => $request->floor,
            'pic' => $fileName??null,
            'pic_path' => $filePath??null,
            'b_id' => $b_id,
            'f_id' => $f_id,
            'company_id' => $company_id,
            'created_user' => $id,
            'updated_user' => $id
        ];
        $createData = $this->factory->areaStore($data);
        return response()->json([
            'message' => '建立成功',
            'f_id' => $f_id
        ]);
    }

    public function areaUpdate(Request $request)
    {
        $id = $request->id;
        $data = [
            'b_id' => $request->b_id,
            'name' => trim($request->name),
            'floor' => trim($request->floor),
            'updated_user' => Auth::user()->id
        ];

        $updateData = $this->factory->areaUpdate($data, $id);

        return response()->json([
            'message' => '修改成功',
            'f_id' => $updateData
        ]);
    }

    public function fileUpdate(Request $request)
    {
        $id = $request->id;
        $fileData = $this->factory->areaData($id);
        $f_id = $fileData->f_id;
        $b_id = $fileData->b_id;
        $file = $request->file('file');
        $fileName = $file->getClientOriginalName();
        $nfileName = time() . '_' . uniqid();
        $filePath = $file->storeAs('public/areaPic/' . $f_id . '/' . $b_id . '_' . $nfileName . '.' . $file->getClientOriginalExtension());

        $data = [
            'pic' => $fileName,
            'pic_path' => $filePath,
            'updated_user' => Auth::user()->id
        ];

        $updateFile = $this->factory->fileUpdate($data, $id);
        $relativePath = $updateFile->pic_path;
        return response()->json([
            'message' => '上傳成功',
            'f_id' => $updateFile->f_id,
            'pic' => $updateFile->pic,
            'pic_path' => $updateFile->pic_path = config('app.asset_url') . Storage::url($relativePath)
        ]);
    }

    public function areadestory($id)
    {
        $del = $this->factory->areadestory($id);

        return response()->json([
            'message' => '刪除成功',
            'f_id' => $del
        ]);
    }

    public function picDestory($id)
    {
        $f_id = $this->factory->picDestory($id);

        return response()->json([
            'message' => '刪除成功',
            'f_id' => $f_id
        ]);
    }

    public function listDestory(Request $request)
    {
        $ids = $request->input('ids');
        $this->factory->listDestory($ids);
        return response()->json([
            'message' => '刪除成功'
        ], 200);
    }
}
