<?php

namespace App\Http\Controllers;

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

class AutoController extends Controller
{
    private function ordersQuery()
    {
        return DB::table('auto_orders as o')
            ->leftJoin('purposes as p', 'p.id', '=', 'o.purpose_id')
            ->leftJoin('concerns as c', 'c.id', '=', 'o.car_category')
            ->selectRaw('o.*, o.ordered_customer as customer, p as "purposeOne"')
            ->selectRaw('o.*, o.ordered_customer as customer')
            ->addSelect([
                'purpose_uz' => DB::table('purposes')->select('uz')->whereColumn('id', 'o.purpose_id'),
                'purpose_ru' => DB::table('purposes')->select('ru')->whereColumn('id', 'o.purpose_id'),
                'purpose_cr' => DB::table('purposes')->select('cr')->whereColumn('id', 'o.purpose_id'),
                'concern_name' => DB::table('concerns')->select('name')->whereColumn('id', 'o.car_category'),
            ]);
    }

    public function index(Request $request)
    {
        $filters = $request->only(['search', 'period', 'status', 'appraiser', 'purpose_id', 'car_category']);
        $size = $request->get('size', 20);

        $query = DB::table('auto_orders as o')
            ->selectRaw('o.*, o.ordered_customer as customer, CONCAT_WS(\' \', o.owner_last_name, o.owner_first_name, o.owner_patronymic) as "ownerName"')
            ->addSelect([
                'purpose_uz' => DB::table('purposes')->select('uz')->whereColumn('id', 'o.purpose_id'),
                'purpose_ru' => DB::table('purposes')->select('ru')->whereColumn('id', 'o.purpose_id'),
                'purpose_cr' => DB::table('purposes')->select('cr')->whereColumn('id', 'o.purpose_id'),
                'concern_uz' => DB::table('concerns')->select('uz')->whereColumn('id', 'o.car_category'),
                'concern_ru' => DB::table('concerns')->select('ru')->whereColumn('id', 'o.car_category'),
                'concern_cr' => DB::table('concerns')->select('cr')->whereColumn('id', 'o.car_category'),
            ])
            ->orderByDesc('o.id');

        if (!empty($filters['search'])) {
            $s = '%' . $filters['search'] . '%';
            $query->where(function ($q) use ($s) {
                $q->where('o.number', 'like', $s)->orWhere('o.ordered_customer', 'like', $s);
            });
        }
        if (!empty($filters['status']))      $query->where('o.status', $filters['status']);
        if (!empty($filters['purpose_id']))  $query->where('o.purpose_id', $filters['purpose_id']);
        if (!empty($filters['car_category'])) $query->where('o.car_category', $filters['car_category']);

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

        $orders = $rawOrders->through(function ($o) {
            $o->purposeOne = (object)['uz' => $o->purpose_uz, 'ru' => $o->purpose_ru, 'cr' => $o->purpose_cr];
            $o->concernOne = (object)['uz' => $o->concern_uz, 'ru' => $o->concern_ru, 'cr' => $o->concern_cr];
            return $o;
        });

        $stats = DB::table('auto_orders')->selectRaw('status, count(*) as cnt')->groupBy('status')->pluck('cnt', 'status');
        $purposeCases = DB::table('purposes')->get();
        $concerns = DB::table('concerns')->get();

        return view('auto.index', compact('orders', 'stats', 'filters', 'size', 'purposeCases', 'concerns'));
    }

    public function create()
    {
        $concerns = DB::table('concerns')->get();
        $purposeCases = DB::table('purposes')->get();
        $regions = DB::table('regions')->get();
        $appraisers = DB::table('users')->whereRaw('LOWER(role) = ?', ['appraiser'])->where('status', 'active')->get();
        $dillers = DB::table('users')->whereRaw('LOWER(role) = ?', ['diller'])->where('status', 'active')->get();
        return view('auto.create', compact('concerns', 'purposeCases', 'regions', 'appraisers', 'dillers'));
    }

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

    public function edit($id)
    {
        $order = DB::table('auto_orders')->find($id);
        $concerns = DB::table('concerns')->get();
        $purposeCases = DB::table('purposes')->get();
        $regions = DB::table('regions')->get();
        $appraisers = DB::table('users')->whereRaw('LOWER(role) = ?', ['appraiser'])->where('status', 'active')->get();
        $dillers = DB::table('users')->whereRaw('LOWER(role) = ?', ['diller'])->where('status', 'active')->get();
        return view('auto.edit', compact('order', 'concerns', 'purposeCases', 'regions', 'appraisers', 'dillers'));
    }

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

    public function show($order)
    {
        $order = DB::table('auto_orders as o')
            ->selectRaw('o.*, o.ordered_customer as customer, CONCAT_WS(\' \', o.owner_last_name, o.owner_first_name, o.owner_patronymic) as "ownerName"')
            ->addSelect([
                'purpose_uz' => DB::table('purposes')->select('uz')->whereColumn('id', 'o.purpose_id'),
                'purpose_ru' => DB::table('purposes')->select('ru')->whereColumn('id', 'o.purpose_id'),
                'purpose_cr' => DB::table('purposes')->select('cr')->whereColumn('id', 'o.purpose_id'),
                'concern_uz' => DB::table('concerns')->select('uz')->whereColumn('id', 'o.car_category'),
                'concern_ru' => DB::table('concerns')->select('ru')->whereColumn('id', 'o.car_category'),
                'concern_cr' => DB::table('concerns')->select('cr')->whereColumn('id', 'o.car_category'),
            ])
            ->where('o.id', $order)->first();

        if ($order) {
            $order->purposeOne = (object)['uz' => $order->purpose_uz, 'ru' => $order->purpose_ru, 'cr' => $order->purpose_cr];
            $order->concernOne = (object)['uz' => $order->concern_uz, 'ru' => $order->concern_ru, 'cr' => $order->concern_cr];
        }

        if ($order) {
            $dillerUser = $order->diller_id ? DB::table('users')->find($order->diller_id) : null;
            $order->diller = $dillerUser->name ?? '';
            $order->dillerUser = $dillerUser;
        }

        $members = DB::table('order_members as om')
            ->leftJoin('users as u', 'u.id', '=', 'om.user_id')
            ->select('om.*', 'u.name', 'u.avatar', 'u.phone', 'u.role')
            ->where('om.order_id', $order->id ?? 0)->where('om.order_type', 'auto_')->get();
        $appraisers = DB::table('users')->whereRaw('LOWER(role) = ?', ['appraiser'])->where('status', 'active')->get();
        $isAppraisers = $members->where('user_id', auth()->id())->count() > 0;
        $files = DB::table('files')->where('order_id', $order->id ?? 0)->where('order_type', 'auto_')->get();
        $conclusions = DB::table('files')->where('order_id', $order->id ?? 0)->where('order_type', 'conclusion_')->get();
        return view('auto.show', compact('order', 'members', 'appraisers', 'isAppraisers', 'files', 'conclusions'));
    }

    public function showActivities($order)
    {
        $order = DB::table('auto_orders')->find($order);
        $actions = DB::table('tracking_actions')->where('order_id', $order->id ?? 0)->latest()->get();
        return view('auto.show-activities', compact('order', 'actions'));
    }

    public function showTeam($order)
    {
        $order = DB::table('auto_orders')->find($order);
        $members = DB::table('order_members as om')
            ->leftJoin('users as u', 'u.id', '=', 'om.user_id')
            ->select('om.*', 'u.name', 'u.avatar', 'u.phone', 'u.role')
            ->where('om.order_id', $order->id ?? 0)->where('om.order_type', 'auto_')->get();
        $appraisers = DB::table('users')->whereRaw('LOWER(role) = ?', ['appraiser'])->where('status', 'active')->get();
        return view('auto.show-team', compact('order', 'members', 'appraisers'));
    }

    public function showDocuments($order, Request $request)
    {
        $order = DB::table('auto_orders')->find($order);
        $type = $request->get('type', 'ALL');
        $filesQuery = DB::table('files')->where('order_id', $order->id ?? 0)->where('order_type', 'auto_');
        if ($type !== 'ALL') {
            $filesQuery->where('type', $type);
        }
        $files = $filesQuery->paginate(20)->withQueryString();
        $allFiles = DB::table('files')->where('order_id', $order->id ?? 0)->where('order_type', 'auto_')->get();
        $countDocs = $allFiles->whereIn('type', ['passport_customer', 'certificate', 'appraiser_certificate', 'insurance_policy', 'participate_certificate'])->count();
        $countMediaFiles = $allFiles->whereIn('type', ['object_photo', 'object_files', 'compares'])->count();
        $otherFiles = $allFiles->where('type', 'additional')->count();
        return view('auto.show-documents', compact('order', 'files', 'type', 'countDocs', 'countMediaFiles', 'otherFiles'));
    }

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