<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once("../php/db_connect.php");

if (!isset($_SESSION["user_id"])) {
    echo "<script>window.location='index.php';</script>";
    exit();
}

$shop_id = (int) $_SESSION["user_id"];

function h($value)
{
    return htmlspecialchars((string)($value ?? ""), ENT_QUOTES, "UTF-8");
}

function formatDateOnly($date)
{
    if (empty($date) || $date === "0000-00-00" || $date === "0000-00-00 00:00:00") {
        return "N/A";
    }

    return date("M d, Y", strtotime($date));
}

function displayStatus($status)
{
    if (empty($status)) {
        return "N/A";
    }

    return ucwords(str_replace("_", " ", $status));
}

function feedbackBadgeClass($status)
{
    $status = strtolower((string)($status ?? ""));

    if ($status === "submitted") {
        return "bg-success-subtle text-success border border-success-subtle";
    }

    if ($status === "reviewed") {
        return "bg-primary-subtle text-primary border border-primary-subtle";
    }

    if ($status === "none") {
        return "bg-secondary-subtle text-secondary border border-secondary-subtle";
    }

    return "bg-warning-subtle text-warning-emphasis border border-warning-subtle";
}

function ratingStars($rating)
{
    $rating = (int) $rating;
    $stars = "";

    for ($i = 1; $i <= 5; $i++) {
        if ($i <= $rating) {
            $stars .= '<i class="fa-solid fa-star text-warning"></i>';
        } else {
            $stars .= '<i class="fa-regular fa-star text-muted"></i>';
        }
    }

    return $stars;
}

/*
|--------------------------------------------------------------------------
| UPDATE FEEDBACK STATUS
|--------------------------------------------------------------------------
*/

if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["mark_reviewed"])) {
    $order_id = (int)($_POST["order_id"] ?? 0);

    $stmt = $conn->prepare("
        UPDATE orders
        SET feedback_status = 'reviewed'
        WHERE id = ?
        AND shop_id = ?
    ");

    if (!$stmt) {
        die("Prepare failed: " . $conn->error);
    }

    $stmt->bind_param("ii", $order_id, $shop_id);

    if ($stmt->execute()) {
        $_SESSION["success_message"] = "Feedback marked as reviewed.";
    } else {
        $_SESSION["error_message"] = "Failed to update feedback.";
    }

    echo "<script>window.location='admin.php?page=feedback-monitoring';</script>";
    exit();
}

/*
|--------------------------------------------------------------------------
| DELETE / CLEAR FEEDBACK
|--------------------------------------------------------------------------
*/

if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["clear_feedback"])) {
    $order_id = (int)($_POST["order_id"] ?? 0);

    $stmt = $conn->prepare("
        UPDATE orders
        SET 
            feedback_rating = NULL,
            feedback_comment = NULL,
            feedback_status = 'none',
            feedback_created_at = NULL
        WHERE id = ?
        AND shop_id = ?
    ");

    if (!$stmt) {
        die("Prepare failed: " . $conn->error);
    }

    $stmt->bind_param("ii", $order_id, $shop_id);

    if ($stmt->execute()) {
        $_SESSION["success_message"] = "Feedback cleared successfully.";
    } else {
        $_SESSION["error_message"] = "Failed to clear feedback.";
    }

    echo "<script>window.location='admin.php?page=feedback-monitoring';</script>";
    exit();
}

/*
|--------------------------------------------------------------------------
| FILTERS
|--------------------------------------------------------------------------
*/

$search = trim($_GET["search"] ?? "");
$status_filter = $_GET["status"] ?? "";
$rating_filter = $_GET["rating"] ?? "";
$from_date = $_GET["from_date"] ?? "";
$to_date = $_GET["to_date"] ?? "";

$where = " WHERE shop_id = ? ";
$params = [$shop_id];
$types = "i";

if (!empty($search)) {
    $where .= " AND (
        order_code LIKE ?
        OR customer_name LIKE ?
        OR service_type LIKE ?
        OR item_name LIKE ?
        OR feedback_comment LIKE ?
    ) ";

    $searchTerm = "%" . $search . "%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $types .= "sssss";
}

if (!empty($status_filter)) {
    $where .= " AND feedback_status = ? ";
    $params[] = $status_filter;
    $types .= "s";
}

if (!empty($rating_filter)) {
    $where .= " AND feedback_rating = ? ";
    $params[] = (int)$rating_filter;
    $types .= "i";
}

if (!empty($from_date) && !empty($to_date)) {
    $where .= " AND DATE(feedback_created_at) BETWEEN ? AND ? ";
    $params[] = $from_date;
    $params[] = $to_date;
    $types .= "ss";
} elseif (!empty($from_date)) {
    $where .= " AND DATE(feedback_created_at) >= ? ";
    $params[] = $from_date;
    $types .= "s";
} elseif (!empty($to_date)) {
    $where .= " AND DATE(feedback_created_at) <= ? ";
    $params[] = $to_date;
    $types .= "s";
}

/*
|--------------------------------------------------------------------------
| SUMMARY
|--------------------------------------------------------------------------
*/

