<?php

namespace app\controllers;

use app\models\Warehouse;
use app\models\WarehouseSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

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

    public function actionIndex()
    {
        // Fetch models and format into $rows for Vue
        $models = \app\models\Warehouse::find()->orderBy(['id' => SORT_DESC])->all();
        $rows = [];
        foreach ($models as $model) {
            $rows[] = [
                'id' => $model->id,
                'name' => $model->name,
                'created' => $model->created ? date('d.m.Y', strtotime($model->created)) : '',
            ];
        }

        return $this->render('index', ['rows' => $rows]);
    }

    public function actionSaveAjax()
    {
        \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' => ['Warehouse name is required.']]];
        }

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

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

        $model = $id ? \app\models\Warehouse::findOne($id) : new \app\models\Warehouse();
        $model->name = $name;

        if ($model->save()) {
            $model->refresh();
            return [
                'success' => true,
                'model' => [
                    'id' => $model->id,
                    'name' => $model->name,
                    'created' => date('d.m.Y', strtotime($model->created)),
                ]
            ];
        }

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

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

        $model = \app\models\Warehouse::findOne($id);
        if (!$model) {
            return ['success' => false, 'message' => 'Warehouse not found.'];
        }

        $inUse = \app\models\Car::find()->where(['warehouse_id' => $id])->exists();
        if ($inUse) {
            return ['success' => false, 'message' => 'Cannot delete: This warehouse is used by one or more car records.'];
        }

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

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

    /**
     * Displays a single Warehouse 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 Warehouse model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return string|\yii\web\Response
     */
    public function actionCreate()
    {
        $model = new Warehouse();

        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 Warehouse 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,
        ]);
    }

    /**
     * Finds the Warehouse 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 Warehouse the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Warehouse::findOne(['id' => $id])) !== null) {
            return $model;
        }

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