<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\WhsItem;
use Exception;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
// 
class WhsReportSettingController extends Controller
{

    public function whsItemStore(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Item Store Validation Error: ' . $validator->errors()->first(),
                'report_type' => 'whs_item',
                'error_type' => 'Validation error',
            ]);
            return $this->message($validator->errors()->first(), 422);
        }
        $validatedData = $validator->validated();
        // Retrieve customer_id and workspace_id
        $userTable = $this->getUserTable();
        if ($userTable == "customer") {
            $customer_id = auth()->id();
            $workspace_id = auth()->user()->current_workspace_id;
        } elseif ($userTable == "emp") {
            $customer_id = auth()->user()->customer_id;
            $workspace_id = auth()->user()->workspace_id;
        }
        // Create a new WHS item
        $whs_item = new WhsItem();
        $whs_item->title = $validatedData['title'];
        $whs_item->status = $request->input('status', 1); // Default status to 1 if not provided
        $whs_item->customer_id = $customer_id;
        $whs_item->workspace_id = $workspace_id;
        $whs_item->created_by = auth()->user()->id;
        $whs_item->save();
        if (!$whs_item) {
            return $this->message('something went wrong while saving the item try again', 500);
        }
        return $this->success($whs_item, 'Saved Successfully');
    }

    public function whsItemGet(Request $request)
    {
        $userTable = $this->getUserTable();
        $auth_id = auth()->user()->id;
        $query = WhsItem::query();
        if ($userTable === 'customer') {
            $query->where('customer_id', $auth_id)
                ->where('workspace_id', auth()->user()->current_workspace_id);
        } elseif ($userTable === 'emp') {
            $query->where('customer_id', auth()->user()->customer_id)
                ->where('workspace_id', auth()->user()->workspace_id);
        } else {
            return $this->error('You do not have permission to access these items.', 403);
        }

        // Apply single search filter for title
        if ($request->has('search') && !empty($request->search)) {
            $searchTerm = $request->search;
            $query->where('title', 'like', '%' . $searchTerm . '%');
        }
        $whs_items = $query->orderBy('id', 'desc')->get();
        return $this->withCount($whs_items, 'Retrieved Successfully');
    }

    public function whsItemUpdate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'status' => 'required|integer|in:0,1',
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first(), 422);
        }
        try {
            $userTable = $this->getUserTable();
            $auth_id = auth()->user()->id;
            // Find WHS item
            $whs_item = WhsItem::find($request->id);
            if (!$whs_item) {
                return $this->error('Record not found.', 404);
            }
            if ($userTable === 'customer') {
                if ($whs_item->customer_id !== $auth_id || $whs_item->workspace_id !== auth()->user()->current_workspace_id) {
                    return $this->error('You do not have access to this item.', 403);
                }
            } elseif ($userTable === 'emp') {
                if ($whs_item->customer_id !== auth()->user()->customer_id || $whs_item->workspace_id !== auth()->user()->workspace_id) {
                    return $this->error('You do not have access to this item.', 403);
                }
            }
            $whs_item->title = $request->input('title');
            $whs_item->status = $request->input('status');
            $whs_item->save();
            return $this->success($whs_item, 'Updated Successfully');
        } catch (\Throwable $e) {
            return $this->error('An error occurred while updating the record.', 500);
        }
    }

    public function whsItemDelete($id)
    {
        try {
            // Fetch the WHS item
            $whs_item = WhsItem::find($id);
            if (!$whs_item) {
                return $this->error('Record not found.', 404);
            }
            // Add customer and employee access checks
            $userTable = $this->getUserTable();
            $auth_id = auth()->user()->id;
            if ($userTable === 'customer') {
                if ($whs_item->customer_id !== $auth_id || $whs_item->workspace_id !== auth()->user()->current_workspace_id) {
                    return $this->error('You do not have access to delete this item.', 403);
                }
            } elseif ($userTable === 'emp') {
                if ($whs_item->customer_id !== auth()->user()->customer_id || $whs_item->workspace_id !== auth()->user()->workspace_id) {
                    return $this->error('You do not have access to delete this item.', 403);
                }
            }
            // Delete the WHS item
            $whs_item->delete();
            return $this->message('Deleted Successfully');
        } catch (\Throwable $e) {
            return $this->error('An error occurred while deleting the record.', 500);
        }
    }
}
