<?php

namespace App\Http\Controllers;

use App\Models\SafetyDataSheet;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class SafetyDataSheetController extends Controller
{

    public function index(Request $request)
    {

        $query = SafetyDataSheet::where("del", "0");
        $query = $this->applyCustomerWorkspaceFilter($query);
        if ($request->has('search') && !empty($request->search)) {
            $searchTerm = $request->search;
            $query->where(function ($q) use ($searchTerm) {
                $q->where('title', 'like', '%' . $searchTerm . '%');
                $q->orWhere('revision_date', 'like', '%' . $searchTerm . '%');
                $q->orWhere('expiry_date', 'like', '%' . $searchTerm . '%');
                
            });
        }
        $query->orderBy("id", "DESC");
        return $this->withCount($query, 'Data get Successfully');
    }


    public function show($id)
    {
        $datasheet = SafetyDataSheet::find($id);
        if (!$datasheet) {
            return $this->message('Data Sheet not found!', 404);
        }
        $userTable  = $this->getUserTable();
        if ($userTable === "customer") {
            if ($datasheet->customer_id != auth()->user()->id || $datasheet->workspace_id != auth()->user()->current_workspace_id) {
                return $this->message('You do not have access to this Safety Data Sheet', 403);
            }
        }
        if ($userTable === "emp") {
            if ($datasheet->customer_id != auth()->user()->customer_id || $datasheet->workspace_id != auth()->user()->workspace_id) {
                return $this->message('You do not have access to this Safety Data Sheet', 403);
            }
        }
        return $this->success($datasheet, 'Data Sheet found successfully!');
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string',
            'image' => 'required|mimes:jpeg,png,jpg,gif,pdf,doc,docx|max:10248',
            'revision_date' => 'required|date',
            'expiry_date' => 'required|date'
        ]);
        if ($validator->fails()) {
            $error = $validator->errors()->first();
            $log = [
                "employee_id" => auth()->user()->id,
                "message" => $error,
                "report_id" => 0,
                "report_type" => "safety_data_sheet",
                "error_type" => "Validation error",
            ];
            storeReportsLogs($log);
            return $this->message($error, 422);
        }
        $userTable  = $this->getUserTable();
        $customer_id = 0;
        $workspace_id = 0;
        $created_by = 0;
        if ($userTable === "customer") {
            $customer_id = auth()->user()->id;
            $workspace_id = auth()->user()->current_workspace_id;
            $created_by = auth()->user()->id;
        }
        if ($userTable === "emp") {
            $customer_id = auth()->user()->customer_id;
            $workspace_id = auth()->user()->workspace_id;
            $created_by = auth()->user()->id;
        }
        if ($request->hasFile('image') && $request->file('image')->isValid()) {
            $imageName = $this->handleFileImageUpload($request, 'datasheet')['path'] ?? null;
            $datasheet = new SafetyDataSheet();
            $datasheet->title = $request->title;
            $datasheet->image = $imageName;
            $datasheet->date =  Carbon::today();
            $datasheet->revision_date = $request->revision_date;
            $datasheet->expiry_date = $request->expiry_date;
            $datasheet->created_by = $created_by;
            $datasheet->customer_id = $customer_id;
            $datasheet->workspace_id = $workspace_id;
            $datasheet->save();
            $log = [
                "employee_id" => auth()->user()->id,
                "message" => 'Sheet Added successfully!',
                "report_id" => $datasheet->id ?? 0,
                "report_type" => "safety_data_sheet",
                "error_type" => "success",
            ];
            storeReportsLogs($log);
            return $this->success($datasheet, 'Sheet Added successfully!');
        }
    }

    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'image' => 'nullable|mimes:jpeg,png,jpg,gif,pdf,doc,docx|max:10248',
            'title' => 'required|string',
            'revision_date' => 'required|date',
            'expiry_date' => 'required|date'
        ]);
        if ($validator->fails()) {
            $errors = $validator->errors()->first();
            $log = [
                "employee_id" => auth()->user()->id,
                "message" => $errors,
                "report_id" => $request->id ?? 0,
                "report_type" => "safety_data_sheet",
                "error_type" => "validation error",
            ];
            storeReportsLogs($log);
            return $this->message($errors, 422);
        }
        $datasheet = SafetyDataSheet::find($request->id);
        if (!$datasheet) {
            return $this->message('Data Sheet not found!', 404);
        }
        $userTable  = $this->getUserTable();
        $created_by = 0;
            if ($userTable == "customer" && ($datasheet->workspace_id != auth()->user()->current_workspace_id || $datasheet->customer_id != auth()->user()->id)
            ) {
                return $this->message('You do not have access to this Safety Data Sheet', 403);
            }
        
        if ($userTable === "emp") {
            $created_by = auth()->user()->id;
            if (($datasheet->customer_id != auth()->user()->customer_id || $datasheet->workspace_id != auth()->user()->workspace_id)) {
                return $this->message('You do not have access to this Safety Data Sheet', 403);
            }
        }
        if (!$datasheet) {
            return $this->message('Data Sheet not found!', 404);
        }
        if ($request->hasFile('image') && $request->file('image')->isValid()) {
            $imageName = $this->handleFileImageUpload($request, 'datasheet', $datasheet->image)['path'] ?? null;
            $datasheet->image = $imageName;
        }
        $datasheet->title = $request->title;
        $datasheet->revision_date = $request->revision_date;
        $datasheet->expiry_date = $request->expiry_date;
        $datasheet->created_by = $created_by;
        $datasheet->save();
        $log = [
            "employee_id" => auth()->user()->id,
            "message" => 'Safety Data Sheet Updated Successfully!',
            "report_id" => $request->id ?? 0,
            "report_type" => "safety_data_sheet",
            "error_type" => "success",
        ];
        storeReportsLogs($log);
        return $this->success($datasheet, 'Safety Data Sheet Updated Successfully!');
    }

    public function delete($id)
    {
        $dataSheet = SafetyDataSheet::where('id', $id)->first();
        if (!$dataSheet) {
            return $this->message('Data Sheet not found!', 404);
        }
        if ($dataSheet->del == '1') {
            return $this->message('Data Sheet already deleted!', 400);
        }
        $userTable  = $this->getUserTable();
        if ($userTable === "customer") {
            if ($dataSheet->customer_id != auth()->user()->id || $dataSheet->workspace_id != auth()->user()->current_workspace_id) {
                return $this->message('You do not have access to this Safety Data Sheet', 403);
            }
        }
        if ($userTable === "emp") {
            if ($dataSheet->customer_id != auth()->user()->customer_id || $dataSheet->workspace_id != auth()->user()->workspace_id) {
                return $this->message('You do not have access to this Safety Data Sheet', 403);
            }
        }
        $dataSheet->update(['del' => '1']);
        $log = [
        "employee_id" => auth()->user()->id,
        "message" => 'Data sheet deleted successfully. Id:' . $id,
        "report_id" => $id ?? 0,
        "report_type" => "safety_data_sheet",
        "error_type" => "success",
    ];
        storeReportsLogs($log);
        return $this->message('Data sheet deleted successfully!');
    }
}
