<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\QrController;
use setasign\Fpdi\Fpdi;

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)
    {
        // Sanitize cost before validation
        if ($request->has('cost')) {
            $request->merge([
                'cost' => str_replace(',', '', $request->cost)
            ]);
        }

        $request->validate([
            'number'                 => 'required',
            'purpose_id'             => 'required',
            'ordered_customer'       => 'required',
            'ordered_customer_phone' => 'required',
            'customer_type'          => 'required|in:physical,juridical',
            'owner_type'             => 'required|in:physical,juridical',
            'car_category'           => 'required',
            'car_mark'               => 'required',
            'car_number'             => 'required',
            'tech_passport'          => 'required',
            'cost'                   => 'required|numeric',
        ]);

        $id = DB::table('auto_orders')->insertGetId([
            'number'                 => $request->number,
            'status'                 => $request->status ?? 'draft',
            'purpose_id'             => $request->purpose_id,
            'diller_id'              => $request->diller_id ?: null,
            'ordered_customer'       => $request->ordered_customer,
            'ordered_customer_phone' => $request->ordered_customer_phone,
            'customer_type'          => $request->customer_type,
            'customer_last_name'     => $request->customer_last_name,
            'customer_first_name'    => $request->customer_first_name,
            'customer_patronymic'    => $request->customer_patronymic,
            'customer_company'       => $request->customer_company,
            'owner_type'             => $request->owner_type,
            'owner_last_name'        => $request->owner_last_name,
            'owner_first_name'       => $request->owner_first_name,
            'owner_patronymic'       => $request->owner_patronymic,
            'owner_company'          => $request->owner_company,
            'car_category'           => $request->car_category,
            'car_mark'               => $request->car_mark,
            'color'                  => $request->color,
            'made_date'              => $request->made_date,
            'body'                   => $request->body,
            'engine'                 => $request->engine,
            'car_number'             => $request->car_number,
            'type'                   => $request->type,
            'shassi'                 => $request->shassi,
            'tech_passport'          => $request->tech_passport,
            'tech_given_date'        => $request->tech_given_date,
            'tech_given_whom'        => $request->tech_given_whom,
            'cost'                   => (int)str_replace(',', '', $request->cost ?? 0),
            'note'                   => $request->note,
            'created_at'             => $request->created_at ?? now(),
            'updated_at'             => now(),
        ]);
        QrController::generateQr($id, 'auto_');
        return redirect()->route('auto.show', $id);
    }

    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)
    {
        // Sanitize cost before validation
        if ($request->has('cost')) {
            $request->merge([
                'cost' => str_replace(',', '', $request->cost)
            ]);
        }

        $request->validate([
            'number'                 => 'required',
            'purpose_id'             => 'required',
            'ordered_customer'       => 'required',
            'ordered_customer_phone' => 'required',
            'customer_type'          => 'required|in:physical,juridical',
            'owner_type'             => 'required|in:physical,juridical',
            'car_category'           => 'required',
            'car_mark'               => 'required',
            'car_number'             => 'required',
            'tech_passport'          => 'required',
            'cost'                   => 'required|numeric',
        ]);

        DB::table('auto_orders')->where('id', $id)->update([
            'number'                 => $request->number,
            'status'                 => $request->status,
            'purpose_id'             => $request->purpose_id,
            'diller_id'              => $request->diller_id ?: null,
            'ordered_customer'       => $request->ordered_customer,
            'ordered_customer_phone' => $request->ordered_customer_phone,
            'customer_type'          => $request->customer_type,
            'customer_last_name'     => $request->customer_last_name,
            'customer_first_name'    => $request->customer_first_name,
            'customer_patronymic'    => $request->customer_patronymic,
            'customer_company'       => $request->customer_company,
            'owner_type'             => $request->owner_type,
            'owner_last_name'        => $request->owner_last_name,
            'owner_first_name'       => $request->owner_first_name,
            'owner_patronymic'       => $request->owner_patronymic,
            'owner_company'          => $request->owner_company,
            'car_category'           => $request->car_category,
            'car_mark'               => $request->car_mark,
            'color'                  => $request->color,
            'made_date'              => $request->made_date,
            'body'                   => $request->body,
            'engine'                 => $request->engine,
            'car_number'             => $request->car_number,
            'type'                   => $request->type,
            'shassi'                 => $request->shassi,
            'tech_passport'          => $request->tech_passport,
            'tech_given_date'        => $request->tech_given_date,
            'tech_given_whom'        => $request->tech_given_whom,
            'cost'                   => (int)str_replace(',', '', $request->cost ?? 0),
            'note'                   => $request->note,
            'created_at'             => $request->created_at,
            'updated_at'             => now(),
        ]);
        return redirect()->route('auto.show', $id);
    }

    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()
            ->map(function ($member) {
                $member->started = DB::table('order_members')->where('user_id', $member->user_id)->count();
                $member->finished = 0; // Defaulting for now
                $member->approved = 0;
                $member->rejected = 0;
                return $member;
            });
        $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();
        $sizeInStorage = $allFiles->sum('size_in_bytes');
        return view('auto.show-documents', compact('order', 'files', 'type', 'countDocs', 'countMediaFiles', 'otherFiles', 'sizeInStorage'));
    }

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

    public function generatePdf($id)
    {
        $order = DB::table('auto_orders as o')
            ->selectRaw('o.*, p.uz as purpose, c.uz as category, CONCAT_WS(\' \', o.owner_last_name, o.owner_first_name, o.owner_patronymic) as "ownerName"')
            ->leftJoin('purposes as p', 'p.id', '=', 'o.purpose_id')
            ->leftJoin('concerns as c', 'c.id', '=', 'o.car_category')
            ->where('o.id', $id)
            ->first();

        if (!$order) {
            abort(404);
        }

        $pdf = new Fpdi();
        $pdf->AddPage();
        
        // Add Title
        $pdf->SetFont('Arial', 'B', 16);
        $pdf->Cell(0, 10, 'BAXOLASH XULOSASI (AVTO)', 0, 1, 'C');
        $pdf->Ln(10);

        // Add Details
        $pdf->SetFont('Arial', '', 12);
        
        $fields = [
            'Tartib raqami' => $order->number,
            'Sana' => date('d.m.Y', strtotime($order->created_at)),
            'Maqsadi' => $order->purpose,
            'Kategoriya' => $order->category,
            'Markasi' => $order->car_mark,
            'Davlat raqami' => $order->car_number,
            'Egasi' => $order->ownerName,
            'Ishlab chiqarilgan yili' => $order->made_date,
            'Baholangan summa' => number_format($order->object_price ?: 0, 0, '.', ' ') . ' UZS',
        ];

        foreach ($fields as $label => $value) {
            $pdf->SetFont('Arial', 'B', 12);
            $pdf->Cell(60, 10, $label . ':', 0, 0);
            $pdf->SetFont('Arial', '', 12);
            $pdf->Cell(0, 10, $value ?: '-', 0, 1);
        }

        $pdf->Ln(20);
        $pdf->SetFont('Arial', 'I', 10);
        $pdf->Cell(0, 10, 'Ushbu hujjat tizim tomonidan avtomatik generatsiya qilindi.', 0, 1, 'C');

        return response($pdf->Output('S'), 200)
            ->header('Content-Type', 'application/pdf')
            ->header('Content-Disposition', 'attachment; filename="Conclusion_'.$order->number.'.pdf"');
    }
}
