<?php
// NewsModel: uses database if DB constants provided, otherwise falls back to data/news.json
class NewsModel {
    protected $dataPath;
    protected $useDb = false;
    protected $mysqli = null;
    public function __construct(){
        $this->dataPath = __DIR__ . '/../data/news.json';
        // Try to include site DB config (db_config.php) which may set $DB_HOST, $DB_USER, $DB_PASS, $DB_NAME or $conn
        $cfg = __DIR__ . '/../db_config.php';
        if (file_exists($cfg)) {
            @include_once $cfg;
        }
        // If a global mysqli connection $conn exists from db_config, use it
        if (!empty($conn) && $conn instanceof mysqli) {
            $this->useDb = true;
            $this->mysqli = $conn;
        } elseif (isset($DB_HOST, $DB_USER, $DB_NAME)) {
            $this->useDb = true;
            $this->mysqli = @new mysqli($DB_HOST, $DB_USER, $DB_PASS ?? '', $DB_NAME);
            if ($this->mysqli && $this->mysqli->connect_error) {
                $this->useDb = false; $this->mysqli = null;
            }
        } elseif (defined('DB_HOST') && defined('DB_USER') && defined('DB_NAME')) {
            $this->useDb = true;
            $this->mysqli = @new mysqli(DB_HOST, DB_USER, DB_PASS ?? '', DB_NAME);
            if ($this->mysqli && $this->mysqli->connect_error) {
                $this->useDb = false; $this->mysqli = null;
            }
        }
    }
    // Return full news structure
    public function all(){
        if ($this->useDb) {
            $out = ['enabled'=>false,'sales_item'=>[], 'items'=>[]];
            // Try to read meta (enabled, sales_item)
            $res = $this->mysqli->query("SELECT meta_key, meta_value FROM site_meta WHERE meta_key IN ('news_enabled','news_sales')");
            if ($res) {
                while($r = $res->fetch_assoc()){
                    $k=$r['meta_key']; $v=$r['meta_value'];
                    if($k==='news_enabled') $out['enabled']= (bool)$v;
                    elseif($k==='news_sales') $out['sales_item']= json_decode($v,true) ?: [];
                }
            }
            // If a dedicated `news` table exists, read from it
            $tbl = $this->mysqli->query("SHOW TABLES LIKE 'news'");
            if ($tbl && $tbl->num_rows > 0) {
                $items = [];
                $q = $this->mysqli->query("SELECT id,title,content,image,link,highlight,created_at FROM news ORDER BY created_at DESC");
                if ($q) {
                    while($r = $q->fetch_assoc()) {
                        $items[] = [
                            'id' => $r['id'],
                            'title' => $r['title'],
                            'content' => $r['content'],
                            'image' => $r['image'],
                            'link' => $r['link'],
                            'highlight' => !empty($r['highlight']),
                            'date' => (int)($r['created_at'] ?? 0)
                        ];
                    }
                }
                $out['items'] = $items;
                return $out;
            }
            // Fallback: read items stored as JSON in site_meta
            $res2 = $this->mysqli->query("SELECT meta_value FROM site_meta WHERE meta_key='news_items' LIMIT 1");
            if ($res2 && $row = $res2->fetch_assoc()) {
                $it = json_decode($row['meta_value'], true);
                if (is_array($it)) $out['items'] = $it;
            }
            return $out;
        }
        if (file_exists($this->dataPath)) {
            $d = @json_decode(file_get_contents($this->dataPath), true);
            if (is_array($d)) return $d;
        }
        return ['enabled'=>false,'sales_item'=>[], 'items'=>[]];
    }
    protected function saveJson($data){
        return file_put_contents($this->dataPath, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    }
    public function saveAll($data){
        if ($this->useDb) {
            // store in single meta rows (simple approach)
            $enabled = !empty($data['enabled']) ? 1 : 0;
            $sales = json_encode($data['sales_item'] ?? []);
            $items = json_encode($data['items'] ?? []);
            $this->mysqli->query("REPLACE INTO site_meta (meta_key, meta_value) VALUES ('news_enabled', '".$this->mysqli->real_escape_string($enabled)."')");
            $this->mysqli->query("REPLACE INTO site_meta (meta_key, meta_value) VALUES ('news_sales', '".$this->mysqli->real_escape_string($sales)."')");
            $this->mysqli->query("REPLACE INTO site_meta (meta_key, meta_value) VALUES ('news_items', '".$this->mysqli->real_escape_string($items)."')");
            return true;
        }
        return $this->saveJson($data);
    }
}
?>