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

class PurchaseOrder extends CI_Controller {

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

   public function index()
    {
        $data['view']            = 'PurchaseOrder/purchaseOrderView';
        $data['purchaseOrders'] = $this->Purchaseorder_model->getAllPurchaseOrders();

        // 🔹 ONLY previous PO number (display purpose)
        $data['prevPoNo'] = $this->Purchaseorder_model->getPreviousPurchaseOrderNo();

        $this->load->view('master', $data);
    }




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

    $vendors = $this->Purchaseorder_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->Purchaseorder_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('Purchaseorder_model');
    $departments = $this->Purchaseorder_model->getCurrency();

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


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

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

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

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

    // 3️⃣ Fetch all units for these items
    $units = $this->Purchaseorder_model->getUnitsByItems($itemIds);

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

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

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


// Save Purchase Order
public function savePurchaseOrder()
    {
        // Validation
        $this->form_validation->set_rules('vendorId', 'Vendor', 'required');
        $this->form_validation->set_rules('invoiceDate', 'Date', 'required');
        $this->form_validation->set_rules('itemMasterId[]', 'Items', 'required');
        // $userId = $this->session->userdata('userId');set_rules

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

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

$items = $this->input->post();
$count = count($items['itemMasterId']);

for ($i = 0; $i < $count; $i++) {
    $totalWithVat += (float) $items['amountWithVatRow'][$i];
}

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

        /* -------------------------------
           AUTO-GENERATE poNoNumeric
           (NOT from UI)
           ------------------------------- */
        $poNoNumeric = $this->Purchaseorder_model->getNextPoNoNumeric();

        /* Optional: generate poNo internally */
        $poNo = 'PO-' . $poNoNumeric;

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


        /* -------------------------------
           MAIN PO DATA
           ------------------------------- */
        $poData = [
            'poNo'                => $poNo,
            'poNoNumeric'         => $poNoNumeric,
            'vendorId'            => $this->input->post('vendorId'),
            'materialRequestId'   => $this->input->post('materialRequestId'),
            'totalAmount'         => $this->input->post('totalAmount'),
            'amtAfterDiscount'    => $this->input->post('amtwithDiscount'),
            'vatAmount'           => $this->input->post('vatAmount'),
            'discount'            => $this->input->post('totalDiscount'),
            'poDate'              => $this->input->post('invoiceDate'),
            'totalWithVatAmount'  => $totalWithVat,
            'paymentTerms'        => $this->input->post('paymentTerms'),
            'deliveryTerms'       => $this->input->post('deliveryTerms'),
            'currencyId'          => $this->input->post('currency'),
            'exRate'              => $exRate,
            'netAmountWithExRate' => $netAmountWithExRate,
             'userId'              => $userId 
        ];

        /* -------------------------------
           INSERT PO
           ------------------------------- */
        $purchaseOrderId = $this->Purchaseorder_model->insertPurchaseOrder($poData);

        if (!$purchaseOrderId) {
            $this->session->set_flashdata('error', 'Failed to save Purchase Order.');
            redirect('PurchaseOrder');
        }

        /* -------------------------------
           INSERT ITEMS
           ------------------------------- */
        $items = $this->input->post();
        $count = count($items['itemMasterId']);

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

            // $itemUnitArray = explode('-', $items['itemUnitRow'][$i]);
            // $itemUnitId    = $itemUnitArray[0] ?? null;

            $itemData = [
                'purchaseOrderId' => $purchaseOrderId,
                '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]
                
            ];

            $this->Purchaseorder_model->insertPurchaseOrderItem($itemData);
        }

        $this->session->set_flashdata('success', 'Purchase Order saved successfully.');
        redirect('PurchaseOrder');
    }

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

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

    $basic = $this->Purchaseorder_model->getPurchaseOrderEditBasic($poId);
    $items = $this->Purchaseorder_model->getPurchaseOrderEditItems($poId);

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

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


