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

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION["user_id"]) || ($_SESSION["role"] ?? '') !== 'customer') {
    header("Location: index.php");
    exit();
}

$customerId = (int)$_SESSION["user_id"];
$customerName = trim(($_SESSION["first_name"] ?? '') . " " . ($_SESSION["last_name"] ?? ''));
$customerEmail = $_SESSION["email"] ?? "";

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 columnExists($conn, $tableName, $columnName) {
    $stmt = $conn->prepare("
        SELECT COUNT(*) AS total
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
        AND TABLE_NAME = ?
        AND COLUMN_NAME = ?
    ");

    $stmt->bind_param("ss", $tableName, $columnName);
    $stmt->execute();

    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    return (int)$row["total"] > 0;
}

function renderStars($rating) {
    $rating = (int)$rating;
    $html = "";

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

    return $html;
}

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";
    }

    return "bg-secondary-subtle text-secondary border border-secondary-subtle";
}

$hasCustomerId = columnExists($conn, "orders", "customer_id");
$hasCustomerEmail = columnExists($conn, "orders", "customer_email");

/*
|--------------------------------------------------------------------------
| SUBMIT / UPDATE FEEDBACK
|--------------------------------------------------------------------------
*/

if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["submit_feedback"])) {
    $orderId = (int)($_POST["order_id"] ?? 0);
    $rating = (int)($_POST["feedback_rating"] ?? 0);
    $comment = trim($_POST["feedback_comment"] ?? "");

    if ($rating < 1 || $rating > 5) {
        $_SESSION["error_message"] = "Please select a rating from 1 to 5 stars.";
        echo "<script>window.location='customer.php?page=feedback-monitoring';</script>";
        exit();
    }

    if ($comment === "") {
        $_SESSION["error_message"] = "Please enter your feedback comment.";
        echo "<script>window.location='customer.php?page=feedback-monitoring';</script>";
        exit();
    }

    $ownershipWhere = [];
    $ownershipParams = [];
    $ownershipTypes = "";

    if ($hasCustomerId) {
        $ownershipWhere[] = "customer_id = ?";
        $ownershipParams[] = $customerId;
        $ownershipTypes .= "i";
    }

    if ($hasCustomerEmail && !empty($customerEmail)) {
        $ownershipWhere[] = "customer_email = ?";
        $ownershipParams[] = $customerEmail;
        $ownershipTypes .= "s";
    }

    $ownershipWhere[] = "customer_name = ?";
    $ownershipParams[] = $customerName;
    $ownershipTypes .= "s";

    $ownershipSql = implode(" OR ", $ownershipWhere);

    $sql = "
        UPDATE orders
        SET 
            feedback_rating = ?,
            feedback_comment = ?,
            feedback_status = 'submitted',
            feedback_created_at = NOW()
        WHERE id = ?
        AND ($ownershipSql)
    ";

    $stmt = $conn->prepare($sql);

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

    $types = "isi" . $ownershipTypes;
    $params = array_merge([$rating, $comment, $orderId], $ownershipParams);

    $stmt->bind_param($types, ...$params);

    if ($stmt->execute()) {
        $_SESSION["success_message"] = "Thank you! Your feedback has been submitted.";
    } else {
        $_SESSION["error_message"] = "Failed to submit feedback.";
    }

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

/*
|--------------------------------------------------------------------------
| GET CUSTOMER ORDERS
|--------------------------------------------------------------------------
*/

$whereParts = [];
$params = [];
$types = "";

if ($hasCustomerId) {
    $whereParts[] = "o.customer_id = ?";
    $params[] = $customerId;
    $types .= "i";
}

if ($hasCustomerEmail && !empty($customerEmail)) {
    $whereParts[] = "o.customer_email = ?";
    $params[] = $customerEmail;
    $types .= "s";
}

$whereParts[] = "o.customer_name = ?";
$params[] = $customerName;
$types .= "s";

$whereSql = implode(" OR ", $whereParts);

$ordersSql = "
    SELECT
        o.id,
        o.order_code,
        o.customer_name,
        o.service_type,
        o.item_name,
        o.quantity,
        o.size,
        o.status,
        o.payment_status,
        o.due_date,
        o.created_at,
        o.feedback_rating,
        o.feedback_comment,
        o.feedback_status,
        o.feedback_created_at,

        u.shop_name,
        u.shop_type,
        u.shop_image
    FROM orders o
    LEFT JOIN users u ON o.shop_id = u.id
    WHERE ($whereSql)
    ORDER BY o.created_at DESC
";

$stmt = $conn->prepare($ordersSql);

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

$stmt->bind_param($types, ...$params);
$stmt->execute();
$orders = $stmt->get_result();

$totalOrders = $orders ? $orders->num_rows : 0;

$feedbackCount = 0;
$reviewedCount = 0;
$ratingSum = 0;
$ratingCount = 0;

$orderRows = [];

if ($orders && $orders->num_rows > 0) {
    while ($row = $orders->fetch_assoc()) {
        $orderRows[] = $row;

        if (!empty($row["feedback_rating"])) {
            $feedbackCount++;
            $ratingSum += (int)$row["feedback_rating"];
            $ratingCount++;
        }

        if (($row["feedback_status"] ?? "") === "reviewed") {
            $reviewedCount++;
        }
    }
}

$averageRating = $ratingCount > 0 ? $ratingSum / $ratingCount : 0;
?>

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

    <div class="d-flex justify-content-between align-items-start flex-wrap gap-3 mb-4">
        <div>
            <h1 class="fw-bold mb-1">Feedback Monitoring</h1>
            <p class="text-muted mb-0">
                Give ratings and feedback for your completed or processed orders.
            </p>
        </div>

        <a href="customer.php?page=track-order" class="btn btn-light border rounded-pill px-4">
            <i class="fa-solid fa-arrow-left me-1"></i> Back to Track Order
        </a>
    </div>

   <?php
$popupMessage = "";
$popupType = "";

if (!empty($_SESSION["success_message"])) {
    $popupMessage = $_SESSION["success_message"];
    $popupType = "success";
    unset($_SESSION["success_message"]);
} elseif (!empty($_SESSION["error_message"])) {
    $popupMessage = $_SESSION["error_message"];
    $popupType = "error";
    unset($_SESSION["error_message"]);
}
?>

<?php if (!empty($popupMessage)): ?>
    <div class="modal fade" id="feedbackMessageModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 rounded-4 success-popup-modal">
                <div class="modal-body text-center p-5">

                    <?php if ($popupType === "success"): ?>
                        <div class="popup-icon success-icon">
                            <i class="fa-solid fa-check"></i>
                        </div>

                        <h3 class="fw-bold mt-3 mb-2">Success!</h3>
                    <?php else: ?>
                        <div class="popup-icon error-icon">
                            <i class="fa-solid fa-xmark"></i>
                        </div>

                        <h3 class="fw-bold mt-3 mb-2">Oops!</h3>
                    <?php endif; ?>

                    <p class="text-muted mb-4">
                        <?php echo h($popupMessage); ?>
                    </p>

                    <button type="button" class="btn btn-primary rounded-pill px-5" data-bs-dismiss="modal">
                        OK
                    </button>

                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const feedbackModal = new bootstrap.Modal(document.getElementById("feedbackMessageModal"));
            feedbackModal.show();
        });
    </script>
