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

class Stock extends BaseController
{   
    protected $helpers = ['form'];
    protected $Orders;
    protected $StockIn;
    protected $Opname;
    protected $Products;
    protected $orderItemModel;
    use ResponseTrait;

    public function __construct()
    {
        
        $this->StockIn = new StockIn();
        $this->Opname = new Opname();
        $this->Products = new Products();
        $this->orderItemModel = new OrderItemModel();
        $this->Qcitem = new Qcitem();
        $this->session = \Config\Services::session();
    }

    public function index()
    {
        return view('templates/v2/header')
        .view('Stock/index')
        .view('templates/v2/footer');

    }

    public function getStockindata()
    {
        $stockIn = $this->StockIn->findAll();
        $result = [];
    
        foreach ($stockIn as $item) {
            $productId = $item['product_id'];
            $name = $this->Products->find($productId)['name'];
            $tanggal = date('Y-m-d H:i:s', $item['date_time']); 
            $result[] = [
                'name' => $name,
                'qty' => $item['qty'],
                'tanggal' => $tanggal,
                'approval' => $item['approval'],
            ];
        }
    
        $responseData = [
            'data' => $result
        ];
        return $this->response->setJSON($responseData);
    }
    
    public function generatedata()
    {
            $ordersItems = $this->orderItemModel->findAll();
            $stockIns = $this->StockIn->findAll();
            $stockopname = $this->Opname->findAll();

           $opnamedata = [];
            foreach ($stockopname as $opname) {
                $productId = $opname['product_id'];
                $qty = intval($opname['qty']); // Mengonversi nilai qty ke integer
                if (!isset($opnamedata[$productId])) {
                    $opnamedata[$productId] = 0;
                }
                $opnamedata[$productId] += $qty;
            }

            $stockQty = [];
            foreach ($stockIns as $stockIn) {
                $productId = $stockIn['product_id'];
                $qty = intval($stockIn['qty']); // Mengonversi nilai qty ke integer
                if (!isset($stockQty[$productId])) {
                    $stockQty[$productId] = 0;
                }
                $stockQty[$productId] += $qty;
            }

            // Buat array untuk menyimpan total totalqc berdasarkan product_id
            $totalQc = [];
            // Menghitung total totalqc berdasarkan product_id
            foreach ($ordersItems as $orderItem) {
                $productId = $orderItem['product_id'];
                $totalqc = $orderItem['totalqc'];
                if (!isset($totalQc[$productId])) {
                    $totalQc[$productId] = 0;
                }
                $totalQc[$productId] += $totalqc;
            }
            // Buat array untuk menyimpan hasil perhitungan
            $result = [];
            // Menghitung selisih antara total stockin qty dan total totalqc
            foreach ($stockQty as $productId => $qty) {
                $name = $this->Products->find($productId)['name']; // Ambil nama produk dari model products
                $availability = $this->Products->find($productId)['availability']; // Ambil nama produk dari model products
                $image = $this->Products->find($productId)['image']; // Ambil nama produk dari model products
                $diff = $qty - (isset($totalQc[$productId]) ? $totalQc[$productId] : 0) + (isset($opnamedata[$productId]) ? $opnamedata[$productId] : 0);
                
                $roundedDiff = round($diff);
                $result[] = [
                    'name' => $name,
                    'product_id' => $productId,
                    'stock_diff' => $roundedDiff,
                    'image' => $image,
                    'availability' => $availability,
                ];
            }

            $responseData = [
                'data' => $result
            ];
            return $this->response->setJSON($responseData);        
    }
    public function history()
    {
        $result = [];
    
        // Mendapatkan data produk
        $Products = new Products();
        $data = $Products->getall();
        $query['product'] = json_decode(json_encode($data), true);
    
        $history_data = $this->Qcitem->findAll();
        foreach ($history_data as $qcitem) {
            // Konversi date_time ke format yyyy-mm-dd his
            $qcitem['date_time'] = date('Y-m-d H:i:s', $qcitem['date_time']);
    
            $item_code = $qcitem['item_code'];
            $details = $this->orderItemModel->getItemByItemCode($item_code);
            $qcitem['details'] = $details;
    
            // Ambil nama file dari details
            $fileName = isset($details[0]['details']) ? $details[0]['details'] : '';
    
            // Ambil hasilqc pada history_data
            $hasilqc = intval($qcitem['hasilqc']);
    
            // Ambil length dari details
            $length = isset($details[0]['length']) ? floatval($details[0]['length']) : 0;
    
            // Hitung qty dikali length
            $qty_times_length = $hasilqc * $length;
    
            // Ambil name dari produk berdasarkan product_id
            $productId = isset($details[0]['product_id']) ? $details[0]['product_id'] : '';
            $productName = '';
            foreach ($query['product'] as $product) {
                if ($product['id'] == $productId) {
                    $productName = $product['name'];
                    break;
                }
            }
    
            // Buat objek baru untuk hasil akhir
            $finalResult = [
                'date_time' => $qcitem['date_time'],
                'file_name' => $fileName,
                'qty_times_length' => $qty_times_length,
                'product_name' => $productName // Menambahkan nama produk
            ];
    
            $result['data'][] = $finalResult;
        }
    
        return $this->response->setJSON($result);
    }
    
    
    public function addstock()
    {
        $request = $this->request;
        $postData = $request->getPost(); 
        $saveData = [
            'product_id' => $postData['data']['products'],
            'qty' => $postData['data']['qty'],
            'approval' => $postData['data']['approval'],
            'date_time' => strtotime(date('Y-m-d h:i:s a')),
        ];

        $stockid = $this->StockIn->addstock($saveData);

        return $this->respond(['message' => 'Data berhasil diterima dan diproses.'], 200);
    }

    public function addopname()
    {
        $request = $this->request;
        // Mendapatkan data dari form input
        $productIds = $request->getPost('product_id');
        $qtys = $request->getPost('pcs');
        $detailsArray = $request->getPost('details');
        $dateTime = strtotime(date('Y-m-d h:i:s a'));
        $guid = 'opname-' . strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 5));
        $userId = $this->session->get('user_id');

        // Memastikan bahwa semua input adalah array dan memiliki panjang yang sama
        if (is_array($productIds) && is_array($qtys) && is_array($detailsArray) && count($productIds) === count($qtys) && count($qtys) === count($detailsArray)) {
            $saveData = [];
    
            // Iterasi melalui setiap input untuk memproses data
            for ($i = 0; $i < count($productIds); $i++) {
                $productId = $productIds[$i];
                $qty = floatval($qtys[$i]);
                $details = $detailsArray[$i];
    
                $totalBarangKeluar = $this->orderItemModel->getTotalBarangKeluar($productId);
                $totalBarangMasuk = $this->StockIn->getTotalBarangMasuk($productId);
                $totalOpname = $this->Opname->getTotalOpname($productId);
                $currentstock = $totalBarangMasuk - $totalBarangKeluar + $totalOpname;
                $roundedCurrentStock = round($currentstock); 
                $stokTerbaru = $qty - $roundedCurrentStock;
    
                $saveData[] = [
                    'product_id' => $productId,
                    'guid' => $guid,
                    'stock' => $qty,
                    'keterangan' => $details,
                    'created_date' => $dateTime,
                    'qty' => $stokTerbaru,
                    'users_id' => $userId,
                    'status' => 'Berhasil',
                ];
            }
            
            $this->Opname->insertBatch($saveData);

            return $this->response->setJSON($saveData);
        } else {
            // Mengembalikan respons error jika input tidak valid
            return $this->response->setJSON(['error' => 'Invalid input data']);
        }
    }


    public function getOpname()
    {
        $Opname = $this->Opname->findAll();
        $result = [];
    
        foreach ($Opname as $item) {
            $productId = $item['product_id'];
            $name = $this->Products->find($productId)['name'];
            $tanggal = date('Y-m-d H:i:s', $item['created_date']); 
            $result[] = [
                'name' => $name,
                'qty' => $item['qty'],
                'stock' => $item['stock'],
                'tanggal' => $tanggal,
            ];
        }
    
        $responseData = [
            'data' => $result
        ];
        return $this->response->setJSON($responseData);
    }
    
    public function create()
    {
        return view('templates/v2/header')
        .view('Stock/create')
        .view('templates/v2/footer');
    }
}