<?php

namespace app\controllers;

use app\models\Auction;
use app\models\AuctionSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * AuctionController implements the CRUD actions for Auction model.
 */
class AuctionController extends BaseController
{
    /**
     * @inheritDoc
     */
    public function behaviors()
    {
        return array_merge(
            parent::behaviors(),
            [
                'verbs' => [
                    'class' => VerbFilter::className(),
                    'actions' => [
                        'delete' => ['POST'],
                    ],
                ],
            ]
        );
    }

    /**
     * Lists all Auction models.
     *
     * @return string
     */
    public function actionIndex()
    {
        // 1. Get the models (data)
        $models = \app\models\Auction::find()->orderBy(['id' => SORT_DESC])->all();
        
        // 2. Format the data into the $rows array
        $rows = [];
        foreach ($models as $model) {
            $rows[] = [
                'id' => $model->id,
                'name' => $model->name,
                // Match the date format you want
                'created' => $model->created ? date('d.m.Y', strtotime($model->created)) : '',
            ];
        }

        // 3. Pass $rows to the view
        return $this->render('index', [
            'rows' => $rows,
        ]);
    }

    /**
     * Displays a single Auction model.
     * @param int $id ID
     * @return string
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Auction model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return string|\yii\web\Response
     */
    public function actionCreate()
    {
        $model = new Auction();

        if ($this->request->isPost) {
            if ($model->load($this->request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            }
        } else {
            $model->loadDefaultValues();
        }

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

    /**
     * Updates an existing Auction model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param int $id ID
     * @return string|\yii\web\Response
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

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

    /**
     * Deletes an existing Auction model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param int $id ID
     * @return \yii\web\Response
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $model = \app\models\Auction::findOne($id);

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

        // ✅ Block deletion if any car is linked to this auction
        $inUse = \app\models\Car::find()->where(['auction_id' => $id])->exists();
        if ($inUse) {
            return ['success' => false, 'message' => 'Cannot delete: This auction is used by one or more car records.'];
        }

        if ($model->delete()) {
            return ['success' => true];
        }

        return ['success' => false, 'message' => 'Failed to delete record.'];
    }

    /**
     * Finds the Auction model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param int $id ID
     * @return Auction the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Auction::findOne(['id' => $id])) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }

    public function actionList($q = null)
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $out = ['results' => []];
        if (!is_null($q)) {
            $data = Auction::find()
                ->select(['name as value', 'name as label'])
                ->where(['like', 'name', $q])
                ->limit(10)
                ->asArray()
                ->all();
            return $data;
        }
        return $out;
    }

    public function actionSearch($q)
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return Auction::find()
            ->where(['like', 'name', $q])
            ->limit(10)
            ->all();
    }

    public function actionSaveAjax()
    {
        // Use \ before Yii to avoid the "Class not found" error
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        $data = json_decode(\Yii::$app->request->getRawBody(), true);
        $id = $data['id'] ?? null;
        $name = isset($data['name']) ? trim($data['name']) : '';

        if (empty($name)) {
            return ['success' => false, 'errors' => ['name' => ['Name cannot be empty.']]];
        }

        $modelClass = '\app\models\Auction';
        
        // Check for duplicates
        $exists = $modelClass::find()
            ->where(['name' => $name])
            ->andFilterWhere(['not', ['id' => $id]])
            ->exists();

        if ($exists) {
            return [
                'success' => false, 
                'errors' => ['name' => ["Auction '$name' already exists."]]
            ];
        }

        $model = $id ? $modelClass::findOne($id) : new $modelClass();
        $model->name = $name;

        if ($model->save()) {
            // Refresh the model to get the timestamp from DB if it was just created
            $model->refresh(); 
            
            return [
                'success' => true,
                'model' => [
                    'id' => $model->id,
                    'name' => $model->name,
                    // Formatting date as dd.mm.yyyy
                    'created' => date('d.m.Y', strtotime($model->created)),
                ]
            ];
        }

        return ['success' => false, 'errors' => $model->errors];
    }
}