$summarySql = "
    SELECT
        COUNT(id) AS total_orders,
        SUM(CASE WHEN feedback_status IN ('submitted', 'reviewed') THEN 1 ELSE 0 END) AS total_feedback,
        SUM(CASE WHEN feedback_status = 'reviewed' THEN 1 ELSE 0 END) AS reviewed_feedback,
        SUM(CASE WHEN feedback_rating <= 2 AND feedback_rating IS NOT NULL THEN 1 ELSE 0 END) AS low_ratings,
        COALESCE(AVG(feedback_rating), 0) AS average_rating
    FROM orders
    $where
";

$summaryStmt = $conn->prepare($summarySql);

if (!$summaryStmt) {
    die("Prepare failed: " . $conn->error);
}

$summaryStmt->bind_param($types, ...$params);
$summaryStmt->execute();
$summary = $summaryStmt->get_result()->fetch_assoc();

$total_orders = (int)($summary["total_orders"] ?? 0);
$total_feedback = (int)($summary["total_feedback"] ?? 0);
$reviewed_feedback = (int)($summary["reviewed_feedback"] ?? 0);
$low_ratings = (int)($summary["low_ratings"] ?? 0);
$average_rating = (float)($summary["average_rating"] ?? 0);

/*
|--------------------------------------------------------------------------
| FEEDBACK LIST
|--------------------------------------------------------------------------
*/

$listSql = "
    SELECT
        id,
        order_code,
        customer_name,
        service_type,
        item_name,
        quantity,
        status AS order_status,
        feedback_rating,
        feedback_comment,
        feedback_status,
        feedback_created_at,
        created_at
    FROM orders
    $where
    ORDER BY 
        CASE 
            WHEN feedback_status = 'submitted' THEN 1
            WHEN feedback_status = 'reviewed' THEN 2
            ELSE 3
        END,
        feedback_created_at DESC,
        created_at DESC
";

$listStmt = $conn->prepare($listSql);

if (!$listStmt) {
    die("Prepare failed: " . $conn->error);
}

$listStmt->bind_param($types, ...$params);
$listStmt->execute();
$feedbacks = $listStmt->get_result();
?>

<div class="container-fluid px-0 feedback-page">

    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
        <div>
            <h1 class="fw-bold mb-1">Feedback Monitoring</h1>
            <p class="text-muted mb-0">
                Monitor customer ratings, comments, and service feedback.
            </p>
        </div>

        <a href="admin.php?page=orders" class="btn btn-light border rounded-pill px-4">
            <i class="fa-solid fa-arrow-left me-1"></i> Back to Orders
        </a>
    </div>

    <?php if (!empty($_SESSION["success_message"])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo h($_SESSION["success_message"]); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php unset($_SESSION["success_message"]); ?>
    <?php endif; ?>

    <?php if (!empty($_SESSION["error_message"])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo h($_SESSION["error_message"]); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php unset($_SESSION["error_message"]); ?>
    <?php endif; ?>

    <div class="row g-3 mb-4">
        <div class="col-12 col-sm-6 col-xl">
            <div class="feedback-stat-card">
                <div class="stat-icon bg-primary-subtle text-primary">
                    <i class="fa-solid fa-clipboard-list"></i>
                </div>
                <div>
                    <p>Total Orders</p>
                    <h3><?php echo $total_orders; ?></h3>
                </div>
            </div>
        </div>

        <div class="col-12 col-sm-6 col-xl">
            <div class="feedback-stat-card">
                <div class="stat-icon bg-info-subtle text-info">
                    <i class="fa-solid fa-comments"></i>
                </div>
                <div>
                    <p>Total Feedback</p>
                    <h3><?php echo $total_feedback; ?></h3>
                </div>
            </div>
        </div>

        <div class="col-12 col-sm-6 col-xl">
            <div class="feedback-stat-card">
                <div class="stat-icon bg-success-subtle text-success">
                    <i class="fa-solid fa-circle-check"></i>
                </div>
                <div>
                    <p>Reviewed</p>
                    <h3><?php echo $reviewed_feedback; ?></h3>
                </div>
            </div>
        </div>

        <div class="col-12 col-sm-6 col-xl">
            <div class="feedback-stat-card">
                <div class="stat-icon bg-warning-subtle text-warning-emphasis">
                    <i class="fa-solid fa-star"></i>
                </div>
                <div>
                    <p>Average Rating</p>
                    <h3><?php echo number_format($average_rating, 1); ?>/5</h3>
                </div>
            </div>
        </div>

        <div class="col-12 col-sm-6 col-xl">
            <div class="feedback-stat-card">
                <div class="stat-icon bg-danger-subtle text-danger">
                    <i class="fa-solid fa-triangle-exclamation"></i>
                </div>
                <div>
                    <p>Low Ratings</p>
                    <h3><?php echo $low_ratings; ?></h3>
                </div>
            </div>
        </div>
    </div>

 

    <div class="card border-0 shadow-sm rounded-4">
        <div class="card-body p-4">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
                <div>
                    <h4 class="fw-bold mb-1">Customer Feedback Records</h4>
                    <p class="text-muted mb-0 small">
                        Review ratings and comments from completed orders.
                    </p>
                </div>
            </div>

            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0 feedback-table">
                    <thead>
                        <tr>
                            <th>Order Code</th>
                            <th>Customer</th>
                            <th>Service</th>
                            <th>Item</th>
                            <th>Order Status</th>
                            <th>Rating</th>
                            <th>Comment</th>
                            <th>Feedback Status</th>
                            <th>Date Submitted</th>
                            <th>Action</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php if ($feedbacks && $feedbacks->num_rows > 0): ?>
                            <?php while ($row = $feedbacks->fetch_assoc()): ?>
                                <tr>
                                    <td class="fw-semibold">
                                        <?php echo h($row["order_code"]); ?>
                                    </td>

                                    <td>
                                        <?php echo h($row["customer_name"] ?: "N/A"); ?>
                                    </td>

                                    <td>
                                        <?php echo h($row["service_type"] ?: "N/A"); ?>
                                    </td>

                                    <td>
                                        <?php echo h($row["item_name"] ?: "N/A"); ?>
                                    </td>

                                    <td>
                                        <?php echo h(displayStatus($row["order_status"])); ?>
                                    </td>

                                    <td>
                                        <?php if (!empty($row["feedback_rating"])): ?>
                                            <div class="rating-stars">
                                                <?php echo ratingStars($row["feedback_rating"]); ?>
                                            </div>
                                            <small class="text-muted">
                                                <?php echo (int)$row["feedback_rating"]; ?>/5
                                            </small>
                                        <?php else: ?>
                                            <span class="text-muted">No rating</span>
                                        <?php endif; ?>
                                    </td>

                                    <td class="feedback-comment">
                                        <?php echo h($row["feedback_comment"] ?: "No comment"); ?>
                                    </td>

                                    <td>
                                        <span class="badge rounded-pill px-3 py-2 <?php echo feedbackBadgeClass($row["feedback_status"]); ?>">
                                            <?php echo h(displayStatus($row["feedback_status"])); ?>
                                        </span>
                                    </td>

                                    <td>
                                        <?php echo h(formatDateOnly($row["feedback_created_at"])); ?>
                                    </td>

                                    <td>
                                        <div class="d-flex gap-2">
                                            <?php if ($row["feedback_status"] === "submitted"): ?>
                                                <form method="POST" class="m-0">
                                                    <input type="hidden" name="order_id" value="<?php echo (int)$row["id"]; ?>">
                                                    <button type="submit" name="mark_reviewed" class="btn btn-sm btn-primary rounded-pill px-3">
                                                        Review
                                                    </button>
                                                </form>
                                            <?php endif; ?>

                                            <?php if (!empty($row["feedback_rating"]) || !empty($row["feedback_comment"])): ?>
                                                <form method="POST" class="m-0" onsubmit="return confirm('Clear this feedback?');">
                                                    <input type="hidden" name="order_id" value="<?php echo (int)$row["id"]; ?>">
                                                    <button type="submit" name="clear_feedback" class="btn btn-sm btn-outline-danger rounded-pill px-3">
                                                        Clear
                                                    </button>
                                                </form>
                                            <?php else: ?>
                                                <span class="text-muted small">No action</span>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="10" class="text-center text-muted py-5">
                                    No feedback records found.
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

        </div>
    </div>

</div>

<style>
.feedback-page {
    width: 100%;
    max-width: 100%;
    overflow-x: hidden;
}

.feedback-page h1 {
    font-size: clamp(26px, 2.2vw, 38px);
    color: #111827;
}

.form-control,
.form-select {
    border-radius: 10px;
    padding: 10px 12px;
}

.btn {
    border-radius: 10px;
}

.feedback-stat-card {
    background: #ffffff;
    border-radius: 18px;
    padding: 18px;
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    gap: 12px;
    height: 100%;
}

.stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    flex-shrink: 0;
}

.feedback-stat-card p {
    margin: 0 0 4px;
    color: #6b7280;
    font-size: 13px;
}

.feedback-stat-card h3 {
    margin: 0;
    font-size: 26px;
    font-weight: 800;
    color: #111827;
}

.feedback-table {
    min-width: 1250px;
}

.feedback-table thead th {
    background: #f8fafc;
    color: #111827;
    font-size: 13px;
    font-weight: 700;
    padding: 14px;
    white-space: nowrap;
    border-bottom: 1px solid #e5e7eb;
}

.feedback-table tbody td {
    padding: 14px;
    font-size: 13px;
    white-space: nowrap;
    border-bottom: 1px solid #f0f0f0;
}

.feedback-table tbody tr:hover {
    background: #f9fafb;
}

.feedback-comment {
    max-width: 280px;
    white-space: normal !important;
    line-height: 1.4;
}

.rating-stars {
    white-space: nowrap;
}

@media (max-width: 768px) {
    .feedback-table {
        min-width: 1100px;
    }

    .feedback-table thead th,
    .feedback-table tbody td {
        padding: 12px;
        font-size: 12px;
    }
}
</style>