<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Store_model extends CI_Model {

    const TABLE = 'stores';

    // $user_id = NULL → admin (semua), int → filter by user
    public function get_all($user_id = NULL) {
        if ($user_id) $this->db->where('s.user_id', (int)$user_id);
        return $this->db
            ->select('s.*, u.name as owner_name')
            ->from(self::TABLE.' s')
            ->join('users u','u.id = s.user_id','left')
            ->order_by('s.id','ASC')
            ->get()->result();
    }

    public function get($id, $user_id = NULL) {
        $this->db->where('id',(int)$id);
        if ($user_id) $this->db->where('user_id',(int)$user_id);
        return $this->db->get(self::TABLE)->row();
    }

    public function get_default($user_id) {
        return $this->db
            ->where('user_id',(int)$user_id)
            ->order_by('id','ASC')
            ->limit(1)->get(self::TABLE)->row();
    }

    public function insert($data) {
        $this->db->insert(self::TABLE, $this->_filter($data));
        return $this->db->insert_id();
    }

    public function update($id, $data) {
        $this->db->where('id',(int)$id)->update(self::TABLE, $this->_filter($data));
        return $this->db->affected_rows();
    }

    public function delete($id) {
        $this->db->where('id',(int)$id)->delete(self::TABLE);
        return $this->db->affected_rows();
    }

    private function _filter($data) {
        $allowed = ['user_id','name','address','phone','footer_text'];
        return array_intersect_key($data, array_flip($allowed));
    }
}
