<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Deliverynote extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
	
	$this->load->model('Deliverynote_model');
	 $this->load->library('form_validation');
	 $this->load->helper('url');


	}
	public function index()
	{
		$data['view'] = 'deliveryNote/deliveryNote';
         $data['deliveryNotes'] = $this->Deliverynote_model->getAllMR();
        $data['prevDnNo'] = $this->Deliverynote_model->getPreviousDnNo();
		$this->load->view('master', $data);
	}
    

    public function getVendorAutocomplete()
{
    $term = $this->input->post('term') ?? '';  // ensure string

    $vendors = $this->Deliverynote_model->getVendors($term);

    $result = [];
    foreach ($vendors as $row) {
        $result[] = [
            'id' => $row->vendorId,
            'label' => $row->vendorNo,
            'value' => $row->vendorNo,
            'vendorNo' => $row->vendorNo,
            'vendorName' => $row->vendorName
        ];
    }

    echo json_encode($result);
}

public function getVendorNameAutocomplete()
{
    $term = $this->input->post('term') ?? '';  // ensure string

    $vendors = $this->Deliverynote_model->getVendorName($term);

    $result = [];
    foreach ($vendors as $row) {
        $result[] = [
            'id' => $row->vendorId,
            'label' => $row->vendorName,
            'value' => $row->vendorName,
            'vendorNo' => $row->vendorNo,
            'vendorName' => $row->vendorName
        ];
    }

    echo json_encode($result);
}


    public function get_Currency_ajax()
{
    $this->load->model('Deliverynote_model');
    $departments = $this->Deliverynote_model->getCurrency();

    echo json_encode([
        'status' => true,
        'data'   => $departments
    ]);
    exit;
}

public function getitem()
{
    $term = $this->input->post('term') ?? '';

    // 1️⃣ Get items (ARRAY)
    $items = $this->Deliverynote_model->searchItems($term);

    if (empty($items)) {
        echo json_encode([]);
        return;
    }

    // 2️⃣ Collect itemMasterIds
    $itemIds = array_column($items, 'itemMasterId');

    // 3️⃣ Fetch all units (OBJECTS)
    $units = $this->Deliverynote_model->getUnitsByItems($itemIds);

    // 4️⃣ Group units by itemMasterId
    $unitMap = [];
    foreach ($units as $u) {
        $unitMap[$u->itemMasterId][] = [
            'unitId'   => $u->unitId,
            'unitName' => $u->unitName,
            'multiple' => isset($u->multiple) ? $u->multiple : 1
        ];
    }

    // 5️⃣ Build autocomplete response
    $result = [];
    foreach ($items as $row) {
        $result[] = [
            'id'        => $row['itemMasterId'],
            'label'     => $row['itemCode'].'/'.$row['itemName'],
            'itemCode'  => $row['itemCode'],
            'costPrice' => $row['costPrice'],
            'stock'     => $row['stock'],
            'units'     => $unitMap[$row['itemMasterId']] ?? []
        ];
    }

    $this->output
         ->set_content_type('application/json')
         ->set_output(json_encode($result));
}

