<?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\Deliverytemp;
use App\Models\Delivery;
use App\Models\Deliveryitem;
use App\Models\Products;
use App\Models\Qcitem;
use App\Models\PaymentMainModel;
use App\Models\PaymentRecordsModel;
use CodeIgniter\API\ResponseTrait;

class Job extends BaseController
{   
    
    protected $helpers = ['form'];
    protected $Delivery;
    protected $Deliveryitem;
    protected $Deliverytemp;
    protected $Orders;
    protected $orderItemModel;
    use ResponseTrait;

    public function __construct()
    {
        
        $this->Orders = new Orders();
        $this->Delivery = new Delivery();
        $this->Deliveryitem = new Deliveryitem();
        $this->Deliverytemp = new Deliverytemp();
        $this->orderItemModel = new OrderItemModel();
        $this->Qcitem = new Qcitem();
        $this->session = \Config\Services::session();



    }
    public function getNow()
    {
        $userData = session()->get();
        $userId = $userData['user_id'];
        $Deliverytemp = new Deliverytemp();
        $data = $Deliverytemp->where('users_id', $userData['user_id'])->findAll();
        $responseData = [
            'data' => $data
        ];
        return $this->response->setJSON($responseData);
    }

    public function deleteItem()
    {
        $itemcode = $this->request->getPost('item_code');
        $Deliverytemp = new Deliverytemp();
        $deleted = $Deliverytemp->deleteByItemCode($itemcode);
        if ($deleted) {
            return $this->response->setJSON(['success' => true]);
        } else {
            return $this->response->setJSON(['success' => false]);
        }
    }


    public function getSuratJalan()
    {
        $suratjalan = $this->Delivery->findAll();
        
        $responseData = [
            'data' => $suratjalan
        ];
        return $this->response->setJSON($responseData);

    }
    public function saveDelivery()
    { 
        $request = $this->request;
        $userData = session()->get();
        $userId = $userData['user_id'];
        $postData = $request->getPost('data'); 
        $test = $postData['client']['client_key'];
        $items = $postData['item'];
        $item_code = 'TPDO-' . strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 5));
        $orderData = [
            'kode' => $item_code,
            'client_key' => $postData['client']['client_key'],
            'nama' => $postData['client']['customer_name'],
            'phone' => $postData['client']['customer_phone'],
            'address' => $postData['client']['customer_address'],
            'waktu_kirim' => date('Y-m-d H:i:s'),
            'jenis_kirim' => $postData['client']['jenis_kirim'],
            'notes' => $postData['client']['notes'],
        ];
    
        $orderId = $this->Delivery->insert($orderData);
    
        if ($orderId) {
            $orderItems = []; // Inisialisasi array kosong untuk menyimpan data item
            
            // Iterasi melalui setiap item
            foreach ($items as $item) {
                // Tambahkan data item ke dalam array
                $orderItems[] = [
                    'delivery_id' => $orderId,
                    'invoice' => $item['bill_no'],
                    'bahan' => $item['product_name'],
                    'file' => $item['details'],
                    'width' => $item['width'],
                    'length' => $item['length'],
                    'qty' => $item['pcs'],
                    'qty_kirim' => $item['input_value'],
                ];
            }
    
            // Insert semua data item sekaligus menggunakan insertBatch()
            $this->Deliveryitem->insertBatch($orderItems);
    
            // Hapus semua data pada tabel deliverytemp berdasarkan user_id
            $this->Deliverytemp->where('users_id', $userId)->delete();
        }
    
        return $this->respond(['message' => 'Data berhasil diterima dan diproses.'], 200);
    }
    
    public function addDelivery()
    {

      
            // Ambil data POST dari request
            $request = $this->request;

            // Ambil data POST dari request
            $postData = $request->getPost('data'); // Mengambil data dari objek 'data'
            $Deliverytemp = new Deliverytemp();

            // Periksa apakah data terkirim dengan benar
            if (!empty($postData)) {
                $userData = session()->get();
                $userId = $userData['user_id'];
            
                // Persiapkan array untuk menyimpan data yang akan dimasukkan ke dalam tabel delivery_temp
                $deliveryData = [];
            
                // Iterasi setiap data dari payload
                foreach ($postData as $data) {
                    // Periksa apakah item_code sudah ada dalam tabel delivery_temp
                    $itemCodeExists = $Deliverytemp->where('item_code', $data['item_code'])->first();
            
                    // Jika item_code tidak ditemukan, tambahkan ke dalam array $deliveryData
                    if (!$itemCodeExists) {
                        $deliveryData[] = [
                            'users_id' => $userId,
                            'item_code' => $data['item_code'],
                            'bill_no' => $data['bill_no'],
                            'tanggal_order' => $data['tanggal_order'],
                            'customer_name' => $data['customer_name'],
                            'product_name' => $data['product_name'],
                            'details' => $data['details'],
                            'width' => $data['width'],
                            'length' => $data['length'],
                            'pcs' => $data['pcs'],
                            'hasilqc' => $data['hasilqc'],
                            'kirim' => $data['input_value'] // Input_value dari payload digunakan untuk 'kirim'
                        ];
                    }
                }
            
                // Jika ada data yang akan dimasukkan, simpan menggunakan model Deliverytemp
                if (!empty($deliveryData)) {
                    $Deliverytemp->insertBatch($deliveryData);
                    return $this->respond(['message' => 'Data berhasil diterima dan diproses.'], 200);
                } else {
                    echo json_encode($deliveryData);
                    // Jika tidak ada data yang akan dimasukkan, kirim respons bahwa tidak ada data baru
                    return $this->respond(['message' => 'Tidak ada data baru yang perlu dimasukkan.'], 200);
                }
            } else {
                // Kirim respons gagal jika tidak ada data yang diterima
                return $this->fail('Tidak ada data yang diterima.', 500);
            }
            
    


    }

}