<?php

namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\ChartIncome;
use App\Models\Client;
use CodeIgniter\Files\File;
use Aws\S3\S3Client;
use App\Models\Orders;
use App\Models\OrderItemModel;
use App\Models\Products;
use App\Models\Qcitem;
use App\Models\PaymentMainModel;
use App\Models\PaymentRecordsModel;

class Invoice extends BaseController
{
    protected $helpers = ['form'];
    protected $Orders;
    protected $orderItemModel;

    public function __construct()
    {
        
        $this->Orders = new Orders();
        $this->orderItemModel = new OrderItemModel();
        $this->Qcitem = new Qcitem();



    }


    public function create()
    {


        return view('templates/v2/header')
        .view('invoicev2/create')
        .view('templates/v2/footer');
    }

    public function create2()
    {

        return view('templates/v2/header')
        .view('invoicev2/create')
        .view('templates/v2/footer');
    }

    public function list()
    {

        return view('templates/v2/header')
        .view('invoicev2/list')
        .view('templates/v2/footer');
    }


    public function payment()
    {

        return view('templates/v2/header')
        .view('invoicev2/payment')
        .view('templates/v2/footer');
    }


    public function delivery()
    {

        return view('templates/v2/header')
        .view('invoicev2/deliverylist')
        .view('templates/v2/footer');
    }
    
    
    public function qcapp()
    {

        return view('static/qcapp');
    }

    public function index()
    {
        $ordersModel = new Orders();
        $orderItemModel = new OrderItemModel();
    
        $search = $this->request->getGet('search');
        $filter = $this->request->getGet('filter');
        $perPage = 10; 

        $totalRows = $ordersModel->hitungg($search, $filter);

        // Load view dengan data orders
        return $this->response->setJSON($totalRows);
    }

    public function print()
    {
        $kode = $this->request->getGet('kode');
        $OrdersData = $this->Orders->getDataby($kode);
        $result['order'] = $OrdersData;
        $orders_item = $this->orderItemModel->getItemby($OrdersData['id']);
        foreach($orders_item as $k => $v) {

            $result['order_item'][] = $v;

        }
        $paymentRecordsModel = new PaymentRecordsModel();
        $totalNetAmount = $paymentRecordsModel->sumNetAmountByBillNo($kode);
        $result['totalNetAmount'] = $totalNetAmount;
        $Products = new Products();
        $data = $Products->getall();
        $result['product'] = $data;
        $result['product'] = json_decode(json_encode($result['product']), true);

        $request = $this->request;
        

        return view('invoice/print', ['result' => $result]);
       
    }

    public function test()
    {    
        $ordersModel = new Orders();
        $orderItemModel = new OrderItemModel();
    
        $search = $this->request->getGet('search');
        $filter = $this->request->getGet('filter');
        $perPage = 10; 

        $totalRows = $ordersModel->hitungg($search, $filter);
        $totalPages = ceil($totalRows / $perPage);
    
        $page = $this->request->getGet('page') ?? 1;
        if ($page > $totalPages) {
            $page = $totalPages;
        }

        $offset = ($page - 1) * $perPage;
        $query = $ordersModel->fimeee($perPage, $offset, $search, $filter);
        $orders = $query->getResultArray();

        $pager = [
            'currentPage' => $page,
            'total' => $totalRows,
            'perPage' => $perPage,
            'totalPages' => $totalPages,
            'links' => []
        ];

        foreach ($orders as &$order) {
            $orderItems = $orderItemModel->where('order_id', $order['id'])->findAll();
            foreach ($orderItems as &$item) {
                $Products = new Products();
                $product = $Products->find($item['product_id']); // Mengambil data produk berdasarkan product_id
                $item['product_name'] = $product['name']; // Menambahkan nama produk ke 'orderItem'
            }
            $order['items'] = $orderItems;
        }
    
        $kipak = ['dado' => 'dado kontol'];
        $data = [
            'orders' => $orders,
            'pager' => $pager,
            'dado kontol' => $kipak
        ];
    
        return $this->response->setJSON($data);
    }

    public function deleteOrder()
    {
        $kode = $this->request->getGet('kode');

        $orderModel = new Orders();
        $orderItemModel = new OrderItemModel();
        $OrdersData = $this->Orders->getDataby($kode);
        $result['order'] = $OrdersData;
        $orderItemModel->where('order_id', $result['order']['id'])->delete();
        // Menghapus pesanan dari tabel orders
        $orderModel->delete($result['order']['id']);
        // Redirect atau berikan respon sesuai kebutuhan
        return redirect()->to('/invoice/list')->with('success', 'Pesanan berhasil dihapus');
    }
    