public function getAdjustedStock()
{
    $itemMasterId = $this->input->post('itemMasterId');
    $itemUnitId   = $this->input->post('itemUnitId');

    $stock    = $this->Deliverynote_model->getRemainingStock($itemMasterId);
    $multiple = $this->Deliverynote_model->getMultiple($itemUnitId);

    $adjustedStock = $stock / $multiple;

    echo json_encode([
        'success'       => true,
        'adjustedStock' => $adjustedStock
    ]);
}


   public function saveDN()
{
    // Validation
    // $this->form_validation->set_rules('vendorId', 'Vendor', 'required');
    $this->form_validation->set_rules('DNDate', 'Date', 'required');
    $this->form_validation->set_rules('itemMasterId[]', 'Items', 'required');

    if ($this->form_validation->run() === FALSE) {
        $this->session->set_flashdata('error', validation_errors());
        redirect('deliveryNote/Deliverynote');
    }

    /* -------------------------------
       CALCULATIONS
       ------------------------------- */
    $totalWithVat = (float) $this->input->post('netAmount');
    $exRate       = (float) $this->input->post('exRate');
    $netAmountWithExRate = $totalWithVat * $exRate;

    /* -------------------------------
       AUTO-GENERATE DN NUMBER
       ------------------------------- */
    $dnNumeric = $this->Deliverynote_model->getNextDNNumeric();
    $poNo = 'DN-' . $dnNumeric;

    /* -------------------------------
       USER FROM COOKIE (SAFE)
       ------------------------------- */
    $cookie = $_COOKIE['user_data'] ?? '';
    $json   = urldecode($cookie);
    $data   = json_decode($json, true);
    $userId = $data['loginId'] ?? 0;

    $dnDate     = $this->input->post('DNDate');
    $vendorName = $this->input->post('vendorName');

    /* -------------------------------
       MAIN DN DATA
       ------------------------------- */
    $poData = [
        'delNo'                => $poNo,
        'delNoNumeric'         => $dnNumeric,
        'materialRequestId'     => $this->input->post('materialRequestId'),
        'jobOrderId'             => $this->input->post('jobCardId'),
        'totalAmount'          => $this->input->post('totalAmount'),
        'amtAfterDiscount'    => $this->input->post('amtwithDiscount'),
        'vatAmount'            => $this->input->post('vatAmount'),
        'delDate'              => $dnDate,
        'totalWithVatAmount'   => $totalWithVat,
        'paymentTerms'         => $this->input->post('paymentTerms'),
        'deliveryTerms'        => $this->input->post('deliveryTerms'),
        'currencyId'           => $this->input->post('currency'),
        'exRate'               => $exRate,
        'netAmountWithExRate'  => $netAmountWithExRate,
        'userId'              => $userId
    ];

    /* -------------------------------
       START DB TRANSACTION
       ------------------------------- */
    $this->db->trans_start();

    $deliveryNoteId = $this->Deliverynote_model->insertMaterialRequest($poData);

    if (!$deliveryNoteId) {
    $this->session->set_flashdata('error', 'Failed to save Delivery Note');
    redirect('deliveryNote/Deliverynote');
}

    /* -------------------------------
       INSERT ITEMS
       ------------------------------- */
    // $items = $this->input->post(NULL, TRUE);
    $items = $this->input->post();


    if (!empty($items['itemMasterId'])) {

        $count = count($items['itemMasterId']);

        for ($i = 0; $i < $count; $i++) {

            $itemData = [
                'deliveryNoteId' => $deliveryNoteId,
                'itemId'         => $items['itemMasterId'][$i],
                'itemUnitId'     => $items['itemUnitId'][$i],
                'quantity'       => $items['quantityRow'][$i],
                'unitPrice'      => $items['unitPriceRow'][$i],
                'amount'         => $items['amountRow'][$i],
                'discount'        => $items['discountRow'][$i],
                'amountAfterDisc' => $items['amtAfterDiscount'][$i],
                'vatPercent'     => $items['vatPercentRow'][$i],
                'vatAmount'      => $items['vatAmountRow'][$i],
                'amountWithVat'  => $items['amountWithVatRow'][$i]
            ];

            $multiple = $this->Deliverynote_model->getMultiple($items['itemUnitId'][$i]);

            $dnDetailsId = $this->Deliverynote_model->insertMaterialRequestItem($itemData);

            if ($dnDetailsId > 0) {

                $updatingStock = $items['quantityRow'][$i] * $multiple;

                // STOCK UPDATE (model should subtract internally)
                $this->Deliverynote_model->updateStockInMaster(
                    $items['itemMasterId'][$i],
                    $updatingStock
                );

                $remainingStock = $this->Deliverynote_model->getRemainingStock(
                    $items['itemMasterId'][$i]
                );

                $itemTransferData = [
                    'invoiceDetailsId'      => $dnDetailsId,
                    'date'                  => $dnDate,
                    'transactionNo'         => $poNo,
                    'vendorOrCustomerName'  => $vendorName,
                    'itemMasterId'          => $items['itemMasterId'][$i],
                    'itemUnitId'            => $items['itemUnitId'][$i],
                    'quantity'              => $items['quantityRow'][$i],
                    'totalQuanity'          => $updatingStock,
                    'transactionType'       => 'DELIVERYNOTE',
                    'stockStatus'           => 'OUT',
                    'userId'                => $userId,
                    'remainingStock'        => $remainingStock,
                    'status'                => '1'
                ];

                $this->Deliverynote_model->insertIntoItemTransferDetails($itemTransferData);
            }
        }
    }

    /* -------------------------------
       COMPLETE TRANSACTION
       ------------------------------- */
    $this->db->trans_complete();

    if ($this->db->trans_status() === FALSE) {
        $this->session->set_flashdata('error', 'Transaction Failed');
    } else {
        $this->session->set_flashdata('success', 'Delivery note saved successfully');
    }

    redirect('deliveryNote/Deliverynote');
}


    public function getPurchaseOrderEdit()
    {
        $dnId = $this->input->post('purchaseOrderId');

        if (!$dnId) {
            echo json_encode(['success' => false]);
            return;
        }

        $basic = $this->Deliverynote_model->getPurchaseOrderEditBasic($dnId);
        $items = $this->Deliverynote_model->getPurchaseOrderEditItems($dnId);

        if (!$basic) {
            echo json_encode(['success' => false]);
            return;
        }

        echo json_encode([
            'success' => true,
            'data'    => [
                'po'    => $basic,
                'items' => $items
            ]
        ]);
    }


