<?php
/**
 * VENDOR REVIEWS PAGE
 * File: vendor/reviews.php
 * View all reviews for vendor's items
 */

require_once '../app/Core/init.php';

// Require vendor authentication
Auth::requireVendor();

$page_title = "Item Reviews";
$active_menu = "reviews";

// Initialize models
$db = Database::getInstance();
$vendor = new Vendor();

// Get vendor details
$vendor_id = Auth::id();
$vendor_data = $vendor->getByUserId($vendor_id);

if (!$vendor_data) {
    flash('error', 'Please complete your profile first.', 'danger');
    redirect('profile.php');
}

// Get filter parameters
$rating_filter = $_GET['rating'] ?? 'all';
$item_filter = $_GET['item'] ?? 'all';
$status_filter = $_GET['status'] ?? 'all';
$search = $_GET['search'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 15;

// Build WHERE clause
$where_conditions = ["i.vendor_id = ?"];
$params = [$vendor_data['id']];

if ($rating_filter !== 'all' && is_numeric($rating_filter)) {
    $where_conditions[] = "r.rating = ?";
    $params[] = $rating_filter;
}

if ($item_filter !== 'all') {
    $where_conditions[] = "r.item_id = ?";
    $params[] = $item_filter;
}

if ($status_filter !== 'all') {
    $where_conditions[] = "r.status = ?";
    $params[] = $status_filter;
}

if (!empty($search)) {
    $where_conditions[] = "(r.review LIKE ? OR c.first_name LIKE ? OR c.last_name LIKE ? OR i.title LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

$where_clause = 'WHERE ' . implode(' AND ', $where_conditions);

// Get total count
$count_sql = "SELECT COUNT(*) as total 
              FROM reviews r
              JOIN items i ON r.item_id = i.id
              JOIN customers c ON r.customer_id = c.id
              $where_clause";
$count_result = $db->fetch($count_sql, $params);
$total_reviews = $count_result['total'];
$total_pages = ceil($total_reviews / $per_page);
$offset = ($page - 1) * $per_page;

// Get reviews
$sql = "SELECT 
    r.*,
    i.title as item_title,
    i.main_image as item_image,
    CONCAT(c.first_name, ' ', c.last_name) as customer_name,
    c.profile_picture as customer_avatar,
    o.order_number
FROM reviews r
JOIN items i ON r.item_id = i.id
JOIN customers c ON r.customer_id = c.id
JOIN orders o ON r.order_id = o.id
$where_clause
ORDER BY r.created_at DESC
LIMIT ? OFFSET ?";

$params[] = $per_page;
$params[] = $offset;
$reviews = $db->fetchAll($sql, $params);

// Get vendor's items for filter dropdown
$items_sql = "SELECT id, title FROM items WHERE vendor_id = ? AND approval_status = 'approved' ORDER BY title";
$vendor_items = $db->fetchAll($items_sql, [$vendor_data['id']]);

// Get review statistics
$stats_sql = "SELECT 
    COUNT(*) as total_reviews,
    ROUND(AVG(r.rating), 1) as average_rating,
    COUNT(CASE WHEN r.rating = 5 THEN 1 END) as five_star,
    COUNT(CASE WHEN r.rating = 4 THEN 1 END) as four_star,
    COUNT(CASE WHEN r.rating = 3 THEN 1 END) as three_star,
    COUNT(CASE WHEN r.rating = 2 THEN 1 END) as two_star,
    COUNT(CASE WHEN r.rating = 1 THEN 1 END) as one_star,
    COUNT(CASE WHEN r.vendor_reply IS NOT NULL THEN 1 END) as replied_count
FROM reviews r
JOIN items i ON r.item_id = i.id
WHERE i.vendor_id = ?";

$stats = $db->fetch($stats_sql, [$vendor_data['id']]) ?: [
    'total_reviews' => 0,
    'average_rating' => 0,
    'five_star' => 0,
    'four_star' => 0,
    'three_star' => 0,
    'two_star' => 0,
    'one_star' => 0,
    'replied_count' => 0
];

// Handle review actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate CSRF token
    if (!Security::validateToken($_POST['csrf_token'] ?? '')) {
        flash('error', 'Invalid security token', 'danger');
        redirect('reviews.php');
    }
    
    $action = $_POST['action'] ?? '';
    $review_id = isset($_POST['review_id']) ? (int)$_POST['review_id'] : 0;
    
    if ($review_id) {
        // Verify review belongs to vendor
        $verify_sql = "SELECT r.* FROM reviews r 
                      JOIN items i ON r.item_id = i.id 
                      WHERE r.id = ? AND i.vendor_id = ?";
        $review_to_manage = $db->fetch($verify_sql, [$review_id, $vendor_data['id']]);
        
        if (!$review_to_manage) {
            flash('error', 'Review not found or access denied', 'danger');
            redirect('reviews.php');
        }
        
        switch ($action) {
            case 'reply':
                $vendor_reply = trim($_POST['vendor_reply'] ?? '');
                
                if (!empty($vendor_reply)) {
                    try {
                        $update_sql = "UPDATE reviews 
                                      SET vendor_reply = ?, 
                                          vendor_replied_at = NOW(),
                                          updated_at = NOW()
                                      WHERE id = ?";
                        $result = $db->execute($update_sql, [$vendor_reply, $review_id]);
                        
                        if ($result) {
                            flash('success', 'Reply submitted successfully!', 'success');
                        } else {
                            flash('error', 'Failed to submit reply', 'danger');
                        }
                    } catch (Exception $e) {
                        flash('error', 'Error submitting reply: ' . $e->getMessage(), 'danger');
                    }
                }
                break;
                
            case 'hide_review':
                try {
                    $update_sql = "UPDATE reviews SET status = 'hidden', updated_at = NOW() WHERE id = ?";
                    $result = $db->execute($update_sql, [$review_id]);
                    
                    if ($result) {
                        flash('success', 'Review hidden successfully', 'success');
                    } else {
                        flash('error', 'Failed to hide review', 'danger');
                    }
                } catch (Exception $e) {
                    flash('error', 'Error hiding review: ' . $e->getMessage(), 'danger');
                }
                break;
                
            case 'show_review':
                try {
                    $update_sql = "UPDATE reviews SET status = 'active', updated_at = NOW() WHERE id = ?";
                    $result = $db->execute($update_sql, [$review_id]);
                    
                    if ($result) {
                        flash('success', 'Review made visible successfully', 'success');
                    } else {
                        flash('error', 'Failed to show review', 'danger');
                    }
                } catch (Exception $e) {
                    flash('error', 'Error showing review: ' . $e->getMessage(), 'danger');
                }
                break;
        }
    }
    
    redirect('reviews.php?' . http_build_query($_GET));
}

// Handle flash messages
$flash_message = flash('message');

include '../templates/layouts/vendor/header.php';
?>

<div class="main-content">
    <div class="page-header">
        <div class="header-left">
            <h1><i class="fas fa-star"></i> Item Reviews</h1>
            <p class="text-muted">Manage and respond to customer reviews</p>
        </div>
    </div>

    <!-- Flash Messages -->
    <?php if ($flash_message): ?>
        <div class="alert alert-<?= $flash_message['type'] ?>">
            <?= Security::escapeOutput($flash_message['message']) ?>
        </div>
    <?php endif; ?>
    
    <!-- Review Statistics -->
    <div class="stats-grid mb-4">
        <div class="stat-card">
            <div class="stat-icon bg-primary">
                <i class="fas fa-comments"></i>
            </div>
            <div class="stat-details">
                <h3><?= number_format($stats['total_reviews']) ?></h3>
                <p>Total Reviews</p>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon bg-warning">
                <i class="fas fa-star"></i>
            </div>
            <div class="stat-details">
                <h3><?= number_format($stats['average_rating'], 1) ?></h3>
                <p>Average Rating</p>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon bg-success">
                <i class="fas fa-reply"></i>
            </div>
            <div class="stat-details">
                <h3><?= number_format($stats['replied_count']) ?></h3>
                <p>Replied To</p>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon bg-info">
                <i class="fas fa-percentage"></i>
            </div>
            <div class="stat-details">
                <h3><?= $stats['total_reviews'] > 0 ? number_format(($stats['replied_count'] / $stats['total_reviews']) * 100, 1) : 0 ?>%</h3>
                <p>Response Rate</p>
            </div>
        </div>
    </div>

    <!-- Rating Distribution -->
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-chart-bar"></i> Rating Distribution</h5>
        </div>
        <div class="card-body">
            <div class="row">
                <?php
                $ratings = [
                    5 => $stats['five_star'],
                    4 => $stats['four_star'],
                    3 => $stats['three_star'],
                    2 => $stats['two_star'],
                    1 => $stats['one_star']
                ];
                
                foreach ($ratings as $stars => $count):
                    $percentage = $stats['total_reviews'] > 0 ? ($count / $stats['total_reviews']) * 100 : 0;
                ?>
                    <div class="col-md-6 mb-3">
                        <div class="d-flex align-items-center">
                            <div class="text-warning me-2" style="width: 60px;">
                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                    <i class="fas fa-star <?= $i <= $stars ? '' : 'text-light' ?>"></i>
                                <?php endfor; ?>
                            </div>
                            <div class="progress flex-grow-1 me-3" style="height: 20px;">
                                <div class="progress-bar bg-warning" role="progressbar" 
                                     style="width: <?= $percentage ?>%" 
                                     aria-valuenow="<?= $percentage ?>" 
                                     aria-valuemin="0" 
                                     aria-valuemax="100">
                                </div>
                            </div>
                            <div style="width: 40px; text-align: right;">
                                <small class="text-muted"><?= $count ?></small>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" class="filter-form">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Rating</label>
                        <select name="rating" class="form-control" onchange="this.form.submit()">
                            <option value="all" <?= $rating_filter === 'all' ? 'selected' : '' ?>>All Ratings</option>
                            <option value="5" <?= $rating_filter === '5' ? 'selected' : '' ?>>5 Stars</option>
                            <option value="4" <?= $rating_filter === '4' ? 'selected' : '' ?>>4 Stars</option>
                            <option value="3" <?= $rating_filter === '3' ? 'selected' : '' ?>>3 Stars</option>
                            <option value="2" <?= $rating_filter === '2' ? 'selected' : '' ?>>2 Stars</option>
                            <option value="1" <?= $rating_filter === '1' ? 'selected' : '' ?>>1 Star</option>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">Item</label>
                        <select name="item" class="form-control" onchange="this.form.submit()">
                            <option value="all">All Items</option>
                            <?php foreach ($vendor_items as $item): ?>
                                <option value="<?= $item['id'] ?>" <?= $item_filter == $item['id'] ? 'selected' : '' ?>>
                                    <?= esc($item['title']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-control" onchange="this.form.submit()">
                            <option value="all" <?= $status_filter === 'all' ? 'selected' : '' ?>>All Status</option>
                            <option value="active" <?= $status_filter === 'active' ? 'selected' : '' ?>>Active</option>
                            <option value="hidden" <?= $status_filter === 'hidden' ? 'selected' : '' ?>>Hidden</option>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">Search</label>
                        <input type="text" name="search" class="form-control" 
                               placeholder="Search reviews, customers, items..." 
                               value="<?= esc($search) ?>">
                    </div>
                    
                    <div class="col-md-1">
                        <label class="form-label">&nbsp;</label>
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-search"></i>
                            </button>
                            <a href="reviews.php" class="btn btn-secondary">
                                <i class="fas fa-redo"></i>
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Reviews List -->
    <?php if (empty($reviews)): ?>
        <div class="card">
            <div class="card-body text-center py-5">
                <i class="fas fa-star fa-4x text-muted mb-4"></i>
                <h3>No Reviews Yet</h3>
                <p class="text-muted mb-4">Customer reviews will appear here once they rate your items.</p>
            </div>
        </div>
    <?php else: ?>
        <div class="card">
            <div class="card-body">
                <?php foreach ($reviews as $review): ?>
                    <div class="review-item border-bottom pb-4 mb-4">
                        <div class="row">
                            <div class="col-md-8">
                                <!-- Customer & Item Info -->
                                <div class="d-flex align-items-start mb-3">
                                    <?php if (!empty($review['customer_avatar'])): ?>
                                        <img src="<?= upload($review['customer_avatar']) ?>" 
                                             alt="<?= Security::escapeOutput($review['customer_name']) ?>"
                                             class="rounded-circle me-3"
                                             style="width: 50px; height: 50px; object-fit: cover;">
                                    <?php else: ?>
                                        <div class="rounded-circle bg-primary text-white d-flex align-items-center justify-content-center me-3" 
                                             style="width: 50px; height: 50px;">
                                            <?= strtoupper(substr($review['customer_name'], 0, 2)) ?>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <div class="flex-grow-1">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div>
                                                <h6 class="mb-1"><?= Security::escapeOutput($review['customer_name']) ?></h6>
                                                <div class="text-warning mb-1">
                                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                                        <i class="fas fa-star <?= $i <= $review['rating'] ? '' : 'text-light' ?>"></i>
                                                    <?php endfor; ?>
                                                </div>
                                                <small class="text-muted">
                                                    Order #<?= Security::escapeOutput($review['order_number']) ?> • 
                                                    <?= format_date($review['created_at']) ?>
                                                </small>
                                            </div>
                                            <div>
                                                <?= format_status_badge($review['status']) ?>
                                            </div>
                                        </div>
                                        
                                        <!-- Item Info -->
                                        <div class="mt-2 d-flex align-items-center">
                                            <?php if (!empty($review['item_image'])): ?>
                                                <img src="<?= upload('items/' . $review['item_image']) ?>" 
                                                     alt="<?= Security::escapeOutput($review['item_title']) ?>"
                                                     class="rounded me-2"
                                                     style="width: 40px; height: 40px; object-fit: cover;">
                                            <?php endif; ?>
                                            <small class="text-muted"><?= Security::escapeOutput($review['item_title']) ?></small>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Review Text -->
                                <?php if (!empty($review['review'])): ?>
                                    <p class="mb-3"><?= Security::escapeOutput($review['review']) ?></p>
                                <?php endif; ?>
                                
                                <!-- Vendor Reply -->
                                <?php if (!empty($review['vendor_reply'])): ?>
                                    <div class="bg-light p-3 rounded mt-3">
                                        <div class="d-flex justify-content-between align-items-start mb-2">
                                            <strong>Your Reply</strong>
                                            <small class="text-muted"><?= format_date($review['vendor_replied_at']) ?></small>
                                        </div>
                                        <p class="mb-0"><?= Security::escapeOutput($review['vendor_reply']) ?></p>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="col-md-4">
                                <!-- Action Buttons -->
                                <div class="d-flex flex-column gap-2">
                                    <?php if (empty($review['vendor_reply'])): ?>
                                        <button class="btn btn-sm btn-outline-primary" 
                                                data-bs-toggle="modal" 
                                                data-bs-target="#replyModal"
                                                onclick="setReviewId(<?= $review['id'] ?>)">
                                            <i class="fas fa-reply"></i> Reply
                                        </button>
                                    <?php else: ?>
                                        <button class="btn btn-sm btn-outline-secondary" 
                                                data-bs-toggle="modal" 
                                                data-bs-target="#replyModal"
                                                onclick="setReviewId(<?= $review['id'] ?>, '<?= Security::escapeOutput($review['vendor_reply']) ?>')">
                                            <i class="fas fa-edit"></i> Edit Reply
                                        </button>
                                    <?php endif; ?>
                                    
                                    <?php if ($review['status'] === 'active'): ?>
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="csrf_token" value="<?= Security::generateToken() ?>">
                                            <input type="hidden" name="action" value="hide_review">
                                            <input type="hidden" name="review_id" value="<?= $review['id'] ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-warning w-100" 
                                                    onclick="return confirm('Hide this review from public view?')">
                                                <i class="fas fa-eye-slash"></i> Hide
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="csrf_token" value="<?= Security::generateToken() ?>">
                                            <input type="hidden" name="action" value="show_review">
                                            <input type="hidden" name="review_id" value="<?= $review['id'] ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-success w-100" 
                                                    onclick="return confirm('Make this review visible to public?')">
                                                <i class="fas fa-eye"></i> Show
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
            <div class="d-flex justify-content-center mt-4">
                <?php 
                $pagination_params = array_filter([
                    'rating' => $rating_filter !== 'all' ? $rating_filter : null,
                    'item' => $item_filter !== 'all' ? $item_filter : null,
                    'status' => $status_filter !== 'all' ? $status_filter : null,
                    'search' => !empty($search) ? $search : null
                ]);
                echo render_pagination($page, $total_pages, 'reviews.php', $pagination_params); 
                ?>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>

<!-- Reply Modal -->
<div class="modal fade" id="replyModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Reply to Review</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?= Security::generateToken() ?>">
                <input type="hidden" name="action" value="reply">
                <input type="hidden" name="review_id" id="modalReviewId">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Your Reply</label>
                        <textarea name="vendor_reply" id="vendorReply" class="form-control" rows="4" 
                                  placeholder="Type your response to the customer..." required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Send Reply</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function setReviewId(reviewId, existingReply = '') {
    document.getElementById('modalReviewId').value = reviewId;
    document.getElementById('vendorReply').value = existingReply;
}

// Auto-hide success messages
setTimeout(function() {
    const alerts = document.querySelectorAll('.alert-success');
    alerts.forEach(alert => {
        alert.style.transition = 'opacity 0.5s';
        alert.style.opacity = '0';
        setTimeout(() => alert.remove(), 500);
    });
}, 3000);
</script>

<style>
.stat-card {
    background: white;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    gap: 15px;
}

.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 24px;
}

.stat-details h3 {
    margin: 0;
    font-size: 24px;
    font-weight: 700;
}

.stat-details p {
    margin: 0;
    color: #666;
    font-size: 14px;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
}

.review-item:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
}
</style>

<?php //include '../templates/layouts/vendor/footer.php'; ?>