<?php

declare(strict_types=1);

namespace backend\controllers;

use common\forms\CustomerForm;
use common\models\Customer;
use yii\data\ActiveDataProvider;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\Response;

/**
 * CustomerController — unified CRUD for Individual, Business, and Member customers.
 */
class CustomerController extends Controller
{
    public function behaviors(): array
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [['allow' => true, 'roles' => ['@']]],
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => ['delete' => ['POST']],
            ],
        ];
    }

    public function actionIndex(): string
    {
        $query = Customer::find()
            ->with(['parentCustomer'])
            ->orderBy(['created_at' => SORT_DESC]);

        // Filter by type
        $type = \Yii::$app->request->get('type');
        if ($type) {
            $query->andWhere(['customer_type' => $type]);
        }

        $search = \Yii::$app->request->get('search');
        if ($search) {
            $query->andWhere([
                'OR',
                ['LIKE', 'name', $search],
                ['LIKE', 'phone', $search],
                ['LIKE', 'email', $search],
            ]);
        }

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => ['pageSize' => 25],
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'filterType' => $type,
            'search' => $search,
        ]);
    }

    public function actionView(int $id): string
    {
        $model = Customer::find()
            ->with(['customerPlans.plan', 'invoices', 'dietPlans', 'members'])
            ->where(['id' => $id])
            ->one();

        if ($model === null) {
            throw new NotFoundHttpException('Customer not found.');
        }

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

    public function actionCreate(): Response|string
    {
        $form = new CustomerForm();
        if (Yii::$app->request->isPost) {
            echo '<pre>';
            print_r(Yii::$app->request->post());
            exit;
        }

        if ($form->load(\Yii::$app->request->post(), 'CustomerForm') && $form->validate()) {
            $model = new Customer();
            $model->setAttributes($form->getAttributes());

            if ($model->save()) {
                \Yii::$app->session->setFlash('success', 'Customer created.');
                return $this->redirect(['view', 'id' => $model->id]);
            }
            \Yii::$app->session->setFlash('error', 'Save failed: ' . json_encode($model->errors));
        }

        // Get business customers for parent selector
        $businesses = Customer::find()
            ->where(['customer_type' => Customer::TYPE_BUSINESS])
            ->orderBy('name')
            ->all();

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

    public function actionUpdate(int $id): Response|string
    {
        $model = $this->findModel($id);
        $form = new CustomerForm();
        $form->setAttributes($model->getAttributes(), false);

        if ($form->load(\Yii::$app->request->post(), 'CustomerForm') && $form->validate()) {
            $model->setAttributes($form->getAttributes());
            if ($model->save()) {
                \Yii::$app->session->setFlash('success', 'Customer updated.');
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }

        $businesses = Customer::find()
            ->where(['customer_type' => Customer::TYPE_BUSINESS])
            ->andWhere(['!=', 'id', $id])
            ->orderBy('name')
            ->all();

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

    public function actionDelete(int $id): Response
    {
        $model = $this->findModel($id);
        $model->is_active = 0;
        $model->save(false);

        \Yii::$app->session->setFlash('success', 'Customer deactivated.');
        return $this->redirect(['index']);
    }

    private function findModel(int $id): Customer
    {
        $model = Customer::findOne($id);
        if ($model === null) {
            throw new NotFoundHttpException('Customer not found.');
        }
        return $model;
    }
}