    public function getDelivery()
    {
       
    $db      = \Config\Database::connect();
    $builder = $db->table('orders_item');
    $builder->select('*, orders_item.qty AS qty, orders_item.details AS details, products.qty AS product_qty, orders.id AS orders_id');
    $builder->join('orders', 'orders.id = orders_item.order_id');
    $builder->join('products', 'products.id = orders_item.product_id');
    $builder->where('status_produksi !=', 2);
    $builder->where('type', 0);
    $builder->orderBy('date_time', 'DESC');
    $query = $builder->get();

    $result = $query->getResultArray();

    // Format data order item sesuai kebutuhan
    $orderItemsData = [];
    foreach ($result as $row) {
        $orderItemData = [
            'tanggal_order' => $row['tanggal_order'],
            'bill_no' => $row['bill_no'],
            'item_code' => $row['item_code'],
            'customer_name' => $row['customer_name'],
            'product_name' => $row['name'], // Menggunakan nama produk dari tabel products
            'details' => $row['details'],
            'length' => $row['length'],
            'width' => $row['width'],
            'pcs' => $row['pcs'],
            'hasilqc' => $row['hasilqc'],
        ];

        // Tambahkan data order item ke dalam array
        $orderItemsData[] = $orderItemData;
    }

    $responseData = [
        'data' => $orderItemsData
    ];
    
        return $this->response->setJSON($responseData);
    }

    
    public function getData()
    {
        $ordersModel = new Orders();
        $draw = $this->request->getPost('draw');
        $start = $this->request->getPost('start');
        $length = $this->request->getPost('length');
        $searchValue = $this->request->getPost('search')['value'];
        $columnName = ['date_time', 'bill_no', 'customer_name', 'net_amount', 'paid_status'];
        $order = $this->request->getPost('order')[0];
        $orderBy = $columnName[$order['column']];
        $orderDir = $order['dir'];
        $orderDir = 'DESC';
        
        $totalRecords = $ordersModel->countAll();
        $totalFiltered = $totalRecords;
    
        $ordersModel->select('*');
    
        if (!empty($searchValue)) {
            $ordersModel->groupStart()
                ->like('customer_name', $searchValue)
                ->orLike('bill_no', $searchValue)
                ->groupEnd();
            $totalFiltered = $ordersModel->countAllResults(false);
        }
    
        $startDate = $this->request->getPost('startDate');
        $endDate = $this->request->getPost('endDate');
        if (!empty($startDate) && !empty($endDate)) {
            $ordersModel->where('date_time >=', $startDate)
                ->where('date_time <=', $endDate);
        }
    
        $ordersModel->orderBy($orderBy, $orderDir);
    
        // Pagination
        $orders = $ordersModel->paginate($length, 'default', $start / $length + 1);
    
        $data = [];
        if (!empty($orders)) {
            foreach ($orders as $order) {
                $formattedDateTime = date('Y-m-d', $order['date_time']);
                $formattedNetAmount = 'Rp ' . number_format($order['net_amount'], 0, ',', '.');
                $paidStatusLabel = '';
                    switch ($order['paid_status']) {
                        case 1:
                            $paidStatusLabel = '<span style="color:white;" class="badge rounded-pill bg-success"><p>Dibayar</p></span>';
                            break;
                        case 2:
                            $paidStatusLabel = '<span style="color:white;"class="badge rounded-pill bg-warning"><p>Belum Dibayar</p></span>';
                            break;
                        case 3:
                            $paidStatusLabel = '<span style="color:white;" class="badge rounded-pill bg-primary"><p>Partial</p></span>';
                            break;
                        default:
                            $paidStatusLabel = '-';
                            break;
                    }
                    $editButton = '<a class="btn btn-icon btn-primary mr-1" href="' . base_url('invoice/update?kode=') . $order['bill_no'] . '"><i class="fa-solid fa-pencil"></i></a><a class="btn btn-icon btn-secondary  mr-1" href="' . base_url('invoice/qcupdate?kode=') . $order['bill_no'] . '"><i class="fa-solid fa-money-bill-wave"></i></a><a class="btn btn-icon  btn-success mr-1" href="' . base_url('invoice/print?kode=') . $order['bill_no'] . '"><i class="fa-solid fa-print"></i></a><button class="btn btn-icon btn-danger delete-btnz" onclick="contoh(\'' . $order['bill_no'] . '\')"><i class="fa-solid fa-trash"></i></button>';
                    $rowData = [
                    $formattedDateTime,
                    $order['bill_no'],
                    $order['customer_name'],
                    $formattedNetAmount,
                    $paidStatusLabel,
                    $editButton,
                    
                ];
                $data[] = $rowData;
            }
        }
    
        $json_data = array(
            "draw" => intval($draw),
            "recordsTotal" => intval($totalRecords),
            "recordsFiltered" => intval($totalFiltered),
            "data" => $data
        );
    
        echo json_encode($json_data);
    }
    



