<?php
require_once __DIR__ . '/../../../../helpers/response.php';
require_once __DIR__ . '/../../../../helpers/validation.php';
require_once __DIR__ . '/../../../Middleware/AuthMiddleware.php';
require_once __DIR__ . '/../../../Models/Database.php';

class ReviewController {
    
    public function create() {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];
        
        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) $data = $_POST;
        
        $errors = validateRequired($data, ['rating']);
        if (!empty($errors)) {
            sendError('Validation failed', $errors, 422);
        }
        
        if (empty($data['maid_id']) && empty($data['vendor_id'])) {
            sendError('Validation failed', ['target' => 'Either maid_id or vendor_id must be provided.'], 422);
        }
        
        $rating = floatval($data['rating']);
        if ($rating < 1.0 || $rating > 5.0) {
            sendError('Validation failed', ['rating' => 'Rating must be between 1.0 and 5.0.'], 422);
        }
        
        $db = Database::getInstance();
        
        $maidId = !empty($data['maid_id']) ? $data['maid_id'] : null;
        $vendorId = !empty($data['vendor_id']) ? $data['vendor_id'] : null;
        
        // If maid is specified but vendor is not, lookup the maid's vendor
        if ($maidId && !$vendorId) {
            $stmt = $db->prepare("SELECT vendor_id FROM maids WHERE id = ?");
            $stmt->execute([$maidId]);
            $maid = $stmt->fetch();
            if ($maid) {
                $vendorId = $maid['vendor_id'];
            }
        }
        
        // Insert review
        $stmt = $db->prepare("
            INSERT INTO reviews (customer_id, vendor_id, maid_id, rating, comment, status) 
            VALUES (?, ?, ?, ?, ?, 'approved')
        ");
        $stmt->execute([
            $customerId,
            $vendorId,
            $maidId,
            $rating,
            !empty($data['comment']) ? htmlspecialchars($data['comment']) : null
        ]);
        
        sendResponse([], 'Review submitted successfully', 201);
    }
}
