<?php
namespace nota\controllers;

use Yii;
use yii\web\Controller;
use yii\web\Response;
use yii\helpers\Html; 
use yii\web\NotFoundHttpException;
use nota\models\PaymentMethod;
use nota\models\PaymentSettings;
use nota\models\Usermember;
use nota\models\Cluster;
use nota\models\Pembayaran;
use nota\models\MPpn;
use nota\models\SettingPdf;
use nota\models\TemplateNota;
use yii\helpers\Url;
use yii\data\ActiveDataProvider;
use yii\filters\AccessControl;

class SettingController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'only' => ['create','update','delete','print','pdf','index','view','toko'], // halaman yang dilindungi
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'], // hanya user login
                    ],
                ],
                'denyCallback' => function () {
                    return $this->redirect(['/site/index']);
                },
            ],
        ];
    }
    /**
     * Halaman utama pengaturan cluster/perumahan
     */
    public function actionToko($slug)
    {
        $user = Usermember::findOne(Yii::$app->user->id);

        $cluster = Cluster::find()
            ->where(['eDeleted' => 'Tidak', 'idCluster' => $user->idCluster])
            ->one();

        $pembayaran = Pembayaran::find()
            ->where(['idCluster' => $cluster->idCluster, 'eDeleted' => 'Tidak'])
            ->orderBy(['iId' => SORT_DESC])
            ->one();

        if ($pembayaran && $pembayaran->eStatus == 'PROSES') {
            return $this->redirect(['admin/invoice']);
        }
        if ($pembayaran && $pembayaran->dateFinish < date('Y-m-d H:i:s')) {
            return $this->redirect(['admin/create-inv']);
        }

        $model = Cluster::find()
            ->where(['eDeleted' => 'Tidak', 'idCluster' => $slug])
            ->one();

        if (!$model) {
            return $this->redirect(['admin/dashboard']);
        }

        // DataTables untuk Metode Pembayaran
        $paymentDataProvider = new ActiveDataProvider([
            'query' => PaymentMethod::find()->where(['is_active' => 1]),
            'pagination' => ['pageSize' => 50],
        ]);



        // Proses simpan Data Toko
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $model->print_id = (int)$model->print_id;

            $model->print_id= $model->print_id;
            if ($model->save()) {
                Yii::$app->dbnota->createCommand()->insert('log_hist', [
                    'idRef'      => $model->iId,
                    'idCluster'  => $user->idCluster,
                    'eType'      => 'USER',
                    'vKeterangan'=> 'CLUSTER EDIT',
                    'iCreatedid' => Yii::$app->user->id,
                    'iUpdatedid' => Yii::$app->user->id,
                    'tCreated'   => date('Y-m-d H:i:s'),
                    'tUpdated'   => date('Y-m-d H:i:s'),
                ])->execute();

                Yii::$app->session->setFlash('success', '
                    <div class="bg-green alert alert-info" role="alert">
                        Berhasil Update Data Perumahan!
                    </div>
                    <script type="text/javascript">
                        $(window).on("load",function(){
                            $("#modalUbah").modal("show");
                        });
                    </script>
                ');

                // return $this->redirect(['toko', 'slug' => $slug]);
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                return ['success'=>true,'message'=>'Berhasil Update Data '];
            } else {
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                return ['success'=>false,'message'=>'Gagal menyimpan data'];
            }
        }

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

    public function actionPaymentMethodList()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $payments = PaymentMethod::find()->all();
        $data = [];
        foreach($payments as $p){
            $data[] = [
                'id' => $p->id,
                'name' => $p->name,
                'code' => $p->code,
                'status' => $p->is_active ? 'Aktif' : 'Nonaktif',
                'action' => 
                    Html::a('Edit', ['setting/edit-payment-method','id'=>$p->id], ['class'=>'btn btn-primary btn-sm','data-toggle'=>'modal','data-target'=>'#modal-payment']) . ' ' .
                    Html::a('Hapus','javascript:void(0)',['class'=>'btn btn-danger btn-sm btn-delete-payment','data-id'=>$p->id]),
            ];
        }
        return ['data'=>$data];
    }


    /**
     * Tambah metode pembayaran
     */
    public function actionAddPaymentMethod()
    {
        $model = new PaymentMethod();

        // === SAVE VIA AJAX ===
        if (Yii::$app->request->isPost) {

            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            $model->name = Yii::$app->request->post('name');
            $model->code = Yii::$app->request->post('code');
            $model->is_active = Yii::$app->request->post('is_active');

            if ($model->save()) {
                return [
                    'success' => true,
                    'message' => 'Metode pembayaran berhasil ditambahkan!'
                ];
            }

            return [
                'success' => false,
                'message' => 'Gagal menyimpan data!',
                'errors' => $model->errors
            ];
        }

        // === LOAD FORM MODAL ===
        return $this->renderPartial('_form-payment-method', [
            'model' => $model
        ]);
    }

    public function actionEditPaymentMethod($id)
    {
        $model = PaymentMethod::findOne($id);
        if(!$model) throw new \yii\web\NotFoundHttpException();

        if(Yii::$app->request->isPost){
            Yii::$app->response->format = Response::FORMAT_JSON;
            $model->name = Yii::$app->request->post('name');
            $model->code = Yii::$app->request->post('code');
            $model->is_active = Yii::$app->request->post('is_active');

            if($model->save()){
                return ['success'=>true,'message'=>'Metode pembayaran berhasil diupdate!'];
            } else {
                return ['success'=>false,'message'=>'Gagal menyimpan data!'];
            }
        }

        return $this->renderPartial('_form-payment-method',['model'=>$model]);
    }


    public function actionDeletePaymentMethod()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $id = Yii::$app->request->post('id');
        $model = PaymentMethod::findOne($id);

        if($model && $model->delete()){
            return ['success'=>true,'message'=>'Metode pembayaran berhasil dihapus!'];
        }

        return ['success'=>false,'message'=>'Gagal menghapus data!'];
    }

    public function actionPpnList()
{
    Yii::$app->response->format = Response::FORMAT_JSON;

    $data = MPpn::find()->orderBy('iId DESC')->all();

    $rows = [];

    foreach($data as $d){
        $rows[] = [
            'iId' => $d->iId,
            'iPpn' => $d->iPpn.'%',
            'action' => '
                <a href="'.Url::to(['setting/edit-ppn','id'=>$d->iId]).'"
                   class="btn btn-sm btn-primary"
                   data-toggle="modal"
                   data-target="#modal-ppn">Edit</a>

                <!-- <button class="btn btn-sm btn-danger btn-delete-ppn"
                    data-id="'.$d->iId.'">Hapus</button> -->
            '
        ];
    }

    return ['data'=>$rows];
}

    public function actionAddPpn()
{
    $model = new MPpn();

    if(Yii::$app->request->isPost){

        Yii::$app->response->format = Response::FORMAT_JSON;

        $model->load(Yii::$app->request->post(),'');

        if($model->save()){
            return ['success'=>true,'message'=>'PPN berhasil ditambahkan'];
        }

        return [
            'success'=>false,
            'message'=>'Gagal menyimpan',
            'errors'=>$model->getErrors()
        ];
    }

    return $this->renderPartial('_form_ppn',['model'=>$model]);
}

    public function actionEditPpn($id)
{
    $model = MPpn::findOne($id);

    if(!$model){
        throw new NotFoundHttpException();
    }

    if(Yii::$app->request->isPost){

        Yii::$app->response->format = Response::FORMAT_JSON;

        $model->load(Yii::$app->request->post(),'');

        if($model->save()){
            return ['success'=>true,'message'=>'PPN berhasil diupdate'];
        }

        return [
            'success'=>false,
            'message'=>'Gagal update',
            'errors'=>$model->getErrors()
        ];
    }

    // 👇 INI PENTING
    return $this->renderPartial('_form_ppn',[
        'model'=>$model
    ]);
}


    public function actionDeletePpn()
{
    Yii::$app->response->format = Response::FORMAT_JSON;

    $id = Yii::$app->request->post('id');

    if(($model = MPpn::findOne($id))){
        $model->delete();
        return ['success'=>true,'message'=>'PPN dihapus'];
    }

    return ['success'=>false,'message'=>'Data tidak ditemukan'];
}
    
    //PDF
    public function actionPdfList()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $rows = \nota\models\SettingPdf::find()->all();

        $data = [];

        foreach ($rows as $r) {

            $data[] = [
                'id' => $r->id,
                'paper_size' => $r->paper_size,
                'orientation' => $r->orientation,
                'margin' =>
                    'T:' . $r->margin_top .
                    ' B:' . $r->margin_bottom .
                    ' L:' . $r->margin_left .
                    ' R:' . $r->margin_right,
                'action' => '
                    <a href="'.Url::to(['setting/edit-pdf-setting','id'=>$r->id]).'"
                       class="btn btn-primary btn-sm"
                       data-toggle="modal"
                       data-target="#modal-pdf">Edit</a>

                    <button
                        class="btn btn-danger btn-sm btn-delete-pdf"
                        data-id="'.$r->id.'">
                        Hapus
                    </button>
                '
            ];
        }

        return ['data' => $data];
    }
    
    public function actionAddPdfSetting()
    {
        $model = new SettingPdf();

        // Cek apakah ini edit
        $id = Yii::$app->request->post('id');
        if($id){
            $model = SettingPdf::findOne($id);
            if(!$model){
                return ['success'=>false,'message'=>'Data tidak ditemukan'];
            }
        }

        if (Yii::$app->request->isPost) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return [
                    'success' => true,
                    'message' => 'Setting PDF berhasil disimpan'
                ];
            } else {
                return [
                    'success' => false,
                    'message' => implode('<br>', $model->getFirstErrors())
                ];
            }
        }

        return $this->renderPartial('_form-pdf-setting', [
            'model' => $model
        ]);
    }

    
    public function actionEditPdfSetting($id)
    {
        $model = SettingPdf::findOne($id);

        if(!$model){
            throw new \yii\web\NotFoundHttpException('Data tidak ditemukan');
        }

        if (Yii::$app->request->isPost) {

            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            if ($model->load(Yii::$app->request->post()) && $model->save()) {

                return [
                    'success' => true,
                    'message' => 'Setting PDF berhasil diupdate'
                ];

            } else {

                return [
                    'success' => false,
                    'message' => implode('<br>', $model->getFirstErrors())
                ];
            }
        }

        return $this->renderPartial('_form-pdf-setting', [
            'model' => $model
        ]);
    }
    
    public function actionDeletePdfSetting()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $id = Yii::$app->request->post('id');

        $model = SettingPdf::findOne($id);

        if(!$model){
            return ['success'=>false,'message'=>'Data tidak ditemukan'];
        }

        if($model->delete()){
            return ['success'=>true,'message'=>'Setting PDF berhasil dihapus'];
        } else {
            return ['success'=>false,'message'=>'Gagal menghapus data'];
        }
    }


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

    $model = SettingPdf::find()->one();

    if(!$model){
        $model = new SettingPdf();
    }

    if($model->load(Yii::$app->request->post())){

        if($model->save()){
            return ['success'=>true,'message'=>'Setting PDF disimpan'];
        }

        return [
            'success'=>false,
            'message'=>'Gagal menyimpan',
            'errors'=>$model->getErrors()
        ];
    }
}
    public function actionPreviewPdf()
{
    $model = SettingPdf::find()->one();

    return $this->renderPartial('_preview_pdf',[
        'model'=>$model
    ]);
}   

    //TEMPLATE NOTA
    public function actionTemplateNotaList()
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

    $query = TemplateNota::find();

    return [
        'data' => array_map(function($r){
            return [
                'id' => $r->id,
                'name' => $r->name,
                'file' => $r->file,
                'status' => $r->is_active ? 'Aktif' : 'Nonaktif',
                'action' => '
                    <a href="'.Url::to(['setting/edit-template-nota','id'=>$r->id]).'"
                        class="btn btn-primary btn-sm"
                        data-toggle="modal"
                        data-target="#modal-template-nota">Edit</a>
                    <button class="btn btn-danger btn-sm btn-delete-template-nota" data-id="'.$r->id.'">Hapus</button>
                '
            ];
        }, $query->all())
    ];
}
    
    public function actionAddTemplateNota()
{
    $model = new TemplateNota();

    // Jika POST, ambil data manual untuk memastikan load berhasil
    if (Yii::$app->request->isPost) {

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $post = Yii::$app->request->post();

        $model->name = $post['name'] ?? null;
        $model->file = $post['file'] ?? null;
        $model->is_active = isset($post['is_active']) ? $post['is_active'] : 0;

        if ($model->save()) {
            return [
                'success' => true,
                'message' => 'Template Nota berhasil ditambahkan'
            ];
        } else {
            // pastikan message tidak kosong
            $errors = $model->getFirstErrors();
            $msg = !empty($errors) ? implode('<br>',$errors) : 'Gagal menyimpan template, cek input!';
            return [
                'success' => false,
                'message' => $msg,
                'debug' => $model->getErrors() // opsional untuk debugging
            ];
        }
    }

    // Jika bukan POST, tampilkan form modal
    return $this->renderPartial('_form-template-nota', [
        'model' => $model
    ]);
}


    public function actionEditTemplateNota($id = null)
{
    $model = $id ? TemplateNota::findOne($id) : new TemplateNota();

    if (!$model) {
        throw new \yii\web\NotFoundHttpException('Template Nota tidak ditemukan.');
    }

    if (Yii::$app->request->isPost) {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        // Ambil manual dari POST
        $post = Yii::$app->request->post();
        $model->name = $post['name'] ?? null;
        $model->file = $post['file'] ?? null;
        $model->is_active = isset($post['is_active']) ? $post['is_active'] : 0;

        if ($model->save()) {
            return ['success'=>true,'message'=>'Template Nota berhasil disimpan'];
        } else {
            return [
                'success'=>false,
                'message'=>implode('<br>',$model->getFirstErrors()),
                'debug'=>$model->getErrors() // <-- tambahkan ini sementara debug
            ];
        }
    }

    return $this->renderPartial('_form-template-nota', ['model'=>$model]);
}