    public function update()
    {
        $kode = $this->request->getGet('kode');

        // Periksa apakah $kode memiliki nilai
        if (!$kode) {
            // Jika tidak, tampilkan view lain
            return view('templates/header')
                . view('invoice/create')
                . view('templates/footer');
        }


        $OrdersData = $this->Orders->getDataby($kode);
        $result['order'] = $OrdersData;
        $orders_item = $this->orderItemModel->getItemby($OrdersData['id']);
        foreach($orders_item as $k => $v) {

            $result['order_item'][] = $v;

        }
        $paymentRecordsModel = new PaymentRecordsModel();
        $totalNetAmount = $paymentRecordsModel->sumNetAmountByBillNo($kode);
        $result['totalNetAmount'] = $totalNetAmount;
        
        $Products = new Products();
        $data = $Products->getall();
        $result['product'] = $data;
        $result['product'] = json_decode(json_encode($result['product']), true);

        $payment_data = $paymentRecordsModel->getItemby($kode);
        foreach($payment_data as $c => $b) {

            $result['payment_data'][] = $b;

        }

        $request = $this->request;
        

        return view('templates/v2/header')
        .view('invoicev2/update', ['result' => $result])
        .view('templates/v2/footer');
      
       
    }

    public function activity()
    {
        $kode = $this->request->getGet('kode');

        // Periksa apakah $kode memiliki nilai
        if (!$kode) {
            // Jika tidak, tampilkan view lain
            return view('templates/header')
                . view('invoice/create')
                . view('templates/footer');
        }


        $OrdersData = $this->Orders->getDataby($kode);
        $result['order'] = $OrdersData;
        $orders_item = $this->orderItemModel->getItemby($OrdersData['id']);
        foreach($orders_item as $k => $v) {

            $result['order_item'][] = $v;

        }
        $paymentRecordsModel = new PaymentRecordsModel();
        $totalNetAmount = $paymentRecordsModel->sumNetAmountByBillNo($kode);
        $result['totalNetAmount'] = $totalNetAmount;
        
        $Products = new Products();
        $data = $Products->getall();
        $result['product'] = $data;
        $result['product'] = json_decode(json_encode($result['product']), true);

        $payment_data = $paymentRecordsModel->getItemby($kode);
        foreach($payment_data as $c => $b) {

            $result['payment_data'][] = $b;

        }

        $request = $this->request;
        

        return $this->response->setJSON($result);
      
       
    }

    public function qcupdate()
    {
        $kode = $this->request->getGet('kode');
        $OrdersData = $this->Orders->getDataby($kode);
        $result['order'] = $OrdersData;
        $orders_item = $this->orderItemModel->getItemby($OrdersData['id']);
        foreach($orders_item as $k => $v) {

            $result['order_item'][] = $v;

        }
        $Products = new Products();
        $data = $Products->getall();
        $result['product'] = $data;
        $result['product'] = json_decode(json_encode($result['product']), true);

        $history_data = $this->Qcitem->getby($result['order']['id']);
        foreach ($history_data as $qcitem) {
            $item_code = $qcitem['item_code'];
            $details = $this->orderItemModel->getItemByItemCode($item_code);
            $qcitem['details'] = $details;
            $result['history_data'][] = $qcitem;
        }
        
        $request = $this->request;
return view('templates/v2/header')
      .view('invoicev2/qcupdate', ['result' => $result])
        .view('templates/v2/footer');
     //   return $this->response->setJSON($result);
       
    }

    public function getproducts()
    {
        $Products = new Products();
        $data = $Products->getall();


        return $this->response->setJSON($data);

    }

    public function qcpost()
    {
        $request = $this->request;
        $order_id = $request->getPost('id');
        $status_produksi = $request->getPost('status_produksi');
        $tgl_selesai = $request->getPost('tgl_selesai');
        $item_codes = $request->getPost('item_code');
       
        $hasilqc = $request->getPost('hasilqc');
        $reject = $request->getPost('reject');
        $hasilqc_new = $request->getPost('hasilqc_new');
        $reject_new = $request->getPost('reject_new');

        
        $qcData = [];
        $orderData = [];
        $updateData = [];
        for ($i = 0; $i < count($item_codes); $i++) {
            $item_code_array = $item_codes[$i];
            $hasilqc_array = $hasilqc[$i];
            $reject_array = $reject[$i];
            $hasilqc_new_array = $hasilqc_new[$i];
            $reject_new_array = $reject_new[$i];
            $orderItem = $this->orderItemModel->getByItemCode($item_code_array);
            $length = $orderItem['length'];
            $pcs = $orderItem['pcs'];
          
            // Periksa apakah hasilqc_new atau reject_new memiliki nilai
            if ($hasilqc_new_array !== '' || $reject_new_array !== '') {
                // Jika salah satu memiliki nilai, tambahkan data ke $qcData
                $qc_code = 'ITEM-' . strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 5));
                $qcData[] = [
                    'order_id' => $order_id,
                    'qc_code' => $qc_code,
                    'item_code' => $item_code_array,
                    'hasilqc' => $hasilqc_new_array,
                    'reject' => $reject_new_array,
                    'date_time' => strtotime(date('Y-m-d h:i:s a')),
                ];
                $hasilqc_array = floatval($hasilqc[$i]);
                $hasilqc_new_array = floatval($hasilqc_new[$i]);
                $reject_array = floatval($reject[$i]);
                $reject_new_array = floatval($reject_new[$i]);
                $hasilqcad = ($hasilqc_array ?? 0) + ($hasilqc_new_array ?? 0);
                $rejectad = ($reject_array ?? 0) + ($reject_new_array ?? 0);
                $subtotal = $length * $hasilqcad;
                $subreject = $length * $rejectad;
                $totalqc = $subtotal + $subreject;    
                $updateData[] = [
                    'order_id' => $order_id,
                    'item_code' => $item_code_array,
                    'reject' => $rejectad,
                    'hasilqc' => $hasilqcad,
                    'totalqc' => $totalqc,
                    'totalreject' => $subreject,

                ];

                
            }
        }

        
        
        foreach ($updateData as $data) {
            $item_code = $data['item_code'];
            // Temukan ID baris yang sesuai dengan item_code
            $row = $this->orderItemModel->where('item_code', $item_code)->first();
            if ($row) {
                $item_id = $row['id']; // Ambil ID baris
                // Hapus item_code dari data yang akan diperbarui
                unset($data['item_code']);
                // Lakukan pembaruan dengan ID baris yang ditemukan
                $this->orderItemModel->update($item_id, $data);
            }
       
        }

        if (!empty($qcData)) {
            $this->Qcitem->insertBatch($qcData);
        }
        $orderData = [
            'tgl_selesai' => $tgl_selesai,
            'status_produksi' => $status_produksi,
        ];

        $this->Orders->updateOrder($order_id, $orderData);
        $combinedData = [
            'qcData' => $qcData,
            'updateData' => $updateData,
            'orderData' => $orderData
        ];

        $order = $this->Orders->getDatabyid($order_id);
        $bill_No = $order['bill_no'];
    
        // Redirect ke qcupdate dengan parameter kode
        return redirect()->to('/invoice/qcupdate?kode=' . $bill_No)->with('success', 'Pesanan berhasil diperbaharui');
    

        // Pastikan kamu mengembalikan response setelah looping selesai, bukan di dalam looping
    }


    public function post()
    {
        $request = $this->request;
        $order_id = $request->getPost('id');
    
        $paid_status = $request->getPost('paid_status');
        $payment_amount =$request->getPost('payment_amount');
        $orderData = [
            'bill_no' => $request->getPost('bill_no'),
            'client_key' => $request->getPost('client'),
            'customer_name' => $request->getPost('customer_name'),
            'customer_phone' => $request->getPost('customer_phone'),
            'customer_address' => $request->getPost('customer_address'),
            'tanggal_order' => $request->getPost('tanggal_order'),
            'paid_status' => $paid_status,
            'status_order' => $request->getPost('status_order'),
            'cat_order' => $request->getPost('cat_order'),
            'cat_order2' => $request->getPost('cat_order2'),
            'type_produksi' => $request->getPost('type_produksi'),   
         ];

         $orderId = $this->Orders->updateOrder($order_id, $orderData);

         if ($orderId) {
            // Retrieve form data
            $productIds = $request->getPost('product');
            $widths = $request->getPost('width');
            $lengths = $request->getPost('length');
            $pcs = $request->getPost('pcs');
            $images = $request->getFileMultiple('image');
            $rate = $request->getPost('rate_value');
            $details = $request->getPost('details');
            $item_codes = $request->getPost('item_code');
            $type = $request->getPost('type');
            $imagetextz = $request->getPost('imagetext');
            $hasilqc = $request->getPost('hasilqc');
            $reject = $request->getPost('reject');

    
            // Initialize order item data array
            $orderItemData = [];
    
            // Check if all form data arrays are not empty
            if (!empty($productIds) && !empty($widths) && !empty($lengths) && !empty($pcs) && !empty($images) && !empty($rate) && !empty($details) && !empty($item_codes) && !empty($type) && !empty($imagetextz)) {
                // Loop through form data arrays to populate order item data
                for ($i = 0; $i < count($productIds); $i++) {
                    // Retrieve data for current iteration
                    $product_id = $productIds[$i];
                    $detail = $details[$i];
                    $item_code = isset($item_codes[$i]) ? $item_codes[$i] : '';
                    $rates = $rate[$i];
                    $width = $widths[$i];
                    $length = $lengths[$i];
                    $imagetext = $imagetextz[$i];
                    $pcs_array = $pcs[$i];
                    $meter = $lengths[$i] * $pcs[$i];
                    $type_array = $type[$i];
                    $orderItem = $this->orderItemModel->getByItemCode($item_code);

                    if (empty($orderItem)) {
                        $reject_array = $reject[$i];
                        $hasilqc_array = $hasilqc[$i]; // Misalnya, inisialisasi hasilqc ke 0 jika tidak ditemukan
                    } else {
                        $reject_array = $orderItem['reject'];
                        $hasilqc_array = $orderItem['hasilqc'];
                    }
                    $lengthx = floatval($lengths[$i]);
                    $rejectx = floatval($reject_array);
                    $totalreject_array = $length * $rejectx;
                    $subtotalqc = floatval($lengths[$i]) * floatval($hasilqc_array);
                    $totalqc = $subtotalqc + $totalreject_array;

    
                    // Calculate amount based on type
                    if ($type_array === 'meter') {
                        $amount = $rates * $meter;
                    } elseif ($type_array === 'pcs') {
                        $amount = $rates * $pcs_array;
                    }
    
                    // Generate item code if empty
                    if (empty($item_code)) {
                        $item_code = 'ITEM-' . strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 5));
                    }
                    
                    
        
                    // Periksa apakah ada file gambar yang diunggah untuk produk saat ini
                    if (isset($images[$i]) && $images[$i] && $images[$i]->isValid() && !$images[$i]->hasMoved()) {
                        $image = $images[$i];
                        // Proses upload gambar ke S3
                        // (Kode upload gambar ke S3)
                        $s3Client = new S3Client([
                            'version' => 'latest',
                            'region' => 'Global',
                            'url' => 'https://is3.cloudhost.id/texapp/api/',
                            'use_path_style_endpoint' => true,
                            'endpoint' => 'https://is3.cloudhost.id/',
                            'credentials' => [
                                'key' => '4Y7M0354JXFYU8YNZLQO',
                                'secret' => 'ouVVphb4YbQ3YSazWQJngEY7DDm92nQfIUzGzHPQ'
                            ]
                        ]);
        
                        $bucket = 'texapp';
                        $imageName = $image->getRandomName();
                        try {
                            $result = $s3Client->putObject([
                                'Bucket' => $bucket,
                                'Key' => 'order_items/' . $imageName,
                                'Body' => fopen($image->getTempName(), 'rb'), // Upload file langsung dari file temporary
                                'ACL' => 'public-read'
                            ]);
        
                            $image = $result['ObjectURL'];
                        } catch (Aws\S3\Exception\S3Exception $e) {
                            return redirect()->back()->withInput()->with('error', 'Failed to upload image to S3.');
                        }
                    } else {
                        $image = $imagetext;
                    }
        
                    $orderItemData[] = [
                        'order_id' => $order_id,
                        'product_id' => $product_id, 
                        'item_code' => $item_code, 
                        'length' => $length, 
                        'width' => $width,
                        'pcs' => $pcs_array,
                        'amount' => $amount,
                        'qty' => $meter, 
                        'rate' => $rates,
                        'tipe' => $type_array, 
                        'image' => $image,
                        'details' => $detail,
                        'hasilqc' => $hasilqc_array,
                        'reject' => $reject_array, 
                        'totalreject' => $totalreject_array,
                        'totalqc' => $totalqc,
                    ];

                }
            } else {
                for ($i = 0; $i < count($productIds); $i++) {
                    // Retrieve data for current iteration
                    $product_id = $productIds[$i];
                    $detail = $details[$i];
                    $item_code = isset($item_codes[$i]) ? $item_codes[$i] : '';
                    $rates = $rate[$i];
                    $width = $widths[$i];
                    $length = $lengths[$i];
                    $imagetext = $imagetextz[$i];
                    $pcs_array = $pcs[$i];
                    $meter = $lengths[$i] * $pcs[$i];
                    $type_array = $type[$i];
                    $orderItem = $this->orderItemModel->getByItemCode($item_code);

                    if (empty($orderItem)) {
                        $reject_array = $reject[$i];
                        $hasilqc_array = $hasilqc[$i]; // Misalnya, inisialisasi hasilqc ke 0 jika tidak ditemukan
                    } else {
                        $reject_array = $orderItem['reject'];
                        $hasilqc_array = $orderItem['hasilqc'];
                    }
                    $lengthx = floatval($lengths[$i]);
                    $rejectx = floatval($reject_array);
                    $totalreject_array = $lengthx * $rejectx;
                    $subtotalqc = floatval($lengths[$i]) * floatval($hasilqc_array);
                    $totalqc = $subtotalqc + $totalreject_array;

    
                    // Calculate amount based on type
                    if ($type_array === 'meter') {
                        $amount = $rates * $meter;
                    } elseif ($type_array === 'pcs') {
                        $amount = $rates * $pcs_array;
                    }
    
                    // Generate item code if empty
                    if (empty($item_code)) {
                        $item_code = 'ITEM-' . strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 5));
                    }
                    
                    
        
                    // Periksa apakah ada file gambar yang diunggah untuk produk saat ini
                    if (isset($images[$i]) && $images[$i] && $images[$i]->isValid() && !$images[$i]->hasMoved()) {
                        $image = $images[$i];
                        // Proses upload gambar ke S3
                        // (Kode upload gambar ke S3)
                        $s3Client = new S3Client([
                            'version' => 'latest',
                            'region' => 'Global',
                            'url' => 'https://is3.cloudhost.id/texapp/api/',
                            'use_path_style_endpoint' => true,
                            'endpoint' => 'https://is3.cloudhost.id/',
                            'credentials' => [
                                'key' => '4Y7M0354JXFYU8YNZLQO',
                                'secret' => 'ouVVphb4YbQ3YSazWQJngEY7DDm92nQfIUzGzHPQ'
                            ]
                        ]);
        
                        $bucket = 'texapp';
                        $imageName = $image->getRandomName();
                        try {
                            $result = $s3Client->putObject([
                                'Bucket' => $bucket,
                                'Key' => 'order_items/' . $imageName,
                                'Body' => fopen($image->getTempName(), 'rb'), // Upload file langsung dari file temporary
                                'ACL' => 'public-read'
                            ]);
        
                            $image = $result['ObjectURL'];
                        } catch (Aws\S3\Exception\S3Exception $e) {
                            return redirect()->back()->withInput()->with('error', 'Failed to upload image to S3.');
                        }
                    } else {
                        $image = $imagetext;
                    }
        
                    $orderItemData[] = [
                        'order_id' => $order_id,
                        'product_id' => $product_id, 
                        'item_code' => $item_code, 
                        'length' => $length, 
                        'width' => $width,
                        'pcs' => $pcs_array,
                        'amount' => $amount,
                        'qty' => $meter, 
                        'rate' => $rates,
                        'tipe' => $type_array, 
                        'image' => $image,
                        'details' => $detail,
                        'hasilqc' => $hasilqc_array,
                        'reject' => $reject_array, 
                        'totalreject' => $totalreject_array,
                        'totalqc' => $totalqc,
                    ];

                }
            }

           

            $this->orderItemModel->deleteOrderItemsByOrderId($order_id);
            $this->orderItemModel->insertBatch($orderItemData);


            $totalAmount = 0;
            foreach ($orderItemData as $orderItem) {
                $totalAmount += $orderItem['amount'];
            }
    
            if ($paid_status == '1' || $paid_status == '3') {
                $this->handlePayment($orderData, $totalAmount, $paid_status, $payment_amount);
            }
    
            $orderData2 = [
                'net_amount' => $totalAmount,
                'gross_amount' => $totalAmount,
                'paid_status'   => $paid_status,
             ];
    
             $this->Orders->updateOrder($order_id, $orderData2);

             $combinedData = [
                'orderItemData' => $orderItemData,
                'orderData' => $orderData,
                'orderData2' => $orderData2
            ];

            $order = $this->Orders->getDatabyid($order_id);
        $bill_No = $order['bill_no'];


            return redirect()->to('/invoice/update?kode=' . $bill_No)->with('success', 'Pesanan berhasil diperbaharui');
        }
         
    }    

    public function store()
{
    $request = $this->request;
    do {
        // Generate a random bill number
        $bill_no = 'TPINV-' . strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 5));
        
        // Check if the generated bill number already exists
        $existingOrder = $this->Orders->getOrderByBillNo($bill_no);
    } while ($existingOrder);

    $paid_status = $request->getPost('paid_status');
    $payment_amount =$request->getPost('payment_amount');
    $orderData = [
        'bill_no' => $bill_no,
        'client_key' => $request->getPost('client'),
        'customer_name' => $request->getPost('customer_name'),
        'customer_phone' => $request->getPost('customer_phone'),
        'customer_address' => $request->getPost('customer_address'),
        'tanggal_order' => $request->getPost('tanggal_order'),
        'paid_status' => $paid_status,
        'date_time' => strtotime(date('Y-m-d h:i:s a')),
        'status_order' => $request->getPost('status_order'),
        'cat_order' => $request->getPost('cat_order'),
        'cat_order2' => $request->getPost('cat_order2'),
        'type_produksi' => $request->getPost('type_produksi'),   
     ];

    $orderId = $this->Orders->insertOrder($orderData);

    if ($orderId) {
        $productIds = $request->getPost('product_id');
        $widths = $request->getPost('width');
        $lengths = $request->getPost('length');
        $pcs = $request->getPost('pcs'); 
        $images = $request->getFileMultiple('image');
        $rate = $request->getPost('rate_value');
        $details = $request->getPost('details');
        $type = $request->getPost('type');

        $orderItemData = [];

        // Gabungkan data dari form input dengan URL gambar yang telah diunggah
        for ($i = 0; $i < count($productIds); $i++) {
            // Ambil data produk yang sesuai dengan indeks saat ini
            $product_id = $productIds[$i];
            $item_code = 'ITEM-' . strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 8));
            $detail = $details[$i];
            $rates = $rate[$i];
            $width = $widths[$i];
            $length = $lengths[$i];
            $pcs_array = $pcs[$i];
            $meter = $lengths[$i] * $pcs[$i];
            $type_array = $type[$i];
            if ($type_array === 'meter') {
                $amount = $rates * $meter;
            } elseif ($type_array === 'pcs') {
                $amount = $rates * $pcs_array;
            }
            
            

            // Periksa apakah ada file gambar yang diunggah untuk produk saat ini
            if (isset($images[$i]) && $images[$i] && $images[$i]->isValid() && !$images[$i]->hasMoved()) {
                $image = $images[$i];
                // Proses upload gambar ke S3
                // (Kode upload gambar ke S3)
                $s3Client = new S3Client([
                    'version' => 'latest',
                    'region' => 'Global',
                    'url' => 'https://is3.cloudhost.id/texapp/api/',
                    'use_path_style_endpoint' => true,
                    'endpoint' => 'https://is3.cloudhost.id/',
                    'credentials' => [
                        'key' => '4Y7M0354JXFYU8YNZLQO',
                        'secret' => 'ouVVphb4YbQ3YSazWQJngEY7DDm92nQfIUzGzHPQ'
                    ]
                ]);

                $bucket = 'texapp';
                $imageName = $image->getRandomName();
                try {
                    $result = $s3Client->putObject([
                        'Bucket' => $bucket,
                        'Key' => 'order_items/' . $imageName,
                        'Body' => fopen($image->getTempName(), 'rb'), // Upload file langsung dari file temporary
                        'ACL' => 'public-read'
                    ]);

                    // Simpan URL gambar ke dalam variabel $image
                    $image = $result['ObjectURL'];
                } catch (Aws\S3\Exception\S3Exception $e) {
                    // Jika gagal, tampilkan pesan error atau kembali ke halaman create
                    return redirect()->back()->withInput()->with('error', 'Failed to upload image to S3.');
                }
            } else {
                // Jika tidak ada file gambar yang diunggah untuk produk saat ini, berikan nilai default
                $image = 'default_image_url.jpg'; // Misalnya, URL gambar default
            }
            // Tambahkan data order item ke dalam array

            $orderItemData[] = [
                'order_id' => $orderId,
                'product_id' => $product_id, 
                'item_code' => $item_code, 
                'length' => $length, 
                'width' => $width,
                'pcs' => $pcs_array,
                'amount' => $amount,
                'qty' => $meter, 
                'rate' => $rates,
                'tipe' => $type_array, 
                'image' => $image,
                'details' => $detail,
                // Tambahkan field lainnya sesuai kebutuhan
            ];
        }

        // Simpan data ke tabel orders_item
        $this->orderItemModel->insertBatch($orderItemData);
        echo json_encode($orderItemData);
        echo json_encode($orderData);

        $totalAmount = 0;
        foreach ($orderItemData as $orderItem) {
            $totalAmount += $orderItem['amount'];
        }

        if ($paid_status == '1' || $paid_status == '3') {
            $this->handlePayment($orderData, $totalAmount, $paid_status, $payment_amount);
        }

        $orderData2 = [
            'net_amount' => $totalAmount,
            'gross_amount' => $totalAmount,
            'paid_status'   => $paid_status,
         ];
         $this->Orders->updateOrder($orderId, $orderData2);
         return redirect()->to('/invoice/update?kode=' . $orderData['bill_no'])->with('success', 'Pesanan berhasil diperbaharui');

    
                // Redirect ke halaman detail invoice
       // return redirect()->to('invoice/detail/' . $orderId);
    } else {
        // Jika gagal, tampilkan pesan error atau kembali ke halaman create
        return redirect()->back()->withInput()->with('error', 'Failed to create invoice.');
    }
}

