<?php
class SalesInvoiceController extends Controller
{
    public function filters()
    {
        return ['accessControl'];
    }

public function accessRules()
{
    return array(
        array('allow',
    'actions'=>array(
        'index',
        'create',
        'update',
        'view',
        'viewInvoice',
        'save',
        'admin',
        'delete',
        'getAddress',
        'GetList'  
    ),
    'users'=>array('@'), 
),
        array('deny',
            'users'=>array('*'),
        ),
    );
}

    public function actionIndex()
    {
        $model = new SalesInvoice('search');
        $model->unsetAttributes();

        if(isset($_GET['SalesInvoice'])){
            $model->attributes = $_GET['SalesInvoice'];
        }

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

    // OPEN MODAL
    public function actionCreate()
{
    $model = new SalesInvoice();
    $model->invoice_number = 'INV-'.time();

    $customers = CHtml::listData(Customers::model()->findAll('isActive="Y"'), 'id', 'customer_name');
    $products  = InventoryProducts::model()->findAll('isActive="Y"');

    echo $this->renderPartial('create', [
        'model' => $model,
        'customers' => $customers,
        'products' => $products
    ], true, true);

    Yii::app()->end();
}
public function actionGetList()
{
    header('Content-Type: application/json');

    $draw   = isset($_POST['draw']) ? intval($_POST['draw']) : 1;
    $start  = isset($_POST['start']) ? intval($_POST['start']) : 0;
    $length = isset($_POST['length']) ? intval($_POST['length']) : 10;

    $searchValue = isset($_POST['search']['value']) ? $_POST['search']['value'] : '';

    $orderColumnIndex = $_POST['order'][0]['column'];
    $orderDir = $_POST['order'][0]['dir'];

    $columns = [
        'id',
        'invoice_number',
        'customer_name',
        'invoice_date',
        'total_amount',
        'grand_total'
    ];

    $orderColumn = $columns[$orderColumnIndex];

    $criteria = new CDbCriteria();

    if (!empty($searchValue)) {
        $criteria->addSearchCondition('customer_name', $searchValue, true, 'OR');
        $criteria->addSearchCondition('invoice_number', $searchValue, true, 'OR');
    }

    $criteria->order = $orderColumn . ' ' . $orderDir;

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

    $filteredTotal = SalesInvoice::model()->count($criteria);

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

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

    $data = [];

    foreach ($rows as $row) {

        if ($row->status == "Paid") {
    $btn = '<a href="'.Yii::app()->createUrl("salesInvoice/viewInvoice", ["id"=>$row->id]).'" 
            target="_blank" 
            class="btn btn-xs btn-primary">
            View Invoice
        </a>';
} else {
    // Pass a flag in URL to indicate unpaid invoice
    $btn = '<a href="'.Yii::app()->createUrl("salesInvoice/viewInvoice", ["id"=>$row->id]).'" 
            target="_blank" 
            class="btn btn-xs btn-warning">
            View Invoice (Unpaid)
        </a>';
}

        $data[] = [
            $row->id,
            $row->invoice_number,
            $row->customer_name,
            $row->invoice_date,
            number_format($row->total_amount,2),
            number_format($row->grand_total,2),
            $btn
        ];
    }

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

    Yii::app()->end();
}
public function actionViewInvoice($id)
{
    $invoice = SalesInvoice::model()->findByPk($id);

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

    $this->layout = false;

    // Pass a warning flag to the view
    $warning = '';
    if($invoice->status != 'Paid'){
        $warning = 'Invoice not paid yet. Printing is disabled.';
    }

    $this->render('invoice',[
        'invoice'=>$invoice,
        'items'=>$items,
        'warning'=>$warning
    ]);
}
public function actionGetAddress($id)
{
$customer=Customers::model()->findByPk($id);

echo $customer->getAttribute('Address');
}
    // SAVE
   public function actionSave()
{
    if (!isset($_POST['SalesInvoice'])) {
        echo json_encode(['status'=>'error','message'=>'Invalid request']);
        Yii::app()->end();
    }

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

    try {

        $model = new SalesInvoice;
        $model->attributes = $_POST['SalesInvoice'];

        // set required fields
        $model->created_by = Yii::app()->user->id;
        $model->created_date_time = date('Y-m-d H:i:s');

        $totalAmount = 0;

        if (!$model->save()) {
        $errors = $model->getErrors();
        $msg = '';

        foreach ($errors as $fieldErrors) {
            foreach ($fieldErrors as $error) {
                $msg .= $error . "\n";
            }
        }

        throw new Exception(trim($msg));
        }

        if (!empty($_POST['InvoiceItems'])) {

           foreach ($_POST['InvoiceItems'] as $itemData) {

    if (empty($itemData['product_id']))
        continue;

    // GET PRODUCT FROM INVENTORY
    $product = InventoryProducts::model()->findByPk($itemData['product_id']);

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

    // CHECK STOCK
    if ($product->quantity < $itemData['quantity']) {
        throw new Exception("Insufficient stock for SKU: ".$product->sku);
    }

    // SAVE INVOICE ITEM
    $item = new SalesInvoiceItems;
    $item->invoice_id   = $model->id;
    $item->product_id   = $itemData['product_id'];
    $item->sku          = $itemData['sku'];
    $item->product_name = $itemData['product_name'];
    $item->quantity     = $itemData['quantity'];
    $item->unit_price   = $itemData['unit_price'];
    $item->total_price  = $itemData['total_price'];

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

    // REDUCE INVENTORY STOCK
    $product->quantity = $product->quantity - $itemData['quantity'];

    if (!$product->save(false)) {
        throw new Exception("Failed to update inventory stock");
    }

    $totalAmount += $item->total_price;
}
        }

        // update totals
        $model->total_amount = $totalAmount;
       $model->tax_amount = $totalAmount * 0.05;
       $model->grand_total = $totalAmount + $model->tax_amount;
        $model->save(false);

        $transaction->commit();

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

    } catch (Exception $e) {

        $transaction->rollback();

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

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