// Helper method reuse untuk Add/Edit
protected function saveTemplateNota($model)
{
    if (Yii::$app->request->isPost) {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return [
                'success' => true,
                'message' => 'Template Nota berhasil disimpan'
            ];
        } else {
            return [
                'success' => false,
                'message' => implode('<br>', $model->getFirstErrors())
            ];
        }
    }

    // Render partial form untuk modal
    return $this->renderPartial('_form-template-nota', [
        'model' => $model
    ]);
}



    public function actionDeleteTemplateNota()
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $id = Yii::$app->request->post('id');
    $model = TemplateNota::findOne($id);
    if(!$model) return ['success'=>false,'message'=>'Data tidak ditemukan'];

    if($model->delete()){
        return ['success'=>true,'message'=>'Template Nota berhasil dihapus'];
    } else {
        return ['success'=>false,'message'=>'Gagal menghapus data'];
    }
}

    // AKSES
    // List data member untuk DataTable
public function actionMemberList()
{
    $user = Usermember::findOne(Yii::$app->user->id);

    $cluster = Cluster::find()
        ->where(['eDeleted' => 'Tidak', 'idCluster' => $user->idCluster])
        ->one();

    $query = Usermember::find()->where(['eDeleted'=>'Tidak'])->andWhere(['idCluster'=>$user->idCluster]);
    return \yii\helpers\Json::encode([
        'data' => $query->all()
    ]);
}