public function updatePurchaseOrder()
{
    $dnId = $this->input->post('purchaseOrderIdEdit');
   // echo $dnId;
   //print_r($_POST);
    if (!$dnId) {
        $this->session->set_flashdata('error', 'Invalid deliverynote');
         redirect('deliveryNote/Deliverynote');
    }

    /* ------------------------------
       UPDATE MAIN PO
    ------------------------------ */
    $poData = [
        'jobOrderId'           => $this->input->post('jobCardIdEdit'),
        'totalAmount'        => $this->input->post('totalAmountEdit'),
        'vatAmount'          => $this->input->post('vatAmountEdit'),
        'totalWithVatAmount' => $this->input->post('netAmountEdit'),
        'amtAfterDiscount'    => $this->input->post('amtwithDiscountEdit'),
        'paymentTerms'       => $this->input->post('paymentTermsEdit'),
        'deliveryTerms'      => $this->input->post('deliveryTermsEdit'),
        'currencyId'         => $this->input->post('currencyEdit'),
        'exRate'             => $this->input->post('exRateEdit'),
        'delDate'            => $this->input->post('invoiceDateEdit')
    ];

    $this->Deliverynote_model->updatePurchaseOrder($dnId, $poData);

    /* ------------------------------
       HANDLE ITEMS
    ------------------------------ */
    $itemIds      = $this->input->post('itemMasterIdEdit');
    $poItemIds    = $this->input->post('materialRequestItemIdEdit'); // Changed to materialRequestItemIdEdit 
  /*   echo '<pre>';
print_r($poItemIds);
echo '</pre>';
    echo 's';
    die(); */
    $delRows = $this->input->post('delRowEdit');
    $itemMasterIdEditHIde = $this->input->post('itemMasterIdEditHIde');
    $oldQty = $this->input->post('oldQty');

if (!empty($delRows) && is_array($delRows)) {
    foreach ($delRows as $index => $detailId) {

        $this->Deliverynote_model->deleteFrommaterialRequestDetails($detailId);

        if (isset($itemMasterIdEditHIde[$index]) && isset($oldQty[$index])) {
            $itemId = $itemMasterIdEditHIde[$index];
            $qty    = $oldQty[$index];
            $this->Deliverynote_model->deleteFromTransferTable($detailId);
            $this->Deliverynote_model->updateStockInMasterDelete($itemId, $qty);
        }
    }
}

 $cookie = $_COOKIE['user_data'] ?? '';
    $json   = urldecode($cookie);
    $data   = json_decode($json, true);
    $userId = $data['loginId'] ?? 0;

    // Now handle updates/inserts
    if (!empty($itemIds)) {
        $qty          = $this->input->post('quantityRowEdit');
        $unitPrice   = $this->input->post('unitPriceRowEdit');
        $amount      = $this->input->post('amountRowEdit');
        $vatPercent  = $this->input->post('vatPercentRowEdit');
        $vatAmount   = $this->input->post('vatAmountRowEdit');
        $netAmount   = $this->input->post('amountWithVatRowEdit');
        $unitId      = $this->input->post('itemUnitIdEdit');
        $quantityRowOld = $this->input->post('quantityRowOldEdit');
        $discount   = $this->input->post('discountRowEdit');
        $amountAfterDisc = $this->input->post('amtAfterDiscountEdit');
      

                

        for ($i = 0; $i < count($itemIds); $i++) {
            $itemData = [
                'itemId'        => $itemIds[$i],
                'itemUnitId'    => $unitId[$i],
                'quantity'      => $qty[$i],
                'unitPrice'     => $unitPrice[$i],
                'amount'        => $amount[$i],
                'discount'      => $discount[$i],
                'amountAfterDisc' => $amountAfterDisc[$i],
                'vatPercent'    => $vatPercent[$i],
                'vatAmount'     => $vatAmount[$i],
                'amountWithVat' => $netAmount[$i]
                
                
            ];
             $multiple = $this->Deliverynote_model->getMultiple($unitId[$i]);
             $updatingStock = $qty[$i] * $multiple;
            

            if ( $poItemIds[$i] >0) { // ngk
               // echo 'poitemsid='.$poItemIds[$i];
                // UPDATE existing item
                $updatedQty = $qty[$i]- $quantityRowOld[$i];
                $this->Deliverynote_model->updateStockInMaster($itemIds[$i],$updatedQty);
                $this->Deliverynote_model->updatematerialRequestDetails($poItemIds[$i], $itemData);
                $remainingStock = $this->Deliverynote_model->getRemainingStock(
                    $itemIds[$i]
                );
                 
                $itemTransferDataUpdate = [
                    'invoiceDetailsId'      => $poItemIds[$i],
                    'date'                  => $this->input->post('invoiceDateEdit'),
                    'vendorOrCustomerName'  => $this->input->post('vendorNameEdit'),
                    'itemUnitId'            =>  $unitId[$i],
                    'quantity'              => $qty[$i],
                    'totalQuanity'          => $updatingStock,
                    'remainingStock'        => $remainingStock,
                    
                ];
                $this->Deliverynote_model->updateItemTransferDetails($poItemIds[$i], $itemTransferDataUpdate);
            } else {
                // INSERT new item
    
                $itemData['deliveryNoteId'] = $dnId;
                $itemData['status'] = 1;
                $dnDetailsId = $this->Deliverynote_model->insertMaterialRequestItem($itemData);
                $this->Deliverynote_model->updateStockInMaster($itemIds[$i],$qty[$i]);
                 $remainingStock = $this->Deliverynote_model->getRemainingStock(
                    $itemIds[$i]
                );
                $itemTransferData = [
                    'invoiceDetailsId'      => $dnDetailsId,
                    'date'                  => $this->input->post('invoiceDateEdit'),
                    'transactionNo'         => $this->input->post('poNumberEdit'),
                    'vendorOrCustomerName'  => $this->input->post('vendorNameEdit'),
                    'itemMasterId'          => $itemIds[$i],
                    'itemUnitId'            =>  $unitId[$i],
                    'quantity'              => $qty[$i],
                    'totalQuanity'          => $updatingStock,
                    'transactionType'       => 'DELIVERYNOTE',
                    'stockStatus'           => 'OUT',
                    'userId'                => $userId,
                    'remainingStock'        => $remainingStock,
                    'status'                => '1'
                ];
                
                $this->Deliverynote_model->insertIntoItemTransferDetails($itemTransferData);
            }
        }
    }

   $this->session->set_flashdata('success', 'delivery note updated successfully');
    redirect('deliveryNote/Deliverynote');
}

//print
  // Print Purchase Order
public function printPurchaseOrder($purchaseOrderId)
{
    // Load model
    $this->load->model('Deliverynote_model');

    // Fetch PO header data
    $poData = $this->Deliverynote_model->getPurchaseOrder($purchaseOrderId);

    if (empty($poData)) {
        show_error('Purchase Order not found');
    }

    // Prepare variables
    $poNumber      = $poData['poNo'];
    $poDate        = date("d-M-Y", strtotime($poData['poDate']));
    $vendorCode    = $poData['vendorNo'];
    $vendorName    = $poData['vendorName'];
    $currency      = $poData['currency'];
    $exRate        = $poData['exRate'];
    $paymentTerms  = $poData['paymentTerms'];
    $deliveryTerms = $poData['deliveryTerms'];

    // Total
    $subTotal   = $poData['totalAmount'];
    $grandTotal = $poData['totalAmount'];

    // Fetch PO items
    $items = $this->Deliverynote_model->getmaterialRequestDetailss($purchaseOrderId);

    // Build item rows
    $itemRows = '';
    $i = 1;

    foreach ($items as $row) {
        $itemRows .= '
        <tr>
            <td align="center">'.$i.'</td>
            <td align="left">'.htmlspecialchars($row['itemName']).'</td>
            <td align="center">'.number_format($row['quantity']).'</td>
            <td align="center">'.$row['unitName'].'</td>
            <td align="right">'.number_format($row['unitPrice'], 2).'</td>
            <td align="right">'.number_format($row['amount'], 2).'</td>
        </tr>';
        $i++;
    }

    // Build HTML
    $html = '
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Material Request</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            font-size: 12px;
        }
        table {
            border-collapse: collapse;
            width: 100%;
        }
        th, td {
            border: 1px solid #999;
            padding: 6px;
        }
        th {
            background-color: #D9E7F4;
            text-align: center;
        }
        .no-border td {
            border: none;
        }
    </style>
</head>
<body>

<h3 align="center">MATERIAL REQUEST</h3>

<table class="no-border">
    <tr>
        <td>
            <strong>Vendor Code:</strong> '.$vendorCode.'<br>
            <strong>Vendor Name:</strong> '.$vendorName.'<br>
        </td>
        <td align="right">
            <strong>Date:</strong> '.$poDate.'<br>
            <strong>PO No:</strong> '.$poNumber.'
        </td>
    </tr>
</table>

<br>

<table>
    <thead>
        <tr>
            <th>#</th>
            <th>Item Description</th>
            <th>Qty</th>
            <th>Unit</th>
            <th>Unit Price</th>
            <th>Amount</th>
        </tr>
    </thead>
    <tbody>
        '.$itemRows.'
    </tbody>
    <tfoot>
        <tr>
            <td colspan="5" align="right"><strong>Total</strong></td>
            <td align="right"><strong>'.number_format($grandTotal, 2).'</strong></td>
        </tr>
    </tfoot>
</table>

<br>

<table class="no-border">
    <tr>
        <td><strong>Payment Terms:</strong> '.$paymentTerms.'</td>
        <td><strong>Delivery Terms:</strong> '.$deliveryTerms.'</td>
    </tr>
</table>

</body>
</html>';

    // Output HTML (for browser print / PDF)
    echo $html;
}


public function test()
{
    echo "Controller is accessible!<br>";
    
    // Test model loading
    if($this->Deliverynote_model) {
        echo "Model loaded successfully!<br>";
        
        // Test database connection
        $result = $this->Deliverynote_model->getCurrency();
        echo "<pre>";
        print_r($result);
        echo "</pre>";
    } else {
        echo "Model failed to load!";
    }
}


/**
     * Print Material Request
     */
    public function printDeliveryNote($deliveryNoteId)
    {
        // Load model
        $this->load->model('Deliverynote_model');
        
        // Fetch Material Request header data
       $mrData = $this->db->query("
    SELECT 
        mr.*,
        GROUP_CONCAT(DISTINCT v.jobCardNo SEPARATOR ', ') AS jobCardNo,
        GROUP_CONCAT(DISTINCT v.assignDate SEPARATOR ', ') AS assignDate,
        c.currency,
        c.currencyCode AS symbol
    FROM acc_deliveryNote mr
    LEFT JOIN acc_jobCard v 
        ON FIND_IN_SET(v.jobCardId, mr.jobOrderId) > 0
    LEFT JOIN acc_currency c 
        ON c.currencyId = mr.currencyId
    WHERE mr.deliveryNoteId = ?
    GROUP BY mr.deliveryNoteId
", [$deliveryNoteId])->row_array();


        if (empty($mrData)) {
            show_error('Material Request not found');
        }

        // Fetch Material Request items
        $items = $this->db->query("
            SELECT 
                mrd.*,
                im.itemCode,
                im.itemName,
                im.description,
                u.unitName
            FROM acc_deliveryNoteItems mrd
            LEFT JOIN acc_itemMaster im ON im.itemMasterId = mrd.itemId
            
            LEFT JOIN acc_itemUnit IU ON IU.itemUnitId  = mrd.itemUnitId
            LEFT JOIN acc_unit u ON u.unitId = IU.unitId
            WHERE mrd.deliveryNoteId = ?
            AND mrd.status = 1
            ORDER BY mrd.deliveryNoteId ASC
        ", [$deliveryNoteId])->result_array();

        // Prepare data for view
        $data = [
            'mr' => $mrData,
            'items' => $items,
            'companyName' => $this->session->userdata('companyName') ?? 'Aldana',
            'companyAddress' => $this->session->userdata('companyAddress') ?? 'Your Company Address',
            'companyPhone' => $this->session->userdata('companyPhone') ?? 'Phone',
            'companyEmail' => $this->session->userdata('companyEmail') ?? 'Email',
            'printDate' => date('d-M-Y H:i:s')
        ];

        // Load print view
        $this->load->view('deliveryNote/print_view', $data);
    }
    /* ===============mr details================ */
    public function getMRNoAutocomplete()
    {
        $term = $this->input->post('term');

        $data = $this->Deliverynote_model->getMRNoAutocomplete($term);

        $result = [];

        foreach ($data as $row) {
            $result[] = [
                'label' => $row->MRNo, // display
                'value' => $row->MRNo, // input value
                'id'    => $row->materialRequestId
            ];
        }

        echo json_encode($result);
    }
    /* public function getMRData()
{
    $mrId = $this->input->post('mrId');
    $mrIdsArray = explode(',', $mrId); 

    $main    = $this->Deliverynote_model->getMRMain($mrIdsArray);
    $details = $this->Deliverynote_model->getMRDetails($mrIdsArray);

    echo json_encode([
        'success' => true,
        'main'    => $main,
        'details' => $details
    ]);
}
 */
public function getMRData()
{
    $mrId = $this->input->post('mrId');   // "19,18"
    $mrIdsArray = array_map('trim', explode(',', $mrId));

    $main    = $this->Deliverynote_model->getMRMain($mrIdsArray);
    $details = $this->Deliverynote_model->getMRDetails($mrIdsArray);

    $jobCardNos = [];
    $jobCardIds = [];

    foreach ($main as $row) {
        if (!empty($row->jobCardId)) {
            $jobCardIds[] = $row->jobCardId;
            $jobCardNos[] = $row->jobCardNo;
        }
    }

    $jobCardIds = implode(',', array_unique($jobCardIds));
    $jobCardNos = implode(',', array_unique($jobCardNos));

    echo json_encode([
        'success' => true,
        'jobCardIds' => $jobCardIds,
        'jobCardNos' => $jobCardNos,
        'details' => $details
    ]);
}

    /* ===============mr details ends================ */



}
