<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Device;
use App\Models\DeviceReturn;
use App\Models\StockMovement;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ReturnController extends Controller
{
    //


    public function index(Request $request)
    {
        $query = DeviceReturn::with([
            'device',
            'returnedBy',
            'receivedBy',
            'borderStation'
        ]);

        if (
            $request->user()->hasRole('Sales')
        ) {

            $query->where(
                'returned_by',
                $request->user()->id
            );
        }

        return response()->json([

            'success' => true,

            'returns' => $query
                ->latest()
                ->get()

        ]);
    }


    public function store(Request $request)
    {
        $request->validate([
            'device_ids' => ['required', 'array'],
            'remarks'    => ['nullable', 'string'],
        ]);

        DB::beginTransaction();

        try {

            $user = auth()->user();

            $returnNo = 'RTN'
                . now()->format('y')
                . str_pad(
                    DeviceReturn::count() + 1,
                    5,
                    '0',
                    STR_PAD_LEFT
                );

            foreach ($request->device_ids as $deviceId) {

                $device = Device::findOrFail($deviceId);

                /*
            |--------------------------------------------------------------------------
            | Security Validation
            |--------------------------------------------------------------------------
            */

                if (
                    $user->hasRole('Sales') &&
                    $device->sales_user_id != $user->id
                ) {
                    throw new \Exception(
                        "Device {$device->serial_number} does not belong to you."
                    );
                }

                if (
                    $user->hasRole('Border Staff') &&
                    $device->status !== 'border_stock'
                ) {
                    throw new \Exception(
                        "Device {$device->serial_number} is not in Border Stock."
                    );
                }

                /*
            |--------------------------------------------------------------------------
            | Create Return
            |--------------------------------------------------------------------------
            */

                DeviceReturn::create([

                    'return_no' =>
                    $returnNo,

                    'device_id' =>
                    $device->id,

                    'return_source' =>
                    $user->hasRole('Border Staff')
                        ? 'border'
                        : 'sales',

                    'returned_by' =>
                    $user->id,

                    'border_station_id' =>
                    $user->hasRole('Border Staff')
                        ? $user->border_station_id
                        : null,

                    'remarks' =>
                    $request->remarks,

                    'returned_at' =>
                    now(),

                    'status' =>
                    'pending',
                ]);

                /*
            |--------------------------------------------------------------------------
            | Update Device
            |--------------------------------------------------------------------------
            */

                $device->update([
                    'status' => 'pending'
                ]);

                /*
            |--------------------------------------------------------------------------
            | Stock Movement
            |--------------------------------------------------------------------------
            */

                StockMovement::create([

                    'device_id' =>
                    $device->id,

                    'movement_type' =>
                    'RETURN_REQUEST',

                    'from_location' =>
                    $user->hasRole('Border Staff')
                        ? 'BORDER_STOCK'
                        : 'SALES_STOCK',

                    'to_location' =>
                    'RETURN_PENDING',

                    'user_id' =>
                    $user->id,

                    'remarks' =>
                    $user->hasRole('Border Staff')
                        ? 'Returned by Border Staff'
                        : 'Returned by Sales User',
                ]);
            }

            DB::commit();

            return response()->json([
                'success'   => true,
                'message'   => 'Devices returned successfully.',
                'return_no' => $returnNo,
            ]);
        } catch (\Exception $e) {

            DB::rollBack();

            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 500);
        }
    }


    public function receive(
        DeviceReturn $deviceReturn
    ) {
        DB::beginTransaction();

        try {

            $deviceReturn->update([

                'status' => 'received',

                'received_by' =>
                auth()->id(),

                'received_at' =>
                now(),
            ]);

            $deviceReturn
                ->device
                ->update([

                    'status' =>
                    'store_stock',

                    'sales_user_id' =>
                    null
                ]);

            StockMovement::create([

                'device_id' =>
                $deviceReturn->device_id,

                'movement_type' =>
                'RETURN_RECEIVED',

                'from_location' =>
                'RETURN_PENDING',

                'to_location' =>
                'STORE_STOCK',

                'user_id' =>
                auth()->id(),

                'remarks' =>
                'Device received back to store',
            ]);

            DB::commit();

            return response()->json([

                'success' => true,

                'message' =>
                'Device received successfully.'
            ]);
        } catch (\Exception $e) {

            DB::rollBack();

            return response()->json([

                'success' => false,

                'message' =>
                $e->getMessage()

            ], 500);
        }
    }
}