// Add Member
public function actionAddMember()
{
    $model = new Usermember();
    return $this->saveMember($model);
}

// Edit Member
public function actionEditMember($id)
{
    $model = Usermember::findOne($id);
    return $this->saveMember($model);
}

// Fungsi save member (Add/Edit)
protected function saveMember($model)
{
    if(Yii::$app->request->isPost){
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        if($model->load(Yii::$app->request->post()) && $model->save()){
            return ['success'=>true,'message'=>'Member berhasil disimpan'];
        } else {
            return ['success'=>false,'message'=>implode('<br>', $model->getFirstErrors())];
        }
    }

    return $this->renderPartial('_form-member',['model'=>$model]);
}


// Delete Member
public function actionDeleteMember($id)
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $model = Usermember::findOne($id);
    if ($model) {
        $model->eDeleted = 'Ya';
        $model->save(false);
        return ['success'=>true,'message'=>'Member berhasil dihapus'];
    }
    return ['success'=>false,'message'=>'Member tidak ditemukan'];
}
    
    //Metode Pembayaran User
    public function actionPaymentList()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $rows = PaymentSettings::find()->where(['idCluster'=>Yii::$app->user->identity->idCluster])->all();

        $data = [];

        foreach ($rows as $r) {
            // BCA - 3232832890 a/n Arman
            $data[] = [
                'id' => $r->id,
                'metode' => $r->paymentMethod->name,
                'bank_name' => $r->bank_name.' '.$r->account_number.' a/n '.$r->owner_name,
                // 'account_number' => $r->account_number,
                // 'owner_name' => $r->owner_name,                
                'action' => '
                    <a href="'.Url::to(['setting/edit-payment-setting','id'=>$r->id]).'"
                       class="btn btn-primary btn-sm"
                       data-toggle="modal"
                       data-target="#modal-payment-setting">Edit</a>

                    <button
                        class="btn btn-danger btn-sm btn-delete-payment"
                        data-id="'.$r->id.'">
                        Hapus
                    </button>
                '
            ];
        }

        return ['data' => $data];
    }
    
    public function actionAddPaymentSetting()
    {
        $model = new PaymentSettings();

        // Cek apakah ini edit
        $id = Yii::$app->request->post('id');
        if($id){
            $model = PaymentSettings::findOne($id);
            if(!$model){
                return ['success'=>false,'message'=>'Data tidak ditemukan'];
            }
        }

        if (Yii::$app->request->isPost) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            $model->idCluster = Yii::$app->user->identity->idCluster;

            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return [
                    'success' => true,
                    'message' => 'Metode Pembayaran berhasil disimpan'
                ];
            } else {
                return [
                    'success' => false,
                    'message' => implode('<br>', $model->getFirstErrors())
                ];
            }
        }

        return $this->renderPartial('_form-payment-setting', [
            'model' => $model
        ]);
    }

    
    public function actionEditPaymentSetting($id)
    {
        $model = PaymentSettings::findOne($id);

        if(!$model){
            throw new \yii\web\NotFoundHttpException('Data tidak ditemukan');
        }

        if (Yii::$app->request->isPost) {

            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            if ($model->load(Yii::$app->request->post()) && $model->save()) {

                return [
                    'success' => true,
                    'message' => 'Metode Pembayaran berhasil diupdate'
                ];

            } else {

                return [
                    'success' => false,
                    'message' => implode('<br>', $model->getFirstErrors())
                ];
            }
        }

        return $this->renderPartial('_form-payment-setting', [
            'model' => $model
        ]);
    }
    
    public function actionDeletePaymentSetting()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $id = Yii::$app->request->post('id');

        $model = PaymentSettings::findOne($id);

        if(!$model){
            return ['success'=>false,'message'=>'Data tidak ditemukan'];
        }

        if($model->delete()){
            return ['success'=>true,'message'=>'Setting PDF berhasil dihapus'];
        } else {
            return ['success'=>false,'message'=>'Gagal menghapus data'];
        }
    }

    /**
     * Cari PaymentMethod
     */
    protected function findPaymentMethod($id)
    {
        if (($model = PaymentMethod::findOne($id)) !== null) {
            return $model;
        }
        throw new NotFoundHttpException('Metode pembayaran tidak ditemukan.');
    }
}
