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

class Ruta_model extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    public function getRutaConsolidado($start_date, $end_date, $user_ids = []) {
        $this->db->select('si.product_id, si.product_name, SUM(si.quantity) as total_qty')
                 ->from('sma_sales s')
                 ->join('sma_sale_items si', 'si.sale_id = s.id', 'left')
                 ->where('s.sale_status', 'completed');

        if ($start_date) {
            $this->db->where('s.date >=', $start_date . ' 00:00:00');
        }
        if ($end_date) {
            $this->db->where('s.date <=', $end_date . ' 23:59:59');
        }
        if (!empty($user_ids)) {
            $this->db->where_in('s.created_by', $user_ids);
        }

        $this->db->group_by('si.product_id, si.product_name');
        $query = $this->db->get();
        return $query->result();
    }
    public function getCustomerLocationBySale($sale_id) {
    $this->db->select('s.id as sale_id, s.customer_id, c.id as company_id, c.name, c.latitude, c.longitude');
    $this->db->from('sma_sales s');
    $this->db->join('sma_companies c', 'c.id = s.customer_id', 'left');
    $this->db->where('s.id', $sale_id); // 🔥 aquí está la clave
    $query = $this->db->get();

    if ($query->num_rows() > 0) {
        return $query->row();
    }
    return null;
}

}