<?php endif; ?>

    <div class="row g-3 mb-4">
        <div class="col-12 col-md-3">
            <div class="feedback-stat-card">
                <div class="stat-icon bg-primary-subtle text-primary">
                    <i class="fa-solid fa-box"></i>
                </div>
                <div>
                    <p>Total Orders</p>
                    <h3><?php echo $totalOrders; ?></h3>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-3">
            <div class="feedback-stat-card">
                <div class="stat-icon bg-success-subtle text-success">
                    <i class="fa-solid fa-comments"></i>
                </div>
                <div>
                    <p>Feedback Given</p>
                    <h3><?php echo $feedbackCount; ?></h3>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-3">
            <div class="feedback-stat-card">
                <div class="stat-icon bg-info-subtle text-info">
                    <i class="fa-solid fa-circle-check"></i>
                </div>
                <div>
                    <p>Reviewed</p>
                    <h3><?php echo $reviewedCount; ?></h3>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-3">
            <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>Your Avg. Rating</p>
                    <h3><?php echo number_format($averageRating, 1); ?>/5</h3>
                </div>
            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm rounded-4">
        <div class="card-body p-4">
            <h4 class="fw-bold mb-1">Your Orders</h4>
            <p class="text-muted mb-4">
                Select an order and submit your rating for the shop.
            </p>

            <?php if (!empty($orderRows)): ?>
                <div class="row g-4">
                    <?php foreach ($orderRows as $order): ?>
                        <?php
                        $shopName = $order["shop_name"] ?? $order["business_name"] ?? "Unnamed Shop";
                        $orderStatus = strtolower($order["status"] ?? "");
                        $hasFeedback = !empty($order["feedback_rating"]) || !empty($order["feedback_comment"]);

                        $canGiveFeedback = in_array($orderStatus, ["completed", "delivered", "in_progress", "accepted", "pending", "outsourced"], true);
                        ?>

                        <div class="col-12 col-lg-6">
                            <div class="order-feedback-card h-100">
                                <div class="d-flex justify-content-between align-items-start gap-3 mb-3">
                                    <div>
                                        <h5 class="fw-bold mb-1"><?php echo h($order["order_code"]); ?></h5>
                                        <p class="text-muted mb-0">
                                            Shop:
                                            <strong><?php echo h($shopName); ?></strong>
                                        </p>
                                    </div>

                                    <span class="badge rounded-pill bg-light text-dark border px-3 py-2">
                                        <?php echo h(displayStatus($order["status"])); ?>
                                    </span>
                                </div>

                                <div class="order-info-grid mb-3">
                                    <div>
                                        <small>Service</small>
                                        <strong><?php echo h($order["service_type"] ?: "N/A"); ?></strong>
                                    </div>

                                    <div>
                                        <small>Item</small>
                                        <strong><?php echo h($order["item_name"] ?: "N/A"); ?></strong>
                                    </div>

                                    <div>
                                        <small>Quantity</small>
                                        <strong><?php echo h($order["quantity"] ?: "N/A"); ?></strong>
                                    </div>

                                    <div>
                                        <small>Due Date</small>
                                        <strong><?php echo h(formatDateOnly($order["due_date"])); ?></strong>
                                    </div>
                                </div>

                                <?php if ($hasFeedback): ?>
                                    <div class="submitted-feedback-box mb-3">
                                        <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-2">
                                            <div class="submitted-stars">
                                                <?php echo renderStars($order["feedback_rating"]); ?>
                                                <span class="ms-1 text-muted">
                                                    <?php echo (int)$order["feedback_rating"]; ?>/5
                                                </span>
                                            </div>

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

                                        <p class="mb-1">
                                            <?php echo h($order["feedback_comment"]); ?>
                                        </p>

                                        <small class="text-muted">
                                            Submitted on: <?php echo h(formatDateOnly($order["feedback_created_at"])); ?>
                                        </small>
                                    </div>
                                <?php else: ?>
                                    <div class="no-feedback-box mb-3">
                                        <i class="fa-regular fa-star me-1"></i>
                                        No feedback submitted yet.
                                    </div>
                                <?php endif; ?>

                                <div class="mt-auto">
                                    <?php if ($canGiveFeedback): ?>
                                        <button 
                                            type="button" 
                                            class="btn btn-primary rounded-pill px-4"
                                            data-bs-toggle="modal"
                                            data-bs-target="#feedbackModal<?php echo (int)$order["id"]; ?>"
                                        >
                                            <?php echo $hasFeedback ? "Edit Feedback" : "Give Feedback"; ?>
                                        </button>
                                    <?php else: ?>
                                        <button type="button" class="btn btn-light border rounded-pill px-4" disabled>
                                            Feedback unavailable
                                        </button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- FEEDBACK MODAL -->
                        <div class="modal fade" id="feedbackModal<?php echo (int)$order["id"]; ?>" tabindex="-1">
                            <div class="modal-dialog modal-dialog-centered">
                                <div class="modal-content border-0 rounded-4">
                                    <form method="POST">
                                        <div class="modal-header">
                                            <div>
                                                <h5 class="modal-title fw-bold">Rate This Shop</h5>
                                                <small class="text-muted">
                                                    <?php echo h($shopName); ?> — <?php echo h($order["order_code"]); ?>
                                                </small>
                                            </div>

                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                        </div>

                                        <div class="modal-body">
                                            <input type="hidden" name="order_id" value="<?php echo (int)$order["id"]; ?>">

                                            <div class="mb-4">
                                                <label class="form-label fw-semibold">Your Rating</label>

                                                <div class="star-rating-input">
                                                    <?php for ($i = 5; $i >= 1; $i--): ?>
                                                        <input 
                                                            type="radio" 
                                                            id="star<?php echo $i; ?>_order<?php echo (int)$order["id"]; ?>" 
                                                            name="feedback_rating" 
                                                            value="<?php echo $i; ?>"
                                                            <?php echo ((int)$order["feedback_rating"] === $i) ? "checked" : ""; ?>
                                                            required
                                                        >
                                                        <label for="star<?php echo $i; ?>_order<?php echo (int)$order["id"]; ?>">
                                                            <i class="fa-solid fa-star"></i>
                                                        </label>
                                                    <?php endfor; ?>
                                                </div>

                                                <small class="text-muted d-block mt-2">
                                                    Choose 1 star as lowest and 5 stars as highest.
                                                </small>
                                            </div>

                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Feedback Comment</label>
                                                <textarea 
                                                    name="feedback_comment" 
                                                    class="form-control" 
                                                    rows="5" 
                                                    placeholder="Write your experience with this shop..."
                                                    required
                                                ><?php echo h($order["feedback_comment"]); ?></textarea>
                                            </div>
                                        </div>

                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-light border" data-bs-dismiss="modal">
                                                Cancel
                                            </button>

                                            <button type="submit" name="submit_feedback" class="btn btn-primary">
                                                Submit Feedback
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>

                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="empty-feedback-card">
                    <i class="fa-solid fa-comment-slash"></i>
                    <h5>No orders found</h5>
                    <p class="text-muted mb-0">
                        You can submit feedback once you have an order.
                    </p>
                </div>
            <?php endif; ?>
        </div>
    </div>

</div>

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

.customer-feedback-page h1 {
    font-size: clamp(30px, 3vw, 42px);
    color: #111827;
}

.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%;
}

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

.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;
}

.order-feedback-card {
    background: #ffffff;
    border: 1px solid #eef0f4;
    border-radius: 20px;
    padding: 20px;
    box-shadow: 0 8px 22px rgba(0, 0, 0, 0.05);
    display: flex;
    flex-direction: column;
}

.order-info-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px;
}

.order-info-grid div {
    background: #f8fafc;
    border: 1px solid #eef0f4;
    border-radius: 14px;
    padding: 12px;
}

.order-info-grid small {
    display: block;
    color: #6b7280;
    font-size: 12px;
    margin-bottom: 4px;
}

.order-info-grid strong {
    color: #111827;
    font-size: 14px;
}

.submitted-feedback-box {
    background: #f8fafc;
    border: 1px solid #e5e7eb;
    border-radius: 16px;
    padding: 14px;
}

.submitted-stars {
    color: #facc15;
}

.no-feedback-box {
    background: #fff7ed;
    border: 1px solid #fed7aa;
    color: #9a3412;
    border-radius: 16px;
    padding: 14px;
    font-weight: 600;
}

.star-rating-input {
    display: inline-flex;
    flex-direction: row-reverse;
    justify-content: flex-end;
    gap: 4px;
}

