<?php
namespace Models;

class Customer {
    private $db;
    
    public function __construct($db) {
        $this->db = $db;
    }
    
    public function findAll() {
        return $this->db->exec('SELECT * FROM customers ORDER BY name');
    }
    
    public function findByCompany($companyId) {
        return $this->db->exec('SELECT * FROM customers WHERE company_id = ? ORDER BY name', [$companyId]);
    }
    
    public function findById($id) {
        $result = $this->db->exec('SELECT * FROM customers WHERE id = ?', [$id]);
        return $result ? $result[0] : null;
    }
    
    public function create($data) {
        $this->db->exec(
            'INSERT INTO customers (name, email, phone, address, company_id) VALUES (?, ?, ?, ?, ?)',
            [$data['name'], $data['email'] ?? null, $data['phone'], $data['address'] ?? null, $data['company_id']]
        );
        return $this->db->lastinsertid();
    }
    
    public function update($id, $data) {
        $sets = [];
        $params = [];
        
        foreach (['name', 'email', 'phone', 'address'] as $field) {
            if (isset($data[$field])) {
                $sets[] = "$field = ?";
                $params[] = $data[$field];
            }
        }
        
        $sets[] = "updated_at = CURRENT_TIMESTAMP";
        $params[] = $id;
        
        $this->db->exec('UPDATE customers SET ' . implode(', ', $sets) . ' WHERE id = ?', $params);
    }
    
    public function delete($id) {
        $this->db->exec('DELETE FROM customers WHERE id = ?', [$id]);
    }
    
    public function countByCompany($companyId) {
        $result = $this->db->exec('SELECT COUNT(*) as count FROM customers WHERE company_id = ?', [$companyId]);
        return $result[0]['count'];
    }
    
    public function countAll() {
        $result = $this->db->exec('SELECT COUNT(*) as count FROM customers');
        return $result[0]['count'];
    }
}
