<?php

namespace app\controllers;

use Yii;
use app\models\Client;
use app\models\User; // Your User model
use app\models\Car;  // Your Car model
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

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

    // 1. Index ordered by client.no
    public function actionIndex()
    {
        $rows = Client::find()->orderBy(['no' => SORT_DESC])->asArray()->all();
        return $this->render('index', ['rows' => $rows]);
    }

    public function actionSaveAjax()
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        $rawBody = Yii::$app->request->getRawBody();
        $data = json_decode($rawBody, true);
        if (empty($data)) $data = Yii::$app->request->post();

        $isNew = empty($data['id']);
        $model = !$isNew ? Client::findOne($data['id']) : new Client();

        // Manual assignment to Client model
        $model->name = $data['name'] ?? null;
        $model->phone = $data['phone'] ?? null;
        $model->email = $data['email'] ?? null;
        $model->address = $data['address'] ?? null;
        $model->town = $data['town'] ?? null;
        $model->country = $data['country'] ?? null;
        $model->balance = $data['balance'] ?? 0;
        
        // Virtual attributes for User data
        $model->username = $data['username'] ?? null;
        $model->password = $data['password'] ?? null;

        $db = Yii::$app->db;
        $transaction = $db->beginTransaction();

        try {
            // 1. UNIQUE USERNAME CHECK
            if (!empty($model->username)) {
                $userQuery = User::find()->where(['username' => $model->username]);
                if (!$isNew) {
                    $userQuery->andWhere(['!=', 'client_id', $model->id]);
                }
                if ($userQuery->exists()) {
                    throw new \Exception("The username '{$model->username}' is already taken.");
                }
            }

            if ($isNew) {
                // Auto-number 00161
                $maxNo = Client::find()->max('CAST(no AS UNSIGNED)');
                $model->no = str_pad(($maxNo ? (int)$maxNo + 1 : 1), 5, '0', STR_PAD_LEFT);
            }

            if ($model->save()) {
                // 2. FIND OR CREATE USER
                $user = !$isNew ? User::findOne(['client_id' => $model->id]) : new User();
                if (!$user) $user = new User(); // Fallback if record missing

                $user->client_id = $model->id;
                $user->auction_id = $user->auction_id ?? 0;
                $user->name = $model->name;
                $user->email = $model->email;
                $user->phone = $model->phone;
                $user->username = $model->username;
                $user->position = 'client';

                // 3. PASSWORD UPDATE LOGIC
                if (!empty($model->password)) {
                    $user->password = \Yii::$app->security->generatePasswordHash($model->password);
                    $user->auth_key = \Yii::$app->security->generateRandomString();
                } elseif ($isNew) {
                    throw new \Exception("Password is required for new clients.");
                }

                if (!$user->save()) {
                    throw new \Exception("User Account Error: " . implode(", ", $user->getFirstErrors()));
                }
                
                $transaction->commit();
                return ['success' => true, 'client' => $model->attributes];
            } else {
                throw new \Exception("Client Error: " . implode(", ", $model->getFirstErrors()));
            }

        } catch (\Exception $e) {
            $transaction->rollBack();
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

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

        try {
            $client = Client::findOne($id);
            if (!$client) {
                return ['success' => false, 'message' => 'Client not found.'];
            }

            // 4. Check if record exists in Table Car
            $hasCars = Car::find()->where(['client_id' => $id])->exists();
            if ($hasCars) {
                return ['success' => false, 'message' => 'Cannot delete: Client has car records.'];
            }

            // 5. Delete from User table first (linked by email)
            User::deleteAll(['email' => $client->email]);

            // 6. Delete Client record
            if ($client->delete()) {
                $transaction->commit();
                return ['success' => true];
            }

            throw new \Exception("Failed to delete client.");

        } catch (\Exception $e) {
            $transaction->rollBack();
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    protected function findModel($id)
    {
        if (($model = Client::findOne(['id' => $id])) !== null) {
            return $model;
        }
        throw new NotFoundHttpException('The requested page does not exist.');
    }

    public function actionGetNextNo()
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        // Find the max number
        $maxNo = Client::find()->max('CAST(no AS UNSIGNED)');
        $nextVal = $maxNo ? (int)$maxNo + 1 : 1;
        
        // Pad with zeros to a length of 5: e.g., 161 becomes 00161
        $formattedNo = str_pad($nextVal, 5, '0', STR_PAD_LEFT);
        
        return ['next_no' => $formattedNo];
    }
}