<?php
// Start the session if it's not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Include necessary files
include('sidebar.php');
include('header.php');
include('db_connection.php');

try {
    // Fetch and display data
    $sql = "
    SELECT 
        sc.id, 
        sc.Area, 
        sc.min_price, 
        sc.max_price,
        sc.start_date, 
        sc.end_date, 
        sc.remarks,
        su.name 
    FROM 
        submit_connection AS sc
    JOIN 
        sign_up AS su 
    ON 
        sc.user_id = su.id";

    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $submitConnectionRecords = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo "Error fetching data: " . $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Get the remarks from the submitted form
        $remarks = isset($_POST['remarks']) ? trim($_POST['remarks']) : null;

        // Validate the input
        if (empty($remarks)) {
            echo "<script>alert('Accept successfull.'); window.history.back();</script>";
            exit; // Stop further execution
        }

        // Update the remarks column for the latest record (or any desired logic)
        $updateSql = "UPDATE submit_connection 
                      SET remarks = :remarks 
                      WHERE id = (SELECT MAX(id) FROM submit_connection)";
        $updateStmt = $conn->prepare($updateSql);

        // Bind the parameter
        $updateStmt->bindParam(':remarks', $remarks, PDO::PARAM_STR);

        // Execute the update query
        if ($updateStmt->execute()) {
            echo "<p style='color: green;'>Remarks updated successfully for the latest record.</p>";
        } else {
            throw new Exception("Failed to update remarks.");
        }
    } catch (Exception $e) {
        echo "<p style='color: red;'>Error updating remarks: " . $e->getMessage() . "</p>";
    }
}


//accept button
ob_start(); // Start output buffering

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['accept'])) {
    // Validate the ID
    $id = intval($_POST['id']); // Get the record ID from the form

    try {
        // Prepare the update query
        $stmt = $conn->prepare("UPDATE submit_connection SET is_accepted = 1 WHERE id = ?");

        // Execute the query with the provided ID
        if ($stmt->execute([$id])) {
            // Redirect back to the product page with a success message
            // header("Location: product.php?status=success");
            exit; // Ensure no further code is executed
        } else {
            echo "Failed to accept the record.";
        }
    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
}

ob_end_flush(); // End output buffering

?>




<!DOCTYPE html>
<html lang="en">

<style>
    /* Modal styling */
    .modal {
        display: none;
        /* Hidden by default */
        position: fixed;
        z-index: 1;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0, 0, 0, 0.5);
        /* Black background with transparency */
    }

    .modal-content {
        background-color: #fefefe;
        margin: 15% auto;
        padding: 20px;
        border: 1px solid #888;
        width: 50%;
        /* Width of the modal */
        border-radius: 5px;
    }

    .close {
        color: #aaa;
        float: right;
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
    }

    .close:hover,
    .close:focus {
        color: black;
        text-decoration: none;
        cursor: pointer;
    }

    textarea {
        width: 100%;
        margin-top: 10px;
        padding: 10px;
        border-radius: 5px;
        border: 1px solid #ccc;
    }
</style>

<body>

    <!-- Table Start -->
    <div class="container-fluid pt-4 px-4">
        <div class="row g-4">
            <div class="col-12">
                <div class="bg-light rounded h-100 p-4">
                    <h6 class="mb-4">Submit Connection Table</h6>
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th scope="col" style="text-align: center;">#</th>
                                    <th scope="col" style="text-align: center;">Area</th>
                                    <th scope="col" style="text-align: center;">Min Price</th>
                                    <th scope="col" style="text-align: center;">Max Price</th>
                                    <th scope="col" style="text-align: center;">Start Date</th>
                                    <th scope="col" style="text-align: center;">End Date</th>
                                    <th scope="col" style="text-align: center;">Name</th>
                                    <th scope="col" style="text-align: center;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $serialNumber = 1; // Initialize serial number
                                if (!empty($submitConnectionRecords)) {
                                    // Output data of each row
                                    foreach ($submitConnectionRecords as $record) {
                                        echo "<tr>";
                                        echo "<th scope='row' style='text-align: center;'>" . $serialNumber++ . "</th>";
                                        echo "<td style='text-align: center;'>" . htmlspecialchars($record['Area']) . "</td>";
                                        echo "<td style='text-align: center;'>" . htmlspecialchars($record['min_price']) . "</td>";
                                        echo "<td style='text-align: center;'>" . htmlspecialchars($record['max_price']) . "</td>";
                                        echo "<td style='text-align: center;'>" . htmlspecialchars($record['start_date']) . "</td>";
                                        echo "<td style='text-align: center;'>" . htmlspecialchars($record['end_date']) . "</td>";
                                        echo "<td style='text-align: center;'>" . htmlspecialchars($record['name']) . "</td>";
                                        echo "<td style='text-align: center;'>
                <form method='POST' action='submit_connection.php' style='display:inline;'>
                    <input type='hidden' name='id' value='" . htmlspecialchars($record['id']) . "'>
                    <button class='btn btn-success' type='submit' name='accept'>Accept</button>
                </form>
                <button class='btn btn-danger' onclick='rejectRecord(" . htmlspecialchars($record['id']) . ")'>Reject</button>
                <button class='btn btn-warning' onclick='openRemarksModal(" . htmlspecialchars($record['id']) . ")'>Remarks</button>
            </td>";
                                        echo "</tr>"; // Close the table row
                                    }
                                } else {
                                    echo "<tr><td colspan='8' style='text-align: center;'>No records found</td></tr>";
                                }
                                ?>
                            </tbody>

                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Table End -->

    <!-- Modal -->
    <div id="remarksModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeRemarksModal()">&times;</span>
            <form method="POST" action="submit_connection.php" onsubmit="return validateRemarks()">
                <p>Add your remarks below:</p>
                <textarea id="remarksText" name="remarks" rows="4" cols="50" placeholder="Enter your remarks here" required></textarea><br>
                <!-- Pass the record ID dynamically -->
                <input type="hidden" name="record_id" id="recordId" value="">
                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </div>
    </div>





    <script>
        function openRemarksModal(recordId) {
            document.getElementById('recordId').value = recordId; // Set the record ID dynamically
            document.getElementById('remarksModal').style.display = 'block'; // Show the modal
        }

        function closeRemarksModal() {
            document.getElementById('remarksModal').style.display = 'none'; // Hide the modal
        }

        function validateRemarks() {
            const remarks = document.getElementById('remarksText').value.trim();
            if (!remarks) {
                alert("Remarks cannot be empty.");
                return false;
            }
            return true;
        }


        // Submit remarks
        function submitRemarks() {
            const modal = document.getElementById("remarksModal");
            const recordId = modal.getAttribute("data-record-id"); // Get record ID
            const remarks = document.getElementById("remarksText").value;

            if (remarks.trim() === "") {
                alert("Please enter your remarks.");
                return;
            }

            // Handle the submission logic here (e.g., send to the server via AJAX)
            console.log("Record ID:", recordId);
            console.log("Remarks:", remarks);

            alert("Remarks submitted successfully!");

            // Close modal after submission
            closeRemarksModal();
        }
    </script>

</body>

</html>