<?php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../middleware/auth.php';

$database = new Database();
$db = $database->getConnection();

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        // Get all reviews for admin (pending and approved)
        $user = requireAdmin();
        
        try {
            $status = $_GET['status'] ?? 'all'; // all, pending, approved
            $limit = $_GET['limit'] ?? 20;
            $offset = $_GET['offset'] ?? 0;

            $whereClause = '';
            if ($status === 'pending') {
                $whereClause = 'WHERE r.is_approved = 0';
            } elseif ($status === 'approved') {
                $whereClause = 'WHERE r.is_approved = 1';
            }

            $stmt = $db->prepare("
                SELECT 
                    r.*,
                    u.name as user_name,
                    u.email as user_email,
                    p.name as product_name,
                    p.brand as product_brand
                FROM reviews r
                JOIN users u ON r.user_id = u.id
                JOIN products p ON r.product_id = p.id
                $whereClause
                ORDER BY r.created_at DESC
                LIMIT :limit OFFSET :offset
            ");
            $stmt->bindValue(':limit', (int)$limit, PDO::PARAM_INT);
            $stmt->bindValue(':offset', (int)$offset, PDO::PARAM_INT);
            $stmt->execute();
            
            $reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Get media for each review
            foreach ($reviews as &$review) {
                $mediaStmt = $db->prepare("
                    SELECT media_type, file_name, file_path, file_size, position
                    FROM review_media 
                    WHERE review_id = :review_id 
                    ORDER BY position ASC
                ");
                $mediaStmt->bindParam(':review_id', $review['id'], PDO::PARAM_STR);
                $mediaStmt->execute();
                
                $review['media'] = $mediaStmt->fetchAll(PDO::FETCH_ASSOC);
            }

            http_response_code(200);
            echo json_encode([
                'success' => true,
                'reviews' => $reviews
            ]);

        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode([
                'success' => false,
                'message' => 'Internal Server Error: ' . $e->getMessage()
            ]);
        }
        break;

    case 'PUT':
        // Approve/Reject review(s)
        $user = requireAdmin();
        
        try {
            $data = json_decode(file_get_contents("php://input"), true);
            
            // Handle bulk actions
            if (isset($data['action']) && $data['action'] === 'bulk') {
                $operation = $data['operation'] ?? null;
                $reviewIds = $data['review_ids'] ?? [];
                
                if (empty($reviewIds) || !$operation) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'Review IDs and operation are required for bulk action']);
                    exit;
                }

                $placeholders = str_repeat('?,', count($reviewIds) - 1) . '?';
                
                if ($operation === 'approve') {
                    $stmt = $db->prepare("UPDATE reviews SET is_approved = 1 WHERE id IN ($placeholders)");
                } elseif ($operation === 'reject') {
                    $stmt = $db->prepare("UPDATE reviews SET is_approved = 0 WHERE id IN ($placeholders)");
                } elseif ($operation === 'delete') {
                    $stmt = $db->prepare("DELETE FROM reviews WHERE id IN ($placeholders)");
                } else {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'Invalid operation']);
                    exit;
                }

                $stmt->execute($reviewIds);

                if ($stmt->rowCount() > 0) {
                    http_response_code(200);
                    echo json_encode([
                        'success' => true,
                        'message' => count($reviewIds) . ' reviews ' . $operation . 'd successfully'
                    ]);
                } else {
                    http_response_code(404);
                    echo json_encode(['success' => false, 'message' => 'No reviews were affected']);
                }
                exit;
            }

            // Handle single review action
            $reviewId = $_GET['id'] ?? null;
            $action = $data['action'] ?? null; // approve, reject

            if (!$reviewId || !$action) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Review ID and action are required']);
                exit;
            }

            if ($action === 'approve') {
                $stmt = $db->prepare("UPDATE reviews SET is_approved = 1 WHERE id = :id");
            } elseif ($action === 'reject') {
                $stmt = $db->prepare("UPDATE reviews SET is_approved = 0 WHERE id = :id");
            } else {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Invalid action']);
                exit;
            }

            $stmt->bindParam(':id', $reviewId, PDO::PARAM_STR);
            $stmt->execute();

            if ($stmt->rowCount() > 0) {
                http_response_code(200);
                echo json_encode([
                    'success' => true,
                    'message' => 'Review ' . ($action === 'approve' ? 'approved' : 'rejected') . ' successfully'
                ]);
            } else {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Review not found']);
            }

        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode([
                'success' => false,
                'message' => 'Internal Server Error: ' . $e->getMessage()
            ]);
        }
        break;

    case 'DELETE':
        // Delete review
        $user = requireAdmin();
        
        try {
            $reviewId = $_GET['id'] ?? null;

            if (!$reviewId) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Review ID is required']);
                exit;
            }

            // Delete review (cascade will delete media)
            $stmt = $db->prepare("DELETE FROM reviews WHERE id = :id");
            $stmt->bindParam(':id', $reviewId, PDO::PARAM_STR);
            $stmt->execute();

            if ($stmt->rowCount() > 0) {
                http_response_code(200);
                echo json_encode([
                    'success' => true,
                    'message' => 'Review deleted successfully'
                ]);
            } else {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Review not found']);
            }

        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode([
                'success' => false,
                'message' => 'Internal Server Error: ' . $e->getMessage()
            ]);
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
        break;
}
?>