private function handlePayment($orderData, $totalAmount, $paid_status, $payment_amount) {
    $paidStatus = '';

    if ($paid_status == '1') {
        $paidStatus = 'Dibayar';
    } elseif ($paid_status == '2') {
        $paidStatus = 'Belum Dibayar';
    } elseif ($paid_status == '3') {
        $paidStatus = 'Partial';
    }
    // Check if payment amount is not 0
    if ($payment_amount != 0) {
        // If payment amount is not 0, generate transaction code and insert payment data
        $transactionCode = $this->generateRandomString(7);
        $paymentMainModel = new PaymentMainModel();
        $paymentMainData = [
            'transaction_code' => $transactionCode,
            'client_key' => $orderData['client_key'],
            'date_created' => date('Y-m-d H:i:s'), // Current datetime
            'paid_status' => $paidStatus,
        ];
        $paymentMainModel->insert($paymentMainData);
        $paymentRecordsModel = new PaymentRecordsModel();
        $paymentRecordsData = [
            'transaction_code' => $transactionCode,
            'client_key'    => $orderData['client_key'],
            'bill_no'       => $orderData['bill_no'],
            'customer_name' => $orderData['customer_name'],
            'tanggal_order' => $orderData['tanggal_order'],
            'net_amount'    => $payment_amount,
            'date_created'  => date('Y-m-d H:i:s'), // Current datetime
            'paid_status'   => $paid_status,
            'payment_code'  => $this->generateRandomString(7), // Generate payment code
        ];
        $paymentRecordsModel->insert($paymentRecordsData);
       return;
    } else {
        // If payment amount is 0, simply skip the payment process
        return;
    }
    return;

}

private function generateRandomString($length = 7)
{
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';

    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }

    return $randomString;
}

    
    
    
   public function testz()
    {    
        $ordersModel = new Orders();
        $orderItemModel = new OrderItemModel();
    
        $search = $this->request->getGet('search');
    
        if (!empty($search)) {
            $ordersModel->like('bill_no', $search);
            $ordersModel->orLike('customer_name', $search);
        }
        $ordersModel->where('status_order', 2);
        $ordersModel->orderBy('tanggal_order', 'desc');
        $totalRows = $ordersModel->countAllResults(false);
    
        $perPage = 10; 
        $totalPages = ceil($totalRows / $perPage);
    
        $page = $this->request->getGet('page') ?? 1;
        if ($page > $totalPages) {
            $page = $totalPages;
        }
       
    
        $offset = ($page - 1) * $perPage;
        $orders = $ordersModel->findAll($perPage, $offset);

        
        $pager = [
            'currentPage' => $page,
            'total' => $totalRows,
            'perPage' => $perPage,
            'totalPages' => $totalPages,
            'links' => []
        ];

        foreach ($orders as &$order) {
            $orderItems = $orderItemModel->where('order_id', $order['id'])->findAll();
            foreach ($orderItems as &$item) {
                $Products = new Products();
                $product = $Products->find($item['product_id']); // Mengambil data produk berdasarkan product_id
                $item['product_name'] = $product['name']; // Menambahkan nama produk ke 'orderItem'
            }
            $order['items'] = $orderItems;
        }
    
        $kipak = ['dado' => 'dado kontol'];
        $data = [
            'orders' => $orders,
            'pager' => $pager,
            'dado kontol' => $kipak
        ];
    
        return $this->response->setJSON($data);
    }
    
    
    

}