<?php
require_once __DIR__ . '/BaseModel.php';

/**
 * Vendor Management Class
 * Handles vendor CRUD operations and vendor-related queries
 */
class Vendor extends BaseModel {
    protected $tableName = 'vendors';
    protected $tenantColumn = null; // Vendors are shared across properties
    
    public function __construct() {
        parent::__construct();
    }
    
    /**
     * Create a new vendor
     */
    public function createVendor($data) {
        // Validate required fields
        $required = ['company_name'];
        foreach ($required as $field) {
            if (empty($data[$field])) {
                throw new Exception("Field {$field} is required");
            }
        }
        
        $vendorData = [
            'company_name' => $data['company_name'],
            'contact_person' => $data['contact_person'] ?? null,
            'phone' => $data['phone'] ?? null,
            'email' => $data['email'] ?? null,
            'service_category' => $data['service_category'] ?? null,
            'hourly_rate' => $data['hourly_rate'] ?? null,
            'tax_pin' => $data['tax_pin'] ?? null,
            'bank_details' => $data['bank_details'] ?? null,
            'rating' => 0.00,
            'status' => $data['status'] ?? 'active'
        ];
        
        return $this->create($vendorData);
    }
    
    /**
     * Update vendor
     */
    public function updateVendor($id, $data) {
        return $this->update($id, $data);
    }
    
    /**
     * Get vendor with statistics
     */
    public function getVendorDetails($id) {
        $vendor = $this->getById($id);
        
        if (!$vendor) {
            return null;
        }
        
        // Get maintenance request statistics
        $sql = "SELECT 
                    COUNT(*) as total_requests,
                    SUM(CASE WHEN status = 'Completed' THEN 1 ELSE 0 END) as completed_requests,
                    SUM(CASE WHEN status = 'In Progress' THEN 1 ELSE 0 END) as in_progress_requests,
                    AVG(final_cost) as avg_cost
                FROM maintenance_requests 
                WHERE assigned_vendor_id = ?";
        
        $result = $this->db->query($sql, [$id]);
        $stats = $result->fetch_assoc();
        
        $vendor['stats'] = $stats;
        
        return $vendor;
    }
    
    /**
     * Get vendors by service category
     */
    public function getVendorsByCategory($category) {
        $sql = "SELECT * FROM vendors WHERE service_category = ? AND status = 'active' ORDER BY rating DESC, company_name";
        $result = $this->db->query($sql, [$category]);
        $vendors = [];
        
        while ($row = $result->fetch_assoc()) {
            $vendors[] = $row;
        }
        
        return $vendors;
    }
    
    /**
     * Update vendor rating
     */
    public function updateRating($vendorId) {
        // Calculate average rating from completed maintenance requests
        $sql = "SELECT AVG(rating) as avg_rating 
                FROM maintenance_requests 
                WHERE assigned_vendor_id = ? AND status = 'Completed' AND rating IS NOT NULL";
        
        $result = $this->db->query($sql, [$vendorId]);
        $row = $result->fetch_assoc();
        
        $newRating = $row['avg_rating'] ? round($row['avg_rating'], 2) : 0.00;
        
        $this->update($vendorId, ['rating' => $newRating]);
        
        return $newRating;
    }
    
    /**
     * Blacklist vendor
     */
    public function blacklistVendor($vendorId) {
        return $this->update($vendorId, ['status' => 'blacklisted']);
    }
    
    /**
     * Activate vendor
     */
    public function activateVendor($vendorId) {
        return $this->update($vendorId, ['status' => 'active']);
    }
}
?>