public function updatePurchaseOrder()
{
    $poId = $this->input->post('purchaseOrderIdEdit');

    /* ------------------------------
       UPDATE MAIN PO
    ------------------------------ */
    $exRate = (float) $this->input->post('exRateEdit');
$totalWithVat = (float) $this->input->post('netAmountEdit');

// calculate net amount in local currency
$netAmountWithExRate = $totalWithVat * $exRate;
    $poData = [
    'vendorId'           => $this->input->post('vendorIdEdit'),
    'totalAmount'        => $this->input->post('totalAmountEdit'),
    'vatAmount'          => $this->input->post('vatAmountEdit'),
    'amtAfterDiscount'    => $this->input->post('amtwithDiscountEdit'),
    'totalWithVatAmount' => $totalWithVat,
    'netAmountWithExRate'=> $netAmountWithExRate, // <-- add this
    'paymentTerms'       => $this->input->post('paymentTermsEdit'),
    'deliveryTerms'      => $this->input->post('deliveryTermsEdit'),
    'currencyId'         => $this->input->post('currencyEdit'),
    'exRate'             => $exRate,
    'poDate'             => $this->input->post('invoiceDateEdit'),
    'discount'           => $this->input->post('totalDisAmountEdit'),
];

    $this->Purchaseorder_model->updatePurchaseOrder($poId, $poData);

    /* ------------------------------
       HANDLE ITEMS
    ------------------------------ */
    $itemIds      = $this->input->post('itemMasterIdEdit');
    $rowStatus    = $this->input->post('statusEdit');
    $poItemIds    = $this->input->post('purchaseOrderItemIdEdit');

    $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');
    $discount   = $this->input->post('discountRowEdit');
        $amountAfterDisc = $this->input->post('amtAfterDiscountEdit');
    // $delRow		=$this->input->post('delRowEdit');
    for ($i = 0; $i < count($itemIds); $i++) {

        $itemData = [
            'itemId'        => $itemIds[$i],
            'itemUnitId'    => $unitId[$i],
            'quantity'      => $qty[$i],
            'unitPrice'     => $unitPrice[$i],
            'amount'        => $amount[$i],
            'vatPercent'    => $vatPercent[$i],
            'vatAmount'     => $vatAmount[$i],
            'amountWithVat' => $netAmount[$i],
            'discount'      => $discount[$i],
            'amountAfterDisc' => $amountAfterDisc[$i],
        ];

       if (isset($rowStatus[$i]) && (int)$rowStatus[$i] === 2) {

        $this->Purchaseorder_model
             ->updatePurchaseOrderItem($poItemIds[$i], $itemData);

    } 
    // ✅ NEW ROW
    else {

        $itemData['purchaseOrderId'] = $poId;
        $itemData['status'] = 1;

        $this->Purchaseorder_model
             ->insertPurchaseOrderItem($itemData);
        }
    }

    /* ------------------------------
       HANDLE DELETED ROWS
    ------------------------------ */
   $delRows = $this->input->post('delRowEdit');
if (!empty($delRows)) {
    foreach ($delRows as $poItemId) {
        $this->Purchaseorder_model->deleteFromPurchaseOrderItem($poItemId);
    }
}


    $this->session->set_flashdata('success', 'Purchase Order updated successfully');
    redirect('PurchaseOrder');
}

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

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

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

    // Prepare variables
    $poNumber      = $poData['poNo'];
    // $poDate        = $poData['poDate'];
    $poDate = date('d-m-Y', strtotime($poData['poDate']));
    $vendorAddress    = $poData['vendorAddress'];
    $vendorName    = $poData['vendorName'];
    $vendorPhone1  = $poData['vendorPhone1'];
    $currency      = $poData['currency'];
    $exRate        = $poData['exRate'];
    $paymentTerms  = $poData['paymentTerms'];
    $deliveryTerms = $poData['deliveryTerms'];

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

    // Fetch PO items
    $items = $this->Purchaseorder_model->getPurchaseOrderItems($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">
    
    <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">PURCHASE ORDER</h3>

<table class="no-border">
    <tr>
        <td>
            Vendor Name: <strong>'.$vendorName.'</strong><br><br>

            Vendor Address: <strong>'.$vendorAddress.'</strong><br><br>

            Vendor Phone: <strong>'.$vendorPhone1.'</strong><br>
        </td>
        <td align="right">
            Date: <strong>'.$poDate.'</strong><br><br>

            PO No: <strong>'.$poNumber.'</strong>
        </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 Amount</strong></td>
            <td align="right"><strong>'.number_format($grandTotal, 2).'</strong></td>
        </tr>

        <tr>
            <td colspan="5" align="right"><strong>Vat Amount</strong></td>
            <td align="right"><strong>'.number_format($vatAmount, 2).'</strong></td>
        </tr>

        <tr>
            <td colspan="5" align="right"><strong>Total with Vat</strong></td>
            <td align="right"><strong>'.number_format($totalWithVatAmount, 2).'</strong></td>
        </tr>


        <!-- Payment & Delivery header -->
<tr style="font-weight:bold; text-align:center;">
    <td colspan="3"><strong>Payment Terms</strong></td>
    <td colspan="3"><strong>Delivery Terms</strong></td>
</tr>

<!-- Payment & Delivery content (BOLD) -->
<tr>
    <td colspan="3">'.$paymentTerms.'</td>
    <td colspan="3">'.$deliveryTerms.'</td>
</tr>
    </tfoot>
</table>

<br>


</body>
</html>';

    // Output HTML (for browser print / PDF)
    // echo $html;
// }
// === mPDF ===
// Correct path based on your module structure
ob_start(); // start output buffering

// Your HTML generation code here

require_once APPPATH.'modules/PurchaseOrder/mpdf/vendor/autoload.php';

$mpdf = new \Mpdf\Mpdf([
    'mode' => 'utf-8',
    'format' => 'A4',
    'margin_left' => 10,
    'margin_right' => 10,
    'margin_top' => 20,
    'margin_bottom' => 10,
]);

$mpdf->SetTitle('Purchase Order '.$poNumber);
$mpdf->WriteHTML($html);

// Clear any previous output buffer
ob_end_clean(); 

$mpdf->Output();
exit; // make sure script stops here
}

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

    $this->load->model('PurchaseOrder_model');
    $result = $this->Purchaseorder_model->getMrNoList($term);

    $data = [];

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

    echo json_encode($data);
}


public function getMaterialRequestData()
{
    // "1,2,3"
    $mrIds = $this->input->post('materialRequestId');

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

    // convert to array
    $mrIds = array_filter(explode(',', $mrIds));

    $basic = $this->Purchaseorder_model->getMaterialRequestBasic($mrIds);
    $items = $this->Purchaseorder_model->getMaterialRequestItems($mrIds);

    echo json_encode([
        'success' => true,
        'basic'   => $basic,
        'items'   => $items
    ]);
}
public function searchMaterialRequest()
{
    $term = $this->input->get('term');

    $rows = $this->db
        ->select('materialRequestId, MRNo')
        ->from('acc_materialRequest')
        ->like('MRNo', $term)
        ->limit(10)
        ->get()
        ->result();

    $result = [];

    foreach ($rows as $r) {
        $result[] = [
            'key'   => $r->materialRequestId, // REQUIRED
            'value' => $r->MRNo               // REQUIRED
        ];
    }

    echo json_encode($result);
}


}