<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderMembersController extends Controller
{
    public function invite(Request $request)
    {
        $orderId   = $request->input('order_id');
        $orderType = $request->input('order_type'); // 'AUTO' or 'ESTATE'
        $dbType    = $orderType === 'AUTO' ? 'auto_' : 'estate_';
        $table     = $orderType === 'AUTO' ? 'auto_orders' : 'estate_orders';

        // Collect checked appraiser IDs (checkboxes named by appraiser->id)
        $appraiserIds = [];
        foreach ($request->all() as $key => $value) {
            if (is_numeric($key) && $value === 'on') {
                $appraiserIds[] = (int)$key;
            }
        }

        foreach ($appraiserIds as $userId) {
            // Avoid duplicate
            $exists = DB::table('order_members')
                ->where('order_id', $orderId)
                ->where('order_type', $dbType)
                ->where('user_id', $userId)
                ->exists();

            if (!$exists) {
                DB::table('order_members')->insert([
                    'order_id'   => $orderId,
                    'order_type' => $dbType,
                    'user_id'    => $userId,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }
        }

        // Change status to started if members added
        if (count($appraiserIds) > 0) {
            DB::table($table)->where('id', $orderId)->update([
                'status'     => 'started',
                'updated_at' => now(),
            ]);
        }

        return redirect()->back();
    }

    public function remove(Request $request)
    {
        $memberId  = $request->input('id');
        $orderId   = $request->input('order_id');
        $orderType = $request->input('order_type'); // 'AUTO' or 'ESTATE'
        $dbType    = $orderType === 'AUTO' ? 'auto_' : 'estate_';

        DB::table('order_members')
            ->where('id', $memberId)
            ->where('order_id', $orderId)
            ->where('order_type', $dbType)
            ->delete();

        return redirect()->back();
    }
}
