<?php
require_once '../config.php';
require_once '../lib.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $type = $_GET['type'] ?? 'coach';
        $id = $_GET['id'] ?? null;
        
        if ($type === 'coach' && $id) {
            // Get coach reviews
            $stmt = $pdo->prepare("
                SELECT 
                    cr.*,
                    u.first_name,
                    u.last_name,
                    u.email
                FROM coach_reviews cr
                JOIN users u ON cr.user_id = u.id
                WHERE cr.coach_id = ? AND cr.status = 'approved'
                ORDER BY cr.created_at DESC
            ");
            $stmt->execute([$id]);
            $reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Get average rating
            $stmt = $pdo->prepare("
                SELECT 
                    AVG(rating) as avg_rating,
                    COUNT(*) as total_reviews
                FROM coach_reviews 
                WHERE coach_id = ? AND status = 'approved'
            ");
            $stmt->execute([$id]);
            $stats = $stmt->fetch(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'reviews' => $reviews,
                'avg_rating' => round($stats['avg_rating'], 1),
                'total_reviews' => $stats['total_reviews']
            ]);
            
        } elseif ($type === 'product' && $id) {
            // Get product reviews
            $stmt = $pdo->prepare("
                SELECT 
                    pr.*,
                    u.first_name,
                    u.last_name
                FROM product_reviews pr
                JOIN users u ON pr.user_id = u.id
                WHERE pr.product_id = ? AND pr.status = 'approved'
                ORDER BY pr.created_at DESC
            ");
            $stmt->execute([$id]);
            $reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'reviews' => $reviews
            ]);
        }
        
    } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Submit review
        $input = json_decode(file_get_contents('php://input'), true);
        
        $user_id = getUserIdFromToken($_COOKIE['auth_token'] ?? $_SERVER['HTTP_AUTHORIZATION'] ?? null);
        if (!$user_id) {
            throw new Exception('Authentication required');
        }
        
        $type = $input['type'] ?? 'coach';
        $required = ['rating', 'review_text'];
        
        foreach ($required as $field) {
            if (empty($input[$field])) {
                throw new Exception("$field is required");
            }
        }
        
        if ($input['rating'] < 1 || $input['rating'] > 5) {
            throw new Exception('Rating must be between 1 and 5');
        }
        
        if ($type === 'coach') {
            $stmt = $pdo->prepare("
                INSERT INTO coach_reviews (coach_id, user_id, appointment_id, rating, review_text)
                VALUES (?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $input['coach_id'],
                $user_id,
                $input['appointment_id'] ?? null,
                $input['rating'],
                $input['review_text']
            ]);
        } elseif ($type === 'product') {
            $stmt = $pdo->prepare("
                INSERT INTO product_reviews (product_id, user_id, order_id, rating, review_text)
                VALUES (?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $input['product_id'],
                $user_id,
                $input['order_id'] ?? null,
                $input['rating'],
                $input['review_text']
            ]);
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Review submitted successfully'
        ]);
    }

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>