.star-rating-input input {
    display: none;
}

.star-rating-input label {
    cursor: pointer;
    font-size: 34px;
    color: #d1d5db;
    transition: 0.2s ease;
}

.star-rating-input label:hover,
.star-rating-input label:hover ~ label,
.star-rating-input input:checked ~ label {
    color: #facc15;
}

.empty-feedback-card {
    min-height: 260px;
    background: #f8fafc;
    border: 1px dashed #cbd5e1;
    border-radius: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #6b7280;
    text-align: center;
}

.empty-feedback-card i {
    font-size: 46px;
    color: #9ca3af;
    margin-bottom: 12px;
}

.btn-primary {
    background: #24324d;
    border-color: #24324d;
}

.btn-primary:hover {
    background: #111827;
    border-color: #111827;
}

.success-popup-modal {
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.25);
}

.popup-icon {
    width: 90px;
    height: 90px;
    border-radius: 50%;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 42px;
}

.success-icon {
    background: #ecfdf5;
    color: #22c55e;
    border: 3px solid #bbf7d0;
}

.error-icon {
    background: #fef2f2;
    color: #ef4444;
    border: 3px solid #fecaca;
}

.success-popup-modal h3 {
    color: #111827;
}

.success-popup-modal .btn-primary {
    background: #24324d;
    border-color: #24324d;
    font-weight: 700;
}

@media (max-width: 768px) {
    .order-info-grid {
        grid-template-columns: 1fr;
    }

    .star-rating-input label {
        font-size: 30px;
    }
}
</style>