<?php

namespace app\controllers;

use Yii;
use app\models\User;
use app\models\UserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

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

    public function actionIndex()
    {
        $rows = \app\models\User::find()
            ->alias('u')
            ->select([
                'u.*', 
                'c.no AS client_no', 
                'c.name AS client_name'
            ])
            ->leftJoin('client c', 'u.client_id = c.id')
            ->orderBy([
                // Staff first, then Clients
                new \yii\db\Expression("CASE WHEN u.position = 'client' THEN 2 ELSE 1 END"),
                'u.position' => SORT_ASC,
                'c.no' => SORT_ASC,
                'u.name' => SORT_ASC
            ])
            ->asArray() // Converts the result to an array to easily access joined columns
            ->all();

        $formattedRows = [];
        foreach ($rows as $row) {
            // Logic: client_id=0 ? user.name : client.no - client.name
            if ($row['client_id'] == 0) {
                $displayName = $row['name'];
            } else {
                $displayName = ($row['client_no'] ?? 'N/A') . " - " . ($row['client_name'] ?? 'Unknown');
            }

            $formattedRows[] = [
                'id'         => $row['id'],
                'displayName'=> $displayName,
                'name'       => $row['name'],
                'email'      => $row['email'],
                'phone'      => $row['phone'],
                'username'   => $row['username'],
                'position'   => $row['position'],
                'created'    => $row['created'] ? date('d.m.Y', strtotime($row['created'])) : '',
            ];
        }

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

    public function actionSaveAjax()
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        // Decode Axios JSON body
        $post = json_decode(\Yii::$app->request->getRawBody(), true);

        // Fallback if decode fails
        if (empty($post)) {
            $post = \Yii::$app->request->post();
        }

        $model = (!empty($post['id'])) ? User::findOne($post['id']) : new User();

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

        // --- DUPLICATE USERNAME CHECK ---
        $exists = User::find()
            ->where(['username' => $post['username'] ?? ''])
            ->andFilterWhere(['not', ['id' => $model->id]])
            ->exists();

        if ($exists) {
            return ['success' => false, 'errors' => ['username' => ['Username already taken.']]];
        }

        // IMPORTANT: The second parameter '' is what prevents saving empty records
        if ($model->load($post, '')) {
            
            if (!empty($post['password'])) {
                $model->password = \Yii::$app->security->generatePasswordHash($post['password']);
                $model->auth_key = \Yii::$app->security->generateRandomString();
            }

            if ($model->save()) {
                return [
                    'success' => true,
                    'user' => [
                        'id' => $model->id,
                        'displayName' => $model->name,
                        'name' => $model->name,
                        'username' => $model->username,
                        'phone' => $model->phone,
                        'email' => $model->email,
                        'position' => $model->position,
                    ]
                ];
            }
        }

        return [
            'success' => false,
            'errors' => $model->getErrors() // This will tell you exactly why it didn't save
        ];
    }

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

        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 User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param int $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 User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param int $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;

        try {
            $model = $this->findModel($id);

            // 1. If user is linked to a client, check if that client has any cars
            if ($model->client_id > 0) {
                $hasCars = (new \yii\db\Query())
                    ->from('car')
                    ->where(['client_id' => $model->client_id])
                    ->exists();

                if ($hasCars) {
                    return [
                        'success' => false,
                        'message' => 'Cannot delete: This client user has car records.',
                    ];
                }

                return [
                    'success' => false,
                    'message' => 'Cannot delete: This user is linked to a Client profile.',
                ];
            }

            // 2. For staff users, check car table by user_id
            $hasCars = (new \yii\db\Query())->from('car')->where(['user_id' => $id])->exists();
            $hasOldCars = (new \yii\db\Query())->from('car_old')->where(['user_id' => $id])->exists();

            if ($hasCars || $hasOldCars) {
                return [
                    'success' => false,
                    'message' => 'Cannot delete: This staff member has processed car records.',
                ];
            }

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

        } catch (\Exception $e) {
            return ['success' => false, 'message' => 'System Error: ' . $e->getMessage()];
        }

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

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