<?php

class SalesReturnController extends Controller
{
    public function filters() { return ['accessControl']; }

   public function accessRules()
{
    return [
        ['allow',
            'actions'=>[
                'index',
                'GetList',
                'create',
                'getInvoiceItems',
                'save',
                'view'  
            ],
            'expression'=>'$user->isMember()',
        ],
        ['deny', 'users'=>['*']]
    ];
}

    // Listing page
    public function actionIndex()
    {
        $this->render('index');
    }
public function actionView($id)
{

$return = SalesReturn::model()->findByPk($id);

$items = SalesReturnItems::model()->findAllByAttributes([
'return_id'=>$id
]);

$this->renderPartial('_view_return',[
'return'=>$return,
'items'=>$items
]);

Yii::app()->end();

}
    // AJAX: Get all sales returns for DataTable
    public function actionGetList()
{
    header('Content-Type: application/json');

    $draw   = intval($_POST['draw']);
    $start  = intval($_POST['start']);
    $length = intval($_POST['length']);

    $criteria = new CDbCriteria();

    $total = SalesReturn::model()->count();

    $criteria->limit = $length;
    $criteria->offset = $start;

    $rows = SalesReturn::model()->findAll($criteria);

    $data=[];
    $srNo=$start+1;

    foreach($rows as $row){

        $btn = '<button class="btn btn-xs btn-info view-return-btn" data-id="'.$row->id.'">
        <i class="fa fa-eye"></i> View
        </button>';

        $data[]=[
            $srNo++,
            $row->invoice_number,
            $row->customer_name,
            $row->return_date,
            $btn
        ];
    }

    echo json_encode([
        "draw"=>$draw,
        "recordsTotal"=>$total,
        "recordsFiltered"=>$total,
        "data"=>$data
    ]);

    Yii::app()->end();
}
    // Show invoice selection to create new sales return
public function actionCreate()
{
    $invoices = SalesInvoice::model()->findAll();

    $this->renderPartial('_create_return_form',[
        'invoices'=>$invoices
    ]);
}

    // AJAX: Fetch invoice items
public function actionGetInvoiceItems()
{
    $id = $_GET['id'];

    $invoice = SalesInvoice::model()->findByPk($id);

    $items = SalesInvoiceItems::model()->findAllByAttributes([
        'invoice_id'=>$id
    ]);

    $data = [
        'customer_name'=>$invoice->customer_name,
        'customer_address'=>$invoice->customer_address,
        'items'=>[]
    ];

    foreach($items as $item){
        $data['items'][] = [
            'id'=>$item->id,
            'product_name'=>$item->product_name,
            'sku'=>$item->sku,
            'qty'=>$item->quantity
        ];
    }

    echo json_encode($data);
    Yii::app()->end();
}

    // Save Sales Return
   public function actionSave()
{
    if(!isset($_POST['invoice_id'])){
        echo json_encode(['status'=>'error','message'=>'Invalid request']);
        Yii::app()->end();
    }

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

    try{

        $invoiceId = $_POST['invoice_id'];

        $invoice = SalesInvoice::model()->findByPk($invoiceId);

        if(!$invoice){
            throw new Exception("Invoice not found");
        }

        $return = new SalesReturn();

        $return->invoice_id = $invoiceId;
        $return->invoice_number = $invoice->invoice_number;
        $return->customer_name = $invoice->customer_name;
        $return->return_date = date("Y-m-d H:i:s");
        $return->created_by = Yii::app()->user->id;
        $return->created_date_time = date("Y-m-d H:i:s");

        if(!$return->save()){
            throw new Exception(json_encode($return->getErrors()));
        }

        $hasReturn=false;

        foreach($_POST['return_qty'] as $itemId=>$qty){

            if($qty<=0) continue;

            $hasReturn=true;

            $item = SalesInvoiceItems::model()->findByPk($itemId);

            if(!$item){
                throw new Exception("Invoice item not found");
            }

            $returnItem = new SalesReturnItems();

            $returnItem->return_id = $return->id;
            $returnItem->invoice_item_id = $itemId;
            $returnItem->product_id = $item->product_id;
            $returnItem->sku = $item->sku;
            $returnItem->product_name = $item->product_name;
            $returnItem->sold_qty = $item->quantity;
            $returnItem->return_qty = $qty;
            $returnItem->unit_price = $item->unit_price;

            if(!$returnItem->save()){
                throw new Exception(json_encode($returnItem->getErrors()));
            }

            // update inventory
            $product = InventoryProducts::model()->findByPk($item->product_id);

            if(!$product){
                throw new Exception("Product not found");
            }

            $product->quantity = $product->quantity + $qty;

            if(!$product->save(false)){
                throw new Exception("Inventory update failed");
            }
        }

        if(!$hasReturn){
            throw new Exception("Please enter return quantity");
        }

        $transaction->commit();

        echo json_encode([
            'status'=>'success',
            'message'=>'Sales Return Saved Successfully'
        ]);

    }catch(Exception $e){

        $transaction->rollback();

        echo json_encode([
            'status'=>'error',
            'message'=>$e->getMessage()
        ]);
    }

    Yii::app()->end();
}
}