<?php

namespace app\controllers;

use Yii;
use app\models\Car;
use app\models\CarImage;
use app\models\Client;
use app\models\Auction;
use app\models\Warehouse;
use app\models\Destination;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;

class CarController extends BaseController
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'save-ajax' => ['POST'],
                    'delete'    => ['POST'],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        // ─── Handle AJAX/JSON requests from Vue (server-side pagination) ───
        if (Yii::$app->request->isAjax || Yii::$app->request->get('ajax')) {

            $page     = (int) Yii::$app->request->get('page', 1);
            $pageSize = (int) Yii::$app->request->get('pageSize', 15);
            $search   = trim(Yii::$app->request->get('search', ''));

            $query = Car::find()
                ->with(['client', 'auction', 'warehouse', 'destination'])
                // ✅ No 'images' here — we fetch thumbnail separately below
                ->orderBy(['car.id' => SORT_DESC]);

            if ($search !== '') {
                $matchingClientIds = Client::find()
                    ->select('id')
                    ->where([
                        'or',
                        ['like', 'no',    $search],
                        ['like', 'name',  $search],
                        ['like', 'phone', $search],
                    ])
                    ->column();

                $query->andWhere([
                    'or',
                    ['like', 'car.vin',       $search],
                    ['like', 'car.lot',       $search],
                    ['like', 'car.info',      $search],
                    ['like', 'car.container', $search],
                    ['like', 'car.year',      $search],
                    ['like', 'car.status',    $search],
                    ['in',   'car.client_id', $matchingClientIds ?: [0]],
                ]);
            }

            $totalCount = (clone $query)->count();
            $totalPages = (int) ceil($totalCount / $pageSize);

            $cars = $query
                ->offset(($page - 1) * $pageSize)
                ->limit($pageSize)
                ->all();

            // ✅ Batch-load only the FIRST image per car (thumbnail only)
            // One single query for all car IDs on this page — no N+1
            $carIds = array_map(fn($c) => $c->id, $cars);

            $thumbnailMap = [];
            if (!empty($carIds)) {
                $thumbRows = Yii::$app->db->createCommand('
                    SELECT ci.car_id, ci.image_path
                    FROM car_image ci
                    INNER JOIN (
                        SELECT MIN(id) as min_id
                        FROM car_image
                        WHERE car_id IN (' . implode(',', $carIds) . ')
                        GROUP BY car_id
                    ) first ON ci.id = first.min_id
                ')->queryAll();

                foreach ($thumbRows as $row) {
                    $thumbnailMap[$row['car_id']] = $row['image_path'];
                }
            }

            $carsData = [];
            foreach ($cars as $car) {
                $carsData[] = [
                    'id'             => $car->id,
                    'vin'            => $car->vin,
                    'lot'            => $car->lot,
                    'title'          => $car->title,
                    'info'           => $car->info,
                    'liner'          => $car->liner,
                    'year'           => $car->year,
                    'price'          => $car->price,
                    'status'         => $car->status,
                    'auction_id'     => $car->auction_id,
                    'warehouse_id'   => $car->warehouse_id,
                    'destination_id' => $car->destination_id,
                    'client_id'      => $car->client_id,
                    'purchase_date'  => $car->purchase_date,
                    'received_date'  => $car->received_date,
                    'eta_date'       => $car->eta_date,
                    'shipping_line'  => $car->shipping_line,
                    'container'      => $car->container,
                    'note'           => $car->note,
                    // ✅ Thumbnail from batch map — no extra query per car
                    'thumbnail'      => $thumbnailMap[$car->id] ?? null,
                    // ✅ images array is empty for list view — not needed
                    'images'         => [],
                ];
            }

            Yii::$app->response->format = Response::FORMAT_JSON;
            return [
                'success'    => true,
                'cars'       => $carsData,
                'total'      => (int) $totalCount,
                'page'       => $page,
                'pageSize'   => $pageSize,
                'totalPages' => $totalPages,
            ];
        }

        // ─── Normal page render — load FIRST PAGE only ───
        $pageSize = 15;

        $firstPageCars = Car::find()
            ->with(['client', 'auction', 'warehouse', 'destination'])
            // ✅ No 'images' — thumbnail loaded separately below
            ->orderBy(['car.id' => SORT_DESC])
            ->limit($pageSize)
            ->offset(0)
            ->all();

        $totalCount = Car::find()->count();

        // ─── Status counts for stats bar ───
        $statusRows = Yii::$app->db->createCommand('
            SELECT status, COUNT(*) as cnt FROM car GROUP BY status
        ')->queryAll();

        $statusCounts = [];
        foreach ($statusRows as $row) {
            $statusCounts[$row['status']] = (int) $row['cnt'];
        }

        $clients      = Client::find()->orderBy('name')->all();
        $auctions     = Auction::find()->orderBy('name')->all();
        $warehouses   = Warehouse::find()->orderBy('name')->all();
        $destinations = Destination::find()->orderBy('name')->all();

        // ✅ Batch-load thumbnails for first page — one query total
        $carIds = array_map(fn($c) => $c->id, $firstPageCars);

        $thumbnailMap = [];
        if (!empty($carIds)) {
            $thumbRows = Yii::$app->db->createCommand('
                SELECT ci.car_id, ci.image_path
                FROM car_image ci
                INNER JOIN (
                    SELECT MIN(id) as min_id
                    FROM car_image
                    WHERE car_id IN (' . implode(',', $carIds) . ')
                    GROUP BY car_id
                ) first ON ci.id = first.min_id
            ')->queryAll();

            foreach ($thumbRows as $row) {
                $thumbnailMap[$row['car_id']] = $row['image_path'];
            }
        }

        // ─── Format cars ───────────────────────────────────────────────────
        $carsData = [];
        foreach ($firstPageCars as $car) {
            $carsData[] = [
                'id'             => $car->id,
                'vin'            => $car->vin,
                'lot'            => $car->lot,
                'title'          => $car->title,
                'info'           => $car->info,
                'liner'          => $car->liner,
                'year'           => $car->year,
                'price'          => $car->price,
                'status'         => $car->status,
                'auction_id'     => $car->auction_id,
                'warehouse_id'   => $car->warehouse_id,
                'destination_id' => $car->destination_id,
                'client_id'      => $car->client_id,
                'purchase_date'  => $car->purchase_date,
                'received_date'  => $car->received_date,
                'eta_date'       => $car->eta_date,
                'shipping_line'  => $car->shipping_line,
                'container'      => $car->container,
                'note'           => $car->note,
                // ✅ Thumbnail from batch map
                'thumbnail'      => $thumbnailMap[$car->id] ?? null,
                // ✅ Empty for list view — full images loaded only in edit modal
                'images'         => [],
            ];
        }

        // ─── Format clients ────────────────────────────────────────────────
        $clientsData = array_map(function ($c) {
            return [
                'id'    => $c->id,
                'no'    => $c->no    ?? '',
                'name'  => $c->name  ?? '',
                'phone' => $c->phone ?? '',
            ];
        }, $clients);

        // ─── Format auctions ───────────────────────────────────────────────
        $auctionsData = array_map(function ($a) {
            return ['id' => $a->id, 'name' => $a->name];
        }, $auctions);

        // ─── Format warehouses ─────────────────────────────────────────────
        $warehousesData = array_map(function ($w) {
            return ['id' => $w->id, 'name' => $w->name];
        }, $warehouses);

        // ─── Format destinations ───────────────────────────────────────────
        $destinationsData = array_map(function ($d) {
            return ['id' => $d->id, 'name' => $d->name];
        }, $destinations);

        return $this->render('index', [
            'cars'         => $carsData,
            'clients'      => $clientsData,
            'auctions'     => $auctionsData,
            'warehouses'   => $warehousesData,
            'destinations' => $destinationsData,
            'totalCount'   => (int) $totalCount,
            'statusCounts' => $statusCounts,
        ]);
    }



    public function actionSaveAjax()
    {
        ini_set('max_file_uploads', '100');

        Yii::$app->response->format = Response::FORMAT_JSON;

        $request = Yii::$app->request;
        if (!$request->isPost) {
            return ['success' => false, 'message' => 'Invalid request.'];
        }

        $id  = $request->post('id');
        $car = $id ? Car::findOne((int)$id) : new Car();

        if (!$car) {
            return ['success' => false, 'message' => 'Car not found.'];
        }

        $car->load($request->post(), 'Car');

        if (!$car->save()) {
            return ['success' => false, 'errors' => $car->errors];
        }

        // ─── Handle image uploads ───────────────────────────────
        $uploadPath = Yii::getAlias('@webroot/uploads/cars/');

        if (!is_dir($uploadPath)) {
            mkdir($uploadPath, 0755, true);
        }

        $imageFiles = $_FILES['image_files'] ?? [];

        foreach (['auction', 'warehouse', 'loading'] as $type) {
            if (empty($imageFiles['name'][$type])) continue;

            $names    = $imageFiles['name'][$type];
            $tmpNames = $imageFiles['tmp_name'][$type];
            $errors   = $imageFiles['error'][$type];

            foreach ($names as $i => $originalName) {
                if ($errors[$i] !== UPLOAD_ERR_OK) continue;
                if (empty($tmpNames[$i]))           continue;

                $ext     = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
                $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
                if (!in_array($ext, $allowed)) continue;

                $filename = $type . '_' . $car->id . '_' . uniqid() . '.' . $ext;
                $dest     = $uploadPath . $filename;

                if (move_uploaded_file($tmpNames[$i], $dest)) {
                    $img             = new CarImage();
                    $img->car_id     = $car->id;
                    $img->image_path = $filename;
                    $img->type       = $type;
                    $img->save();
                }
            }
        }

        // ─── Delete removed images ──────────────────────────────
        $deleteIds = $request->post('delete_image_ids', []);
        if (!empty($deleteIds)) {
            foreach ($deleteIds as $imgId) {
                $img = CarImage::findOne((int)$imgId);
                if ($img) {
                    $filePath = $uploadPath . $img->image_path;
                    if (file_exists($filePath)) {
                        @unlink($filePath);
                    }
                    $img->delete();
                }
            }
        }

        // ─── Return fresh data ──────────────────────────────────
        $car->refresh();

        $carData = $car->toArray();

        $carImages = CarImage::find()
            ->where(['car_id' => $car->id])
            ->orderBy(['id' => SORT_ASC])
            ->all();

        $carData['images'] = array_map(function ($img) {
            return [
                'id'         => $img->id,
                'car_id'     => $img->car_id,
                'image_path' => $img->image_path,
                'type'       => $img->type,
            ];
        }, $carImages);

        $carData['thumbnail'] = null;
        foreach ($carData['images'] as $img) {
            if (!empty($img['image_path'])) {
                $carData['thumbnail'] = $img['image_path'];
                break;
            }
        }

        return [
            'success' => true,
            'id'      => $car->id,
            'car'     => $carData,
        ];
    }

    public function actionDelete()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        if (!Yii::$app->request->isPost) {
            Yii::$app->response->statusCode = 405;
            return ['success' => false, 'message' => 'Method not allowed.'];
        }

        $id = (int) Yii::$app->request->post('id');

        if (!$id) {
            return ['success' => false, 'message' => 'Missing or invalid car ID.'];
        }

        $car = Car::findOne($id);

        if (!$car) {
            return ['success' => false, 'message' => 'Car not found (ID: ' . $id . ').'];
        }

        $uploadPath = Yii::getAlias('@webroot/uploads/cars/');
        $images     = CarImage::find()->where(['car_id' => $id])->all();

        foreach ($images as $image) {
            $filePath = $uploadPath . $image->image_path;
            if (!empty($image->image_path) && file_exists($filePath)) {
                @unlink($filePath);
            }
            try {
                $image->delete();
            } catch (\Exception $e) {
                Yii::warning('Image delete failed ID=' . $image->id . ': ' . $e->getMessage());
            }
        }

        try {
            $deleted = $car->delete();

            if ($deleted === false) {
                return [
                    'success' => false,
                    'message' => 'Car record could not be deleted.',
                ];
            }

            return [
                'success' => true,
                'message' => 'Car deleted successfully.',
                'id'      => $id,
            ];

        } catch (\Exception $e) {
            Yii::error('Car delete exception ID=' . $id . ': ' . $e->getMessage());
            return [
                'success' => false,
                'message' => 'Delete exception: ' . $e->getMessage(),
            ];
        }
    }

    public function actionView($id)
    {
        $model = Car::find()
            ->with(['images', 'client', 'auction', 'warehouse', 'destination'])
            ->where(['id' => (int)$id])
            ->one();

        if (!$model) {
            throw new \yii\web\NotFoundHttpException('The car was not found.');
        }

        return $this->render('view', ['car' => $model]);
    }
}