<?php
/**
 * ================================================================
 * SUBMIT RATING AJAX HANDLER
 * ================================================================
 * File: ajax/submit-rating.php
 * Handles rating submissions from customers and vendors
 * ================================================================
 */

header('Content-Type: application/json');
require_once '../app/Core/init.php';

// Check authentication
if (!Auth::check()) {
    echo json_encode(['success' => false, 'message' => 'Please login']);
    exit;
}

$user_type = Auth::userType();
$user_id = Auth::id();

// Validate user type
if (!in_array($user_type, ['customer', 'vendor'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid user type']);
    exit;
}

// Get POST data
$order_id = isset($_POST['order_id']) ? (int)$_POST['order_id'] : 0;

if ($order_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid order ID']);
    exit;
}

try {
    $orderModel = new Order();
    $ratingModel = new OrderRating();
    
    // Get order details
    $order = $orderModel->findById($order_id);
    
    if (!$order) {
        echo json_encode(['success' => false, 'message' => 'Order not found']);
        exit;
    }
    
    // Verify order is completed
    if ($order['status'] !== 'completed') {
        echo json_encode(['success' => false, 'message' => 'Only completed orders can be rated']);
        exit;
    }
    
    // Check if already rated
    if ($ratingModel->hasRated($order_id, $user_type)) {
        echo json_encode(['success' => false, 'message' => 'You have already rated this order']);
        exit;
    }
    
    // Process rating based on user type
    if ($user_type === 'customer') {
        // Verify customer owns this order
        $customerModel = new Customer();
        $customer = $customerModel->findByUserId($user_id);
        
        if (!$customer || $customer['id'] != $order['customer_id']) {
            echo json_encode(['success' => false, 'message' => 'Unauthorized']);
            exit;
        }
        
        // Validate customer ratings
        $item_rating = isset($_POST['item_rating']) ? (int)$_POST['item_rating'] : 0;
        $item_review = isset($_POST['item_review']) ? trim($_POST['item_review']) : '';
        $vendor_rating = isset($_POST['vendor_rating']) ? (int)$_POST['vendor_rating'] : 0;
        $vendor_review = isset($_POST['vendor_review']) ? trim($_POST['vendor_review']) : '';
        
        if ($item_rating < 1 || $item_rating > 5) {
            echo json_encode(['success' => false, 'message' => 'Item rating must be between 1 and 5']);
            exit;
        }
        
        if ($vendor_rating < 1 || $vendor_rating > 5) {
            echo json_encode(['success' => false, 'message' => 'Vendor rating must be between 1 and 5']);
            exit;
        }
        
        if (strlen($item_review) > 150) {
            echo json_encode(['success' => false, 'message' => 'Item review must be 150 characters or less']);
            exit;
        }
        
        if (strlen($vendor_review) > 150) {
            echo json_encode(['success' => false, 'message' => 'Vendor review must be 150 characters or less']);
            exit;
        }
        
        // Submit customer rating
        $result = $ratingModel->rateByCustomer([
            'order_id' => $order_id,
            'order_number' => $order['order_number'],
            'customer_id' => $customer['id'],
            'item_rating' => $item_rating,
            'item_review' => $item_review,
            'vendor_rating' => $vendor_rating,
            'vendor_review' => $vendor_review
        ]);
        
        if ($result) {
            echo json_encode([
                'success' => true,
                'message' => 'Thank you for your rating!'
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to submit rating']);
        }
        
    } elseif ($user_type === 'vendor') {
        // Verify vendor owns this order
        $vendorModel = new Vendor();
        $vendor = $vendorModel->findByUserId($user_id);
        
        if (!$vendor || $vendor['id'] != $order['vendor_id']) {
            echo json_encode(['success' => false, 'message' => 'Unauthorized']);
            exit;
        }
        
        // Validate vendor rating
        $customer_rating = isset($_POST['customer_rating']) ? (int)$_POST['customer_rating'] : 0;
        $customer_review = isset($_POST['customer_review']) ? trim($_POST['customer_review']) : '';
        
        if ($customer_rating < 1 || $customer_rating > 5) {
            echo json_encode(['success' => false, 'message' => 'Customer rating must be between 1 and 5']);
            exit;
        }
        
        if (strlen($customer_review) > 150) {
            echo json_encode(['success' => false, 'message' => 'Review must be 150 characters or less']);
            exit;
        }
        
        // Submit vendor rating
        $result = $ratingModel->rateByVendor([
            'order_id' => $order_id,
            'order_number' => $order['order_number'],
            'vendor_id' => $vendor['id'],
            'customer_rating' => $customer_rating,
            'customer_review' => $customer_review
        ]);
        
        if ($result) {
            echo json_encode([
                'success' => true,
                'message' => 'Rating submitted successfully!'
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to submit rating']);
        }
    }
    
} catch (Exception $e) {
    error_log("Rating submission error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred. Please try again.'
    ]);
}