<?php

namespace App\Controllers;
use CodeIgniter\Controller;
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\TicketM;
use App\Models\PolaModel;
use App\Models\ChatModel;
use App\Models\FileModel;
use CodeIgniter\RESTful\ResourceController;

class Ticket extends BaseController
{
    protected $helpers = ['form'];
    protected $Orders;
    protected $orderItemModel;
    protected $TicketM;
    protected $PolaModel;
    protected $ChatModel;
    protected $FileModel;

    public function __construct()
    {
        
        $this->Orders = new Orders();
        $this->TicketM = new TicketM();
        $this->PolaModel = new PolaModel();
        $this->FileModel = new FileModel();
        $this->ChatModel = new ChatModel();
        $this->orderItemModel = new OrderItemModel();
        $this->ChatModel = new ChatModel();



    }

    public function list()
    {

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


    public function getData()
    {   
        $FileModel = new FileModel();
        $ticket = $FileModel->listticket();
        $result = [];
    
        foreach ($ticket as $item) {
            $result[] = [
               'date_created' => $item['date_created'],
                'client_name' => $item['client_name'],
                'kode' => $item['kode'],
                'status_id' => $item['status_id'],
                'image_url' => $item['image_url'],
            ];
        }
    
        $responseData = [
            'data' => $result
        ];
        return $this->response->setJSON($responseData);
    }

   

    public function update()
    {
        $kode = $this->request->getGet('id');
        $TicketM = new TicketM();
        $TicketData = $this->TicketM->getDataby($kode);
        $result['TicketData'] = $TicketData;
        $pola = $this->PolaModel->getItemby($TicketData['kode']);
        if (!empty($pola)) {
            foreach ($pola as $k => $v) {
                $result['ticket_item'][] = $v;
            }
        } else {
            $result['ticket_item'] = [];
        }
        $file = $this->FileModel->getItemby($TicketData['kode']);
        if (!empty($file)) {
            foreach ($file as $z => $b) {
                $result['ticket_file'][] = $b;
            }
        } else {
            $result['ticket_file'] = [];
        }

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

    }

    public function chat()
    {
        $kode = $this->request->getGet('id');
 
        $userData = session()->get();

        $chat = $this->ChatModel->getChat($kode);



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

    }

    public function sentinv()
    {
        $kode = $this->request->getPost('kode');

        if (empty($kode)) {
            return $this->fail('Kode is required');
        }

        $FileModel = new FileModel();
        $Client = new Client();
        $Orders = new Orders();
        $orderItemModel = new orderItemModel();

        // Ambil data dari filemodel berdasarkan kode
        $fileData = $FileModel->where('kode', $kode)->findAll();
        $data = [
            'status_id' => 'Sedang di produksi'
        ];
        $FileModel->where('kode', $kode);
        $updated = $FileModel->set($data)->update();        
        if (empty($fileData)) {
            return $this->failNotFound('No data found for the provided kode');
        }
        // Cek apakah $kode sudah ada di dalam Orders
        $orderData = $Orders->where('bill_no', $kode)->findAll();

        if (!empty($orderData)) {
            return $this->response->setJSON([
                'message' => 'Ticket sudah pernah dibuat, mohon cek di invoices',
                'order_id' => $kode,
                'update' => $updated

            ])->setStatusCode(500); // OK
        }
        // Ambil client_key dari data pertama (asumsi semua data memiliki client_key yang sama)
        $clientKey = $fileData[0]['client_key'];
        $clientData = $Client->where('client_key', $clientKey)->first();

        if (empty($clientData)) {
            return $this->failNotFound('Client data not found');
        }




        $orderData = [
            'bill_no' => $kode,
            'client_key' => $clientKey,
            'customer_name' => $clientData['client_name'],
            'customer_phone' => $clientData['client_phone'],
            'customer_address' => $clientData['client_address'],
            'date_time' => strtotime(date('Y-m-d h:i:s a')),
            'tanggal_order' => date('Y-m-d'), // Menggunakan format Y-m-d
            'type_produksi' => 1,
            'cat_order' => 0,
            'cat_order2' => 1,
            'net_amount' => 0,
            'gross_amount' => 0,
            'paid_status' => 1,


        ];
        $Orders->insert($orderData);
        $orderId = $Orders->getInsertID();

        // Simpan data ke tabel orders_item
        foreach ($fileData as $file) {
            $item_code = 'ITEM-' . strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 8));
            $width = $file['width'] / 100;
            $length = $file['length'] / 100;
            $orderItemData = [
                'order_id' => $orderId,
                'product_id' => $file['product_id'],
                'details' => $file['filename'],
                'image' => $file['image_url'],
                'width' => $width,
                'length' => $length,
                'pcs' => $file['qty'],
                'qty' => $file['subtotal'],
                'rate' => 0,
                'amount' => 0,
                'tipe' => 'meter',
                'item_code' => $item_code,



            ];
            $orderItemModel->insert($orderItemData);
        }

        return $this->response->setJSON([
            'message' => 'Order and items created successfully',
            'order_id' => $kode,
            'update' => $updated

        ])->setStatusCode(200); // OK
    }

    public function send_chat()
    {        
        $request = $this->request;
        $chat = $request->getPost('message');
        $ticketid = $request->getPost('kode');

        $TicketM = new TicketM();
        $cektiket = $TicketM->where('kode', $ticketid)->first();
        if (!$cektiket) {
            // Jika invoice tidak ditemukan, berikan response error
            return $this->response->setStatusCode(400)
                                  ->setJSON(['status' => 'error', 'message' => 'Ticket tidak ditemukan di database']);
        }

        $chatData = [
            'reference_id' => $ticketid,
            'sender_id' => 'Admin',
            'messages' => $chat,
            'date_sent' => date('Y-m-d H:i:s'),
            'sender' => 2,
        ];

        try {
            // Insert ke database
            $chatId = $this->ChatModel->insert($chatData);
    
            if ($chatId) {
                return $this->response->setJSON([
                    'status' => 'success',
                    'message' => 'Pesan berhasil dikirim.',
                    'data' => [
                        'chat_id' => $chatId,
                        'date_sent' => $chatData['date_sent']
                    ],
                ])->setStatusCode(200); // OK
            } else {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Gagal menyimpan pesan.',
                ])->setStatusCode(500); // Internal Server Error
            }
        } catch (\Exception $e) {
            // Tangani error jika terjadi masalah di database
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Terjadi kesalahan: ' . $e->getMessage(),

            ])->setStatusCode(500); // Internal Server Error
        }
    }
    
}