<?php

namespace App\Http\Controllers;

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

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

        $query = DB::table('estate_orders as o')
            ->selectRaw('o.*, o.ordered_customer as customer, CONCAT_WS(\' \', o.owner_last_name, o.owner_first_name, o.owner_patronymic) as owner')
            ->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'),
                'region_uz' => DB::table('regions')->select('uz')->whereColumn('id', 'o.region'),
                'district_uz' => DB::table('districts')->select('uz')->whereColumn('id', 'o.district'),
            ])
            ->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']);

        $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];
            return $o;
        });

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

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

    public function create()
    {
        $purposeCases = DB::table('purposes')->get();
        $regions = DB::table('regions')->get();
        $districts = DB::table('districts')->get();
        $concerns = DB::table('concerns')->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('estate.create', compact('purposeCases', 'regions', 'districts', 'concerns', 'appraisers', 'dillers'));
    }

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

    public function edit($id)
    {
        $order = DB::table('estate_orders')->find($id);
        $purposeCases = DB::table('purposes')->get();
        $regions = DB::table('regions')->get();
        $districts = DB::table('districts')->get();
        $concerns = DB::table('concerns')->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('estate.edit', compact('order', 'purposeCases', 'regions', 'districts', 'concerns', 'appraisers', 'dillers'));
    }

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

    public function show($order)
    {
        $order = DB::table('estate_orders as o')
            ->selectRaw('o.*, o.ordered_customer as customer, CONCAT_WS(\' \', o.owner_last_name, o.owner_first_name, o.owner_patronymic) as owner')
            ->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'),
                'region_uz' => DB::table('regions')->select('uz')->whereColumn('id', 'o.region'),
                'district_uz' => DB::table('districts')->select('uz')->whereColumn('id', 'o.district'),
            ])
            ->where('o.id', $order)->first();

        if ($order) {
            $order->purposeOne = (object)['uz' => $order->purpose_uz, 'ru' => $order->purpose_ru, 'cr' => $order->purpose_cr];
            $order->regions = DB::table('regions')->find($order->region);
            $order->districts = DB::table('districts')->find($order->district);
            $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', 'estate_')->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', 'estate_')->get();
        $conclusions = DB::table('files')->where('order_id', $order->id ?? 0)->where('order_type', 'conclusion_')->get();
        return view('estate.show', compact('order', 'members', 'appraisers', 'isAppraisers', 'files', 'conclusions'));
    }

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

    public function showTeam($order)
    {
        $order = DB::table('estate_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', 'estate_')->get();
        $appraisers = DB::table('users')->whereRaw('LOWER(role) = ?', ['appraiser'])->where('status', 'active')->get();
        return view('estate.show-team', compact('order', 'members', 'appraisers'));
    }

    public function showDocuments($order, Request $request)
    {
        $order = DB::table('estate_orders')->find($order);
        $type = $request->get('type', 'ALL');
        $filesQuery = DB::table('files')->where('order_id', $order->id ?? 0)->where('order_type', 'estate_');
        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', 'estate_')->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('estate.show-documents', compact('order', 'files', 'type', 'countDocs', 'countMediaFiles', 'otherFiles'));
    }

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