<?php

namespace App\Http\Controllers;

use App\Models\Branch;
use App\Models\Employee;
use App\Models\Requisition;
use App\Models\ItemCategory;
use Illuminate\Http\Request;
use App\Models\RequisitionItem;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\Storage;

class RequisitionController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:requisition_index', ['only' => ['create']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {


        if (auth()->user()->hasPermissionTo('requisition_approve')) {
            $list = Requisition::with('user', 'employee')->where('status', 'Approved')->get();
        } else {
            $list = Requisition::with('user', 'employee')->where('status', 'Approved')->where('creator_user_id', Auth::id())->get();
        }
        return view('requisition.index', [
            'page_title' => 'Requisition List',
            'list' => $list
        ]);
    }
    public function pendingRequisition()
    {

        if (auth()->user()->hasPermissionTo('requisition_approve')) {
            $list = Requisition::with('user', 'employee')->where('status', 'Pending')->paginate('100');
        } else {
            $list = Requisition::with('user', 'employee')->where('status', 'Pending')->where('creator_user_id', Auth::id())->paginate('100');
        }

        return view('requisition.pending', [
            'page_title' => 'Requisition List',
            'list' => $list
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('requisition.create', [
            'employees' => Employee::where('status', "active")->get(),
            'categories' => ItemCategory::all(),
            'branches' => Branch::all(),
            'page_title' => 'Add New Requisition'
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'products' => 'array|required',
            'employee_id' => 'required',
            'purposes' => 'required',
            'location' => 'required',
            'auth_file' => 'nullable|mimes:pdf,jpeg,png,jpg|max:2048',
        ]);

        DB::beginTransaction();
        $requisition = new Requisition();
        $requisition->requisition_number = "RQ-" . \App\Classes\RequisitionNumber::serial_number();
        $requisition->remark = $request->remark;
        $requisition->location = $request->location;
        $requisition->purposes = $request->purposes;
        $requisition->recommendation = $request->recommendation;
        $requisition->branch_id = $request->branch_id;
        $requisition->employee_id = $request->employee_id;
        $requisition->creator_user_id = Auth::id();

        if ($request->auth_file != null) {
            // save in s3 if s3 is enabled
            if (checkSettings('store_image_to_s3') === 'enable') {
                $fileName = strtolower(trim(time() . '.' . $request->auth_file->extension()));
                $path = 'requsition/' . $fileName;

                // Store to S3
                $request->auth_file->storeAs('requsition', $fileName, 's3');

                // Optionally make public (if needed)
                Storage::disk('s3')->setVisibility($path, 'public');

                // ✅ Save full URL or path
                $requisition->auth_file = Storage::disk('s3')->url($path); // or just $path
            }else{
                    $fileName = strtolower(trim(time() . '.' . $request->auth_file->extension()));
                    $request->auth_file->move(storage_path('app/public/requsition'), $fileName);
                    $requisition->auth_file = $fileName;
            }
            // save in local storage


        }

        $requisition->save();
        $products = $request->get('products');

        foreach ($products as $key => $product) {
            $item = new RequisitionItem();
            $item->requisition_id = $requisition->id;
            $item->item_id = $product['item_id'];
            $item->quantity = $product['quantity'];
            $item->save();
        }

        DB::commit();

        $request->session()->flash('success_message', 'Requisition Added Successfull');
        return back();
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Requisition  $requisition
     * @return \Illuminate\Http\Response
     */
    public function show(Requisition $requisition)
    {
        return view('requisition.show', [
            'requisition' => $requisition,
            'page_title' => 'Requisition Details'
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Requisition  $requisition
     * @return \Illuminate\Http\Response
     */
    public function edit(Requisition $requisition)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Requisition  $requisition
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Requisition $requisition)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Requisition  $requisition
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        // dd($request->all());
        $requisition = Requisition::find($request->id);
        RequisitionItem::where('requisition_id', $request->id)->delete();
        $requisition->delete();

        $request->session()->flash('success_message', 'Requisition Deleted Successfull');
        return redirect()->back();
    }
    public function test(Request $request)
    {
        $auth = Auth::id();
        $requisition = "";

        if (Auth()->user()->hasAnyPermission(['requisition_approve', 'requisition_print'])) {
            $requisition = DB::table('requisitions')
                ->join('employees', 'employees.id', '=', 'requisitions.employee_id',)
                ->join('branches', 'branches.id', '=', 'requisitions.branch_id')
                ->join('users', 'users.id', '=', 'requisitions.creator_user_id')
                ->select('requisitions.*', 'employees.name', 'branches.name as branchName', 'users.name as author')
                ->paginate(6);
        } else {
            $requisition = Requisition::where('creator_user_id', $auth)->paginate(6);
        }

        return view('requisition.index', ['list' => $requisition]);
    }

    public function requisitioner(Employee $employee, $id)
    {
        return view('requisition.requisitioner');
    }
}
