<?php
require_once __DIR__ . '/../config/Database.php';

class Kos {
    private $db;

    public function __construct() {
        $database = new Database();
        $this->db = $database->connect();
    }

    public function getAllKos($search = '') {
        $kos_list = [];
        $query = "SELECT k.*, (
                    SELECT kg.nama_file
                    FROM kos_gambar kg
                    WHERE kg.kos_id = k.id
                    ORDER BY kg.urutan ASC
                    LIMIT 1
                ) AS gambar_utama
                FROM kos k";

        if (!empty($search)) {
            $query .= " WHERE MATCH(k.nama, k.lokasi) AGAINST(? IN BOOLEAN MODE)";
            $stmt = $this->db->prepare($query);
            $search_term = "$search*";
            $stmt->bind_param("s", $search_term);
        } else {
            $stmt = $this->db->prepare($query);
        }

        $stmt->execute();
        $result = $stmt->get_result();

        while ($row = $result->fetch_assoc()) {
            $kos_list[] = $row;
        }

        $stmt->close();
        return $kos_list;
    }

    public function getKosByKampus($kampus, $search = '') {
        $kos_list = [];
        $query = "SELECT k.*, (
                    SELECT kg.nama_file
                    FROM kos_gambar kg
                    WHERE kg.kos_id = k.id
                    ORDER BY kg.urutan ASC
                    LIMIT 1
                ) AS gambar_utama
                FROM kos k
                WHERE k.lokasi LIKE ?";

        if (!empty($search)) {
            $query .= " AND MATCH(k.nama, k.lokasi) AGAINST(? IN BOOLEAN MODE)";
            $stmt = $this->db->prepare($query);
            $lokasi_like = "%$kampus%";
            $search_term = "$search*";
            $stmt->bind_param("ss", $lokasi_like, $search_term);
        } else {
            $stmt = $this->db->prepare($query);
            $lokasi_like = "%$kampus%";
            $stmt->bind_param("s", $lokasi_like);
        }

        $stmt->execute();
        $result = $stmt->get_result();

        while ($row = $result->fetch_assoc()) {
            $kos_list[] = $row;
        }

        $stmt->close();
        return $kos_list;
    }

    public function getKosById($id) {
        $kos = null;
        $stmt = $this->db->prepare("SELECT * FROM kos WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        $kos = $result->fetch_assoc();
        $stmt->close();

        if ($kos) {
            $stmt_gambar = $this->db->prepare("SELECT nama_file FROM kos_gambar WHERE kos_id = ? ORDER BY urutan ASC");
            $stmt_gambar->bind_param("i", $id);
            $stmt_gambar->execute();
            $result_gambar = $stmt_gambar->get_result();

            $gambar_files = [];
            while ($row_gambar = $result_gambar->fetch_assoc()) {
                $gambar_files[] = $row_gambar['nama_file'];
            }
            $stmt_gambar->close();

            if (empty($gambar_files)) {
                $kos['gambar_detail'] = ['default.jpg']; 
            } else {
                $kos['gambar_detail'] = $gambar_files;
            }
        }

        return $kos ?: null;
    }

    public function addKos($data) {
        $this->db->begin_transaction();

        try {
            $stmt = $this->db->prepare(
                "INSERT INTO kos (nama, lokasi, kategori, rating, harga, deskripsi)
                 VALUES (?, ?, ?, ?, ?, ?)"
            );
            $stmt->bind_param(
                "sssdds",
                $data['nama'],
                $data['lokasi'],
                $data['kategori'],
                $data['rating'],
                $data['harga'],
                $data['deskripsi']
            );
            $stmt->execute();
            $kos_id = $this->db->insert_id;
            $stmt->close();

            if (!empty($data['gambar_files']) && is_array($data['gambar_files'])) {
                $stmt_gambar = $this->db->prepare(
                    "INSERT INTO kos_gambar (kos_id, urutan, nama_file) VALUES (?, ?, ?)"
                );
                
                foreach ($data['gambar_files'] as $index => $gambar_file) {
                    $urutan = $index + 1;
                    $stmt_gambar->bind_param("iis", $kos_id, $urutan, $gambar_file);
                    $stmt_gambar->execute();
                }
                $stmt_gambar->close();
            }

            $this->db->commit();
            return $kos_id;
        } catch (Exception $e) {
            $this->db->rollback();
            error_log("Error adding kos: " . $e->getMessage());
            return false;
        }
    }

    public static function formatRupiah($angka) {
        return "Rp" . number_format($angka, 0, ',', '.');
    }
}
