<?php
// Customer Reviews Page - Fixed Version
session_start();
require_once '../app/Core/init.php';

// Check if user is logged in and is a customer
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_type']) || $_SESSION['user_type'] !== 'customer') {
    header('Location: ../index.php');
    exit();
}

// Page variables
$page_title = "Reviews";
$active_menu = "reviews";

try {
    $customerModel = new Customer();
    $reviewModel = new Review();
    $orderModel = new Order();
    
    // Get current customer
    $customer = $customerModel->findByUserId($_SESSION['user_id']);
    if (!$customer) {
        throw new Exception('Customer not found');
    }
    
    $customer_id = $customer['id'];
    
    // Handle review submission (simplified)
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_review'])) {
        $order_id = (int)$_POST['order_id'];
        $rating = (int)$_POST['rating'];
        $review_text = trim($_POST['review']);
        
        // Validate
        $errors = [];
        if ($order_id <= 0) $errors[] = 'Invalid order';
        if ($rating < 1 || $rating > 5) $errors[] = 'Rating must be between 1 and 5';
        if (empty($review_text)) $errors[] = 'Review text is required';
        
        // Check if customer already reviewed this order
        if ($reviewModel->hasCustomerReviewedOrder($customer_id, $order_id)) {
            $errors[] = 'You have already reviewed this order';
        }
        
        if (empty($errors)) {
            // Get order details
            $db = Database::getInstance();
            $order_sql = "SELECT * FROM orders WHERE id = ? AND customer_id = ? LIMIT 1";
            $order_details = $db->fetch($order_sql, [$order_id, $customer_id]);
            
            if ($order_details) {
                $review_data = [
                    'customer_id' => $customer_id,
                    'order_id' => $order_id,
                    'item_id' => $order_details['item_id'],
                    'vendor_id' => $order_details['vendor_id'],
                    'rating' => $rating,
                    'review' => $review_text
                ];
                
                $review_id = $reviewModel->create($review_data);
                
                if ($review_id) {
                    $_SESSION['success'] = 'Review submitted successfully!';
                    header('Location: reviews.php');
                    exit();
                } else {
                    $errors[] = 'Failed to submit review. Please try again.';
                }
            } else {
                $errors[] = 'Invalid order or unauthorized access';
            }
        }
        
        if (!empty($errors)) {
            $_SESSION['error'] = implode('<br>', $errors);
        }
    }
    
    // Get customer reviews with pagination
    $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
    $limit = 10;
    $offset = ($page - 1) * $limit;
    
    $reviews = $reviewModel->getCustomerReviews($customer_id, $limit, $offset);
    $total_reviews = $reviewModel->count(['customer_id' => $customer_id]);
    $total_pages = ceil($total_reviews / $limit);
    
    // Get customer review statistics
    $stats = $reviewModel->getCustomerStats($customer_id);
    
    // Calculate percentages and add user-friendly keys
    $total_reviews_count = $stats['total_reviews'] ?? 0;
    
    if ($total_reviews_count > 0) {
        $stats['five_star_percentage'] = round(($stats['five_star'] ?? 0) / $total_reviews_count * 100, 1);
        $stats['four_star_percentage'] = round(($stats['four_star'] ?? 0) / $total_reviews_count * 100, 1);
        $stats['three_star_percentage'] = round(($stats['three_star'] ?? 0) / $total_reviews_count * 100, 1);
        $stats['two_star_percentage'] = round(($stats['two_star'] ?? 0) / $total_reviews_count * 100, 1);
        $stats['one_star_percentage'] = round(($stats['one_star'] ?? 0) / $total_reviews_count * 100, 1);
    } else {
        $stats['five_star_percentage'] = 0;
        $stats['four_star_percentage'] = 0;
        $stats['three_star_percentage'] = 0;
        $stats['two_star_percentage'] = 0;
        $stats['one_star_percentage'] = 0;
    }
    
    // Add review counts with user-friendly keys
    $stats['five_star_reviews'] = $stats['five_star'] ?? 0;
    $stats['four_star_reviews'] = $stats['four_star'] ?? 0;
    $stats['three_star_reviews'] = $stats['three_star'] ?? 0;
    $stats['two_star_reviews'] = $stats['two_star'] ?? 0;
    $stats['one_star_reviews'] = $stats['one_star'] ?? 0;
    
    // Get unreviewed orders
    $unreviewed_orders = $reviewModel->getUnreviewedOrders($customer_id);
    
    // Handle filter
    $filter = isset($_GET['filter']) ? $_GET['filter'] : 'all';
    if ($filter !== 'all') {
        $filtered_reviews = [];
        foreach ($reviews as $review_item) {
            if ($filter == '5' && $review_item['rating'] == 5) {
                $filtered_reviews[] = $review_item;
            } elseif ($filter == '4' && $review_item['rating'] == 4) {
                $filtered_reviews[] = $review_item;
            } elseif ($filter == '3' && $review_item['rating'] == 3) {
                $filtered_reviews[] = $review_item;
            } elseif ($filter == '2' && $review_item['rating'] == 2) {
                $filtered_reviews[] = $review_item;
            } elseif ($filter == '1' && $review_item['rating'] == 1) {
                $filtered_reviews[] = $review_item;
            }
        }
        $reviews = $filtered_reviews;
    }
    
} catch (Exception $e) {
    $_SESSION['error'] = 'Error: ' . $e->getMessage();
    $reviews = [];
    $stats = ['total_reviews' => 0, 'average_rating' => 0];
    $unreviewed_orders = [];
    $total_pages = 1;
}

// Helper function to render stars
function renderStars($rating) {
    $html = '<div class="d-flex align-items-center text-primary rating-stars">';
    for ($i = 1; $i <= 5; $i++) {
        if ($i <= $rating) {
            $html .= '<i class="fas fa-star text-warning"></i>';
        } else {
            $html .= '<i class="far fa-star text-muted"></i>';
        }
    }
    $html .= '</div>';
    return $html;
}

// Helper function to format date
function formatDate($date) {
    return date('M d, Y', strtotime($date));
}

include '../templates/layouts/customer/head.php';
?>

<body class="fixed sidebar-mini">
    <div class="wrapper">
        <!-- Sidebar -->
        <nav class="sidebar">
            <div class="sidebar-header">
                <?php include '../templates/layouts/customer/navbar.php'; ?>
            </div>
        </nav>

        <!-- Page Content -->
        <div class="content-wrapper">
            <div class="main-content">
                <!-- Navbar -->
                <?php include '../templates/layouts/customer/header.php'; ?>
                
                <!-- Display Messages -->
                <?php if (isset($_SESSION['success'])): ?>
                    <div class="alert alert-success alert-dismissible fade show m-3" role="alert">
                        <?= $_SESSION['success']; unset($_SESSION['success']); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                
                <?php if (isset($_SESSION['error'])): ?>
                    <div class="alert alert-danger alert-dismissible fade show m-3" role="alert">
                        <?= $_SESSION['error']; unset($_SESSION['error']); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <div class="body-content">
                    <div class="container-xxl">
                        <div class="card">
                            <div class="card-header position-relative d-flex justify-content-between align-items-center">
                                <h6 class="fs-17 fw-semi-bold my-1">My Reviews</h6>
                                <?php if (!empty($unreviewed_orders)): ?>
                                <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#writeReviewModal">
                                    <i class="fas fa-plus me-1"></i>Write Review
                                </button>
                                <?php endif; ?>
                            </div>
                            <div class="card-body">
                                <!-- Review Statistics -->
                                <div class="mb-4">
                                    <div class="border p-4 mb-5 rounded-4">
                                        <div class="row g-4 align-items-center">
                                            <div class="col-sm-auto">
                                                <div class="text-center">
                                                    <h6 class="mb-4">Your Average Rating</h6>
                                                    <div class="rating-point position-relative ml-auto mr-auto">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="120" height="120" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width=".5" stroke-linecap="round" stroke-linejoin="round" class="feather feather-star text-primary">
                                                            <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
                                                        </svg>
                                                        <h3 class="position-absolute mb-0 fs-18 text-primary"><?= number_format($stats['average_rating'] ?? 0, 1) ?></h3>
                                                    </div>
                                                    <span class="fs-13"><?= number_format($stats['total_reviews']) ?> Total Reviews</span>
                                                </div>
                                            </div>
                                            <div class="col">
                                                <div class="rating-position">
                                                    <h6 class="mb-4">Your Rating Breakdown</h6>
                                                    
                                                    <!-- 5 Star -->
                                                    <div class="align-items-center d-flex mb-2 rating-dimension gap-2">
                                                        <div class="d-flex align-items-center gap-2">
                                                            <span class="fs-14 fw-semibold rating-points">5</span>
                                                            <div class="d-flex align-items-center text-warning">
                                                                <i class="fas fa-star"></i>
                                                                <i class="fas fa-star"></i>
                                                                <i class="fas fa-star"></i>
                                                                <i class="fas fa-star"></i>
                                                                <i class="fas fa-star"></i>
                                                            </div>
                                                        </div>
                                                        <div class="progress flex-grow-1 me-2">
                                                            <div class="progress-bar bg-warning" role="progressbar" style="width: <?= $stats['five_star_percentage'] ?? 0 ?>%" aria-valuenow="<?= $stats['five_star_percentage'] ?? 0 ?>" aria-valuemin="0" aria-valuemax="100"></div>
                                                        </div>
                                                        <div class="bg-dark fs-11 fw-medium px-2 py-1 rounded-pill text-white user-rating"><?= $stats['five_star_reviews'] ?? 0 ?></div>
                                                    </div>
                                                    
                                                    <!-- 4 Star -->
                                                    <div class="align-items-center d-flex mb-2 rating-dimension gap-2">
                                                        <div class="d-flex align-items-center gap-2">
                                                            <span class="fs-14 fw-semibold rating-points">4</span>
                                                            <div class="d-flex align-items-center text-warning">
                                                                <i class="fas fa-star"></i>
                                                                <i class="fas fa-star"></i>
                                                                <i class="fas fa-star"></i>
                                                                <i class="fas fa-star"></i>
                                                                <i class="far fa-star"></i>
                                                            </div>
                                                        </div>
                                                        <div class="progress flex-grow-1 me-2">
                                                            <div class="progress-bar bg-success" role="progressbar" style="width: <?= $stats['four_star_percentage'] ?? 0 ?>%" aria-valuenow="<?= $stats['four_star_percentage'] ?? 0 ?>" aria-valuemin="0" aria-valuemax="100"></div>
                                                        </div>
                                                        <div class="bg-dark fs-11 fw-medium px-2 py-1 rounded-pill text-white user-rating"><?= $stats['four_star_reviews'] ?? 0 ?></div>
                                                    </div>
                                                    
                                                    <!-- 3 Star -->
                                                    <div class="align-items-center d-flex mb-2 rating-dimension gap-2">
                                                        <div class="d-flex align-items-center gap-2">
                                                            <span class="fs-14 fw-semibold rating-points">3</span>
                                                            <div class="d-flex align-items-center text-warning">
                                                                <i class="fas fa-star"></i>
                                                                <i class="fas fa-star"></i>
                                                                <i class="fas fa-star"></i>
                                                                <i class="far fa-star"></i>
                                                                <i class="far fa-star"></i>
                                                            </div>
                                                        </div>
                                                        <div class="progress flex-grow-1 me-2">
                                                            <div class="progress-bar bg-info" role="progressbar" style="width: <?= $stats['three_star_percentage'] ?? 0 ?>%" aria-valuenow="<?= $stats['three_star_percentage'] ?? 0 ?>" aria-valuemin="0" aria-valuemax="100"></div>
                                                        </div>
                                                        <div class="bg-dark fs-11 fw-medium px-2 py-1 rounded-pill text-white user-rating"><?= $stats['three_star_reviews'] ?? 0 ?></div>
                                                    </div>
                                                    
                                                    <!-- 2 Star -->
                                                    <div class="align-items-center d-flex mb-2 rating-dimension gap-2">
                                                        <div class="d-flex align-items-center gap-2">
                                                            <span class="fs-14 fw-semibold rating-points">2</span>
                                                            <div class="d-flex align-items-center text-warning">
                                                                <i class="fas fa-star"></i>
                                                                <i class="fas fa-star"></i>
                                                                <i class="far fa-star"></i>
                                                                <i class="far fa-star"></i>
                                                                <i class="far fa-star"></i>
                                                            </div>
                                                        </div>
                                                        <div class="progress flex-grow-1 me-2">
                                                            <div class="progress-bar bg-primary" role="progressbar" style="width: <?= $stats['two_star_percentage'] ?? 0 ?>%" aria-valuenow="<?= $stats['two_star_percentage'] ?? 0 ?>" aria-valuemin="0" aria-valuemax="100"></div>
                                                        </div>
                                                        <div class="bg-dark fs-11 fw-medium px-2 py-1 rounded-pill text-white user-rating"><?= $stats['two_star_reviews'] ?? 0 ?></div>
                                                    </div>
                                                    
                                                    <!-- 1 Star -->
                                                    <div class="align-items-center d-flex mb-2 rating-dimension gap-2">
                                                        <div class="d-flex align-items-center gap-2">
                                                            <span class="fs-14 fw-semibold rating-points">1</span>
                                                            <div class="d-flex align-items-center text-warning">
                                                                <i class="fas fa-star"></i>
                                                                <i class="far fa-star"></i>
                                                                <i class="far fa-star"></i>
                                                                <i class="far fa-star"></i>
                                                                <i class="far fa-star"></i>
                                                            </div>
                                                        </div>
                                                        <div class="progress flex-grow-1 me-2">
                                                            <div class="progress-bar bg-danger" role="progressbar" style="width: <?= $stats['one_star_percentage'] ?? 0 ?>%" aria-valuenow="<?= $stats['one_star_percentage'] ?? 0 ?>" aria-valuemin="0" aria-valuemax="100"></div>
                                                        </div>
                                                        <div class="bg-dark fs-11 fw-medium px-2 py-1 rounded-pill text-white user-rating"><?= $stats['one_star_reviews'] ?? 0 ?></div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Filter Buttons -->
                                <div class="mb-4">
                                    <div class="btn-group" role="group">
                                        <a href="?filter=all" class="btn <?= $filter === 'all' ? 'btn-primary' : 'btn-outline-primary' ?> btn-sm">All</a>
                                        <a href="?filter=5" class="btn <?= $filter === '5' ? 'btn-primary' : 'btn-outline-primary' ?> btn-sm">5 Star</a>
                                        <a href="?filter=4" class="btn <?= $filter === '4' ? 'btn-primary' : 'btn-outline-primary' ?> btn-sm">4 Star</a>
                                        <a href="?filter=3" class="btn <?= $filter === '3' ? 'btn-primary' : 'btn-outline-primary' ?> btn-sm">3 Star</a>
                                        <a href="?filter=2" class="btn <?= $filter === '2' ? 'btn-primary' : 'btn-outline-primary' ?> btn-sm">2 Star</a>
                                        <a href="?filter=1" class="btn <?= $filter === '1' ? 'btn-primary' : 'btn-outline-primary' ?> btn-sm">1 Star</a>
                                    </div>
                                </div>

                                <!-- Reviews List -->
                                <?php if (!empty($reviews)): ?>
                                    <?php foreach ($reviews as $review_item): ?>
                                        <div class="d-flex mb-4 border-bottom pb-4">
                                            <div class="flex-shrink-0">
                                                <img src="<?= "../public/uploads/items/".htmlspecialchars($review_item['item_image'] ?: 'assets/dist/img/placeholder.jpg') ?>" alt="<?= htmlspecialchars($review_item['item_title']) ?>" height="70" width="70" class="object-fit-cover rounded-circle">
                                            </div>
                                            <div class="flex-grow-1 ms-4">
                                                <div class="comment-header d-flex flex-wrap gap-2 mb-3">
                                                    <div>
                                                        <h4 class="fs-18 mb-0"><?= htmlspecialchars($review_item['customer_first_name'] ?? 'Customer') . ' ' . htmlspecialchars($review_item['customer_last_name'] ?? '') ?></h4>
                                                        <div class="comment-datetime fs-12 text-muted"><?= formatDate($review_item['created_at']) ?></div>
                                                        <div class="fs-12 text-muted">Order: <?= htmlspecialchars($review_item['order_number']) ?></div>
                                                        <div class="fs-12 text-muted">Item: <?= htmlspecialchars($review_item['item_title']) ?></div>
                                                        <div class="fs-12 text-muted">Vendor: <?= htmlspecialchars($review_item['vendor_name']) ?></div>
                                                    </div>
                                                    <div class="d-flex align-items-center gap-2 ms-auto">
                                                        <?= renderStars($review_item['rating']) ?>
                                                        <span class="fs-14 fw-semibold rating-points"><?= $review_item['rating'] ?>/5</span>
                                                    </div>
                                                </div>
                                                <div class="fs-15"><?= nl2br(htmlspecialchars($review_item['review'])) ?></div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>

                                    <!-- Pagination -->
                                    <?php if ($total_pages > 1): ?>
                                        <nav aria-label="Reviews pagination">
                                            <ul class="pagination justify-content-center">
                                                <?php if ($page > 1): ?>
                                                    <li class="page-item">
                                                        <a class="page-link" href="?page=<?= $page - 1 ?>&filter=<?= $filter ?>">Previous</a>
                                                    </li>
                                                <?php endif; ?>
                                                
                                                <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                                                    <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                                                        <a class="page-link" href="?page=<?= $i ?>&filter=<?= $filter ?>"><?= $i ?></a>
                                                    </li>
                                                <?php endfor; ?>
                                                
                                                <?php if ($page < $total_pages): ?>
                                                    <li class="page-item">
                                                        <a class="page-link" href="?page=<?= $page + 1 ?>&filter=<?= $filter ?>">Next</a>
                                                    </li>
                                                <?php endif; ?>
                                            </ul>
                                        </nav>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <div class="text-center py-5">
                                        <i class="fas fa-star fs-1 text-muted mb-3"></i>
                                        <h5>No Reviews Yet</h5>
                                        <p class="text-muted">
                                            <?php if (!empty($unreviewed_orders)): ?>
                                                You have completed rentals waiting for your review!
                                            <?php else: ?>
                                                You haven't written any reviews yet.
                                            <?php endif; ?>
                                        </p>
                                        <?php if (!empty($unreviewed_orders)): ?>
                                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#writeReviewModal">
                                            Write Your First Review
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Write Review Modal -->
    <?php if (!empty($unreviewed_orders)): ?>
    <div class="modal fade" id="writeReviewModal" tabindex="-1" aria-labelledby="writeReviewModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="writeReviewModalLabel">Write a Review</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="orderSelect" class="form-label">Select Rental to Review</label>
                            <select class="form-select" id="orderSelect" name="order_id" required>
                                <option value="">Choose a completed rental...</option>
                                <?php foreach ($unreviewed_orders as $order_item): ?>
                                    <option value="<?= $order_item['id'] ?>">
                                        <?= htmlspecialchars($order_item['item_title']) ?> - <?= htmlspecialchars($order_item['vendor_name']) ?> (Order: <?= htmlspecialchars($order_item['order_number']) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Rating</label>
                            <div class="star-rating-input d-flex gap-1">
                                <?php for ($i = 5; $i >= 1; $i--): ?>
                                    <input type="radio" id="star<?= $i ?>" name="rating" value="<?= $i ?>" required>
                                    <label for="star<?= $i ?>" class="fs-4 text-warning" style="cursor: pointer;">★</label>
                                <?php endfor; ?>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="reviewText" class="form-label">Your Review</label>
                            <textarea class="form-control" id="reviewText" name="review" rows="4" placeholder="Share your experience with this rental..." required></textarea>
                            <div class="form-text">Be honest and detailed to help other customers</div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="submit_review" class="btn btn-primary">Submit Review</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Global script -->
    <script src="../assets/plugins/jQuery/jquery.min.js"></script>
    <script src="../assets/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../assets/plugins/metisMenu/metisMenu.min.js"></script>
    <script src="../assets/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script>
    <script src="../assets/dist/js/app.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Form validation
            $('form').on('submit', function(e) {
                const rating = $('input[name="rating"]:checked').val();
                const reviewText = $('#reviewText').val().trim();
                const orderId = $('#orderSelect').val();
                
                if (!orderId) {
                    e.preventDefault();
                    alert('Please select a rental to review.');
                    return false;
                }
                
                if (!rating) {
                    e.preventDefault();
                    alert('Please select a rating.');
                    return false;
                }
                
                if (!reviewText) {
                    e.preventDefault();
                    alert('Please enter your review.');
                    return false;
                }
            });
        });
    </script>
</body>
</html>