<?php
namespace Models;

class Company {
    private $db;
    
    public function __construct($db) {
        $this->db = $db;
    }
    
    public function findAll() {
        return $this->db->exec('SELECT * FROM companies ORDER BY name');
    }
    
    public function findById($id) {
        $result = $this->db->exec('SELECT * FROM companies WHERE id = ?', [$id]);
        return $result ? $result[0] : null;
    }
    
    public function create($data) {
        $this->db->exec(
            'INSERT INTO companies (name, email, phone, address, is_active) VALUES (?, ?, ?, ?, ?)',
            [$data['name'], $data['email'] ?? null, $data['phone'] ?? null, $data['address'] ?? null, true]
        );
        return $this->db->lastinsertid();
    }
    
    public function update($id, $data) {
        $sets = [];
        $params = [];
        
        $allowedFields = ['name', 'email', 'phone', 'address', 'is_active', 'joined_date', 'subscription_expiry', 'subscription_plan', 'subscription_status'];
        
        foreach ($allowedFields as $field) {
            if (array_key_exists($field, $data)) {
                $sets[] = "$field = ?";
                $params[] = $data[$field];
            }
        }
        
        if (empty($sets)) {
            return;
        }
        
        $sets[] = "updated_at = CURRENT_TIMESTAMP";
        $params[] = $id;
        
        $this->db->exec('UPDATE companies SET ' . implode(', ', $sets) . ' WHERE id = ?', $params);
    }
    
    public function delete($id) {
        $this->db->exec('DELETE FROM activity_logs WHERE user_id IN (SELECT id FROM users WHERE company_id = ?)', [$id]);
        
        $this->db->exec('DELETE FROM reminders WHERE service_id IN (SELECT s.id FROM services s INNER JOIN vehicles v ON s.vehicle_id = v.id INNER JOIN customers c ON v.customer_id = c.id WHERE c.company_id = ?)', [$id]);
        
        $this->db->exec('DELETE FROM services WHERE vehicle_id IN (SELECT v.id FROM vehicles v INNER JOIN customers c ON v.customer_id = c.id WHERE c.company_id = ?)', [$id]);
        
        $this->db->exec('DELETE FROM vehicles WHERE customer_id IN (SELECT id FROM customers WHERE company_id = ?)', [$id]);
        
        $this->db->exec('DELETE FROM customers WHERE company_id = ?', [$id]);
        
        $this->db->exec('DELETE FROM users WHERE company_id = ?', [$id]);
        
        $this->db->exec('DELETE FROM companies WHERE id = ?', [$id]);
    }
    
    public function countAll() {
        $result = $this->db->exec('SELECT COUNT(*) as count FROM companies');
        return $result[0]['count'];
    }
    
    public function getStats($id) {
        $customers = $this->db->exec('SELECT COUNT(*) as count FROM customers WHERE company_id = ?', [$id]);
        $vehicles = $this->db->exec('SELECT COUNT(*) as count FROM vehicles v INNER JOIN customers c ON v.customer_id = c.id WHERE c.company_id = ?', [$id]);
        $staff = $this->db->exec('SELECT COUNT(*) as count FROM users WHERE company_id = ?', [$id]);
        
        return [
            'customers' => $customers[0]['count'],
            'vehicles' => $vehicles[0]['count'],
            'staff' => $staff[0]['count']
        ];
    }
}
