<?php

namespace App\Http\Controllers;

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

class DebitController extends Controller
{
    public function index(Request $request)
    {
        $filters = $request->only(['search', 'status', 'appraiser']);
        $size = $request->get('size', 20);

        $query = DB::table('debits as d')
            ->leftJoin('users as u', 'u.id', '=', 'd.appraiser_id')
            ->select('d.*')
            ->selectRaw('u.name as appraiser_name, u.id as appraiser_user_id')
            ->orderByDesc('d.id');

        if (!empty($filters['appraiser'])) $query->where('d.appraiser_id', $filters['appraiser']);
        if (!empty($filters['status']))    $query->where('d.status', $filters['status']);

        $rawDebits = $query->paginate($size)->withQueryString();

        $debits = $rawDebits->through(function ($d) {
            $d->appraiser = (object)['id' => $d->appraiser_user_id, 'name' => $d->appraiser_name];
            // get order number
            if ($d->order_id && $d->order_type) {
                $table = $d->order_type === 'auto_' ? 'auto_orders' : 'estate_orders';
                $ord = DB::table($table)->select('id', 'number')->find($d->order_id);
                $d->order = $ord;
            } else {
                $d->order = null;
            }
            return $d;
        });

        $appraisers = DB::table('users')->whereRaw('LOWER(role) = ?', ['appraiser'])->get();
        $debit = null;
        $appraiser = null;

        return view('debit.index', compact('debits', 'appraisers', 'filters', 'debit', 'appraiser', 'size'));
    }

    public function create()
    {
        $appraisers = DB::table('users')->whereRaw('LOWER(role) = ?', ['appraiser'])->get();
        return view('debit.create', compact('appraisers'));
    }

    public function store(Request $request)
    {
        return redirect()->route('debit.index');
    }

    public function show($id)
    {
        $debit = DB::table('debits')->find($id);
        return view('debit.show', compact('debit'));
    }

    public function edit($id)
    {
        $debit = DB::table('debits')->find($id);
        $appraisers = DB::table('users')->whereRaw('LOWER(role) = ?', ['appraiser'])->get();
        return view('debit.edit', compact('debit', 'appraisers'));
    }

    public function update(Request $request, $id)
    {
        return redirect()->route('debit.index');
    }

    public function destroy($id)
    {
        return redirect()->route('debit.index');
    }
}
