<?php
/**
 * ================================================================
 * ORDER RATING MODEL
 * ================================================================
 * File: app/Models/OrderRating.php
 * Handles all rating and review operations
 * ================================================================
 */

class OrderRating {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * Check if order has been rated by specific user type
     */
    public function hasRated($order_id, $rater_type) {
        $sql = "SELECT id FROM order_ratings 
                WHERE order_id = ? AND rater_type = ? 
                LIMIT 1";
        $result = $this->db->fetch($sql, [$order_id, $rater_type]);
        return !empty($result);
    }
    
    /**
     * Customer rates item and vendor
     */
    public function rateByCustomer($data) {
        $sql = "INSERT INTO order_ratings 
                (order_id, order_number, rater_type, rater_id, 
                 item_rating, item_review, vendor_rating, vendor_review, created_at)
                VALUES (?, ?, 'customer', ?, ?, ?, ?, ?, NOW())";
        
        return $this->db->execute($sql, [
            $data['order_id'],
            $data['order_number'],
            $data['customer_id'],
            $data['item_rating'],
            $data['item_review'],
            $data['vendor_rating'],
            $data['vendor_review']
        ]);
    }
    
    /**
     * Vendor rates customer
     */
    public function rateByVendor($data) {
        $sql = "INSERT INTO order_ratings 
                (order_id, order_number, rater_type, rater_id, 
                 customer_rating, customer_review, created_at)
                VALUES (?, ?, 'vendor', ?, ?, ?, NOW())";
        
        return $this->db->execute($sql, [
            $data['order_id'],
            $data['order_number'],
            $data['vendor_id'],
            $data['customer_rating'],
            $data['customer_review']
        ]);
    }
    
    /**
     * Get all ratings for an order
     */
    public function getByOrder($order_id) {
        $sql = "SELECT 
                    r.*,
                    CASE 
                        WHEN r.rater_type = 'customer' THEN CONCAT(c.first_name, ' ', c.last_name)
                        WHEN r.rater_type = 'vendor' THEN v.business_name
                    END as rater_name
                FROM order_ratings r
                LEFT JOIN customers c ON r.rater_type = 'customer' AND r.rater_id = c.id
                LEFT JOIN vendors v ON r.rater_type = 'vendor' AND r.rater_id = v.id
                WHERE r.order_id = ?
                ORDER BY r.created_at DESC";
        
        return $this->db->fetchAll($sql, [$order_id]);
    }
    
    /**
     * Get customer's rating for specific order
     */
    public function getCustomerRating($order_id) {
        $sql = "SELECT * FROM order_ratings 
                WHERE order_id = ? AND rater_type = 'customer' 
                LIMIT 1";
        return $this->db->fetch($sql, [$order_id]);
    }
    
    /**
     * Get vendor's rating for specific order
     */
    public function getVendorRating($order_id) {
        $sql = "SELECT * FROM order_ratings 
                WHERE order_id = ? AND rater_type = 'vendor' 
                LIMIT 1";
        return $this->db->fetch($sql, [$order_id]);
    }
    
    /**
     * Get average ratings for an item
     */
    public function getItemAverageRating($item_id) {
        $sql = "SELECT 
                    AVG(r.item_rating) as avg_rating,
                    COUNT(r.item_rating) as total_ratings
                FROM order_ratings r
                JOIN orders o ON r.order_id = o.id
                WHERE o.item_id = ? AND r.item_rating IS NOT NULL";
        
        $result = $this->db->fetch($sql, [$item_id]);
        return [
            'average' => round($result['avg_rating'] ?? 0, 1),
            'count' => (int)($result['total_ratings'] ?? 0)
        ];
    }
    
    /**
     * Get average ratings for a vendor
     */
    public function getVendorAverageRating($vendor_id) {
        $sql = "SELECT 
                    AVG(r.vendor_rating) as avg_rating,
                    COUNT(r.vendor_rating) as total_ratings
                FROM order_ratings r
                JOIN orders o ON r.order_id = o.id
                WHERE o.vendor_id = ? AND r.vendor_rating IS NOT NULL";
        
        $result = $this->db->fetch($sql, [$vendor_id]);
        return [
            'average' => round($result['avg_rating'] ?? 0, 1),
            'count' => (int)($result['total_ratings'] ?? 0)
        ];
    }
    
    /**
     * Get average ratings for a customer
     */
    public function getCustomerAverageRating($customer_id) {
        $sql = "SELECT 
                    AVG(r.customer_rating) as avg_rating,
                    COUNT(r.customer_rating) as total_ratings
                FROM order_ratings r
                JOIN orders o ON r.order_id = o.id
                WHERE o.customer_id = ? AND r.customer_rating IS NOT NULL";
        
        $result = $this->db->fetch($sql, [$customer_id]);
        return [
            'average' => round($result['avg_rating'] ?? 0, 1),
            'count' => (int)($result['total_ratings'] ?? 0)
        ];
    }
}