<?php
require_once 'vendor/autoload.php';

require_once 'model/MongoDBConnection.php';
require_once 'model/ThuCung.php';
require_once 'model/HangHoa.php';
require_once 'model/DichVu.php';

require_once 'controller/JSONHelper.php';

class Bill{
    private $collection;
    private $dichVuCollection;
    private $hangHoaCollection;


    public function __construct() {
        // Lấy kết nối MongoDB
        $mongoDB = MongoDBConnection::getInstance();
        $this->collection = $mongoDB->getCollection('bill');
        $this->dichVuCollection = $mongoDB->getCollection('dich_vu');
        $this->hangHoaCollection = $mongoDB->getCollection('hang_hoa');
    }

    // Thêm bill mới
    public function addBill($data) {

        if (isset($data["san_pham"]) && !empty($data["san_pham"])){
            
            foreach ($data['san_pham'] as $san_pham){
                $san_pham->id_san_pham = new MongoDB\BSON\ObjectId($san_pham->id_san_pham);
            }
        }

        $insertResult = $this->collection->insertOne($data);
        return $insertResult->getInsertedId();
    }


    // Cập nhật bill
    public function updateBill($id, $data) {

        if (isset($data["san_pham"]) && !empty($data["san_pham"])){
            
            foreach ($data['san_pham'] as $san_pham){
                $san_pham->id_san_pham = new MongoDB\BSON\ObjectId($san_pham->id_san_pham);
            }
        }

        $updateResult = $this->collection->updateOne(
            ['_id' => new MongoDB\BSON\ObjectId($id)],
            ['$set' => $data] 
        );
        return $updateResult->getModifiedCount(); // Số bản ghi bị thay đổi
    }

    // Xoá bill
    public function deleteBill($id) {
        $deleteResult = $this->collection->deleteOne(['_id' => new MongoDB\BSON\ObjectId($id)]);
        return $deleteResult->getDeletedCount(); 
    }

    //Search tên hàng hoá và dịch vụ, nếu $onlyDichVu = true chỉ search Dich Vu
    public function searchItemBill($keyword, $onlyDichVu = false) {

        $dichVuResults = $this->dichVuCollection->find([
            'ten_dich_vu' => new MongoDB\BSON\Regex($keyword, 'i')
        ],  [
            'projection' => ['_id' => 1, 'ten_dich_vu' => 1, 'gia_dich_vu' => 1],
            'limit' => 5
        ]);

        if ($onlyDichVu){
            return JSONHelper::objectToJson([
            'dich_vu_results' =>  iterator_to_array($dichVuResults)
        ]);
        }

        $hangHoaResults = $this->hangHoaCollection->find([
            'ten_hang_hoa' => new MongoDB\BSON\Regex($keyword, 'i')
        ], [
            'projection' => ['_id' => 1, 'ten_hang_hoa' => 1, 'gia_hang_hoa' => 1],
            'limit' => 5
        ]);

        return JSONHelper::objectToJson([
            'dich_vu_results' =>  iterator_to_array($dichVuResults),
            'hang_hoa_results' =>  iterator_to_array($hangHoaResults)
        ]);
    }

    // Kiểm tra id_san_pham thuộc collection nào
    private function checkItemCollection($idSanPham) {

        // Kiểm tra trong collection 'dich_vu'
        $dichVuResult = $this->dichVuCollection->findOne([
            '_id' => new MongoDB\BSON\ObjectId($idSanPham)
        ]);

        if ($dichVuResult) {
            return "dich_vu"; // Thuộc collection dich_vu
        
        
        }
        // Kiểm tra trong collection 'hang_hoa'
        $hangHoaResult = $this->hangHoaCollection->findOne([
            '_id' => new MongoDB\BSON\ObjectId($idSanPham)
        ]);

        if ($hangHoaResult) {
            return "hang_hoa"; // Thuộc collection hang_hoa
        }

        return null; // Không tìm thấy trong cả hai collection
    }

    // Hàm Lấy bill 
    public function getBill($id, $trongLuong = 0, $isFrontEnd = false){
        
        $id = new MongoDB\BSON\ObjectId($id);
        $cursor = $this->collection->findOne(['_id' => $id]);

        $tmp =  iterator_to_array($cursor);

        $result = new stdClass();

        $result->_id = $tmp["_id"];

        $result->san_pham = [];
        //Lấy từng giá trị trong mảng san_pham
        if (isset($tmp["san_pham"])){
            foreach ($tmp["san_pham"] as $key => $item){
                if ($this->checkItemCollection($item["id_san_pham"])=="hang_hoa"){
                    $hangHoa = new HangHoa();
                    $tmp = $hangHoa->getHangHoa($item["id_san_pham"]);
                    
                    $result->san_pham[$key]["ten_hang_hoa"] = $tmp[0]->ten_hang_hoa;
                    $result->san_pham[$key]["gia_hang_hoa"] = $tmp[0]->gia_hang_hoa;
                    $result->san_pham[$key]["don_vi"] = $tmp[0]->don_vi;
                    $result->san_pham[$key]["cach_dung"] = $tmp[0]->cach_dung;
    
                    $result->san_pham[$key]["so_luong"] = $item["so_luong"];

                } elseif ($this->checkItemCollection($item["id_san_pham"])=="dich_vu") {
                    
                    $dichvu = new DichVu();
                    $result->san_pham[$key]["dich_vu"] = $dichvu->getDichVu($item["id_san_pham"]);

                } else {
                    continue;
                }
            }
        }

        if ($isFrontEnd){
            return JSONHelper::objectToJson($result);
        } else {
            return($result);
        }
    }

    // Tính tổng tiền bill 
    public function getPriceBill($id){
        $id = new MongoDB\BSON\ObjectId($id);
        $cursor = $this->collection->findOne(['_id' => $id]);

        $tmp =  iterator_to_array($cursor);

        $priceBill = 0;
        if (isset($tmp["san_pham"])){
            foreach ($tmp["san_pham"] as $key => $item){
                if ($this->checkItemCollection($item["id_san_pham"])=="hang_hoa"){
                    $hangHoa = new HangHoa();
                    $objHangHoa = $hangHoa->getHangHoa($item["id_san_pham"]);

                    $priceBill += $item["so_luong"] * $objHangHoa[0]->gia_hang_hoa;
                } elseif ($this->checkItemCollection($item["id_san_pham"])=="dich_vu") {
                    
                    $dichvu = new DichVu();
                    $objDichVu = $dichvu->getDichVu($item["id_san_pham"]);

                    $priceBill += $objDichVu->gia_dich_vu;

                } else {
                    continue;
                }
            }
        }

        return $priceBill;
    }
}

?>