<?php
require_once 'includes/config.php';
$pageTitle = "Bank Modification";
$curdate = date('Y-m-d h:i:s');
$sidebar = "Support";

// Require login for this page
requireLogin();

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $response = ['success' => false, 'message' => ''];
    
    if ($_POST['action'] === 'update_status') {
        $issueId = $_POST['issue_id'] ?? null;
        $reply = $_POST['reply'] ?? '';

        if (empty($issueId)) {
            $response['message'] = "Issue ID is required.";
        } else {
            try {
                // First check if the issue exists
                $checkStmt = $conn->prepare("SELECT id FROM issues WHERE id = ?");
                if ($checkStmt) {
                    $checkStmt->bind_param("i", $issueId);
                    $checkStmt->execute();
                    $result = $checkStmt->get_result();
                    
                    if ($result->num_rows === 0) {
                        $response['message'] = "Issue #$issueId not found.";
                    } else {
                        // Update the issue status and reply
                        $updateStmt = $conn->prepare("UPDATE issues SET status = 'Resolved', reply = ? WHERE id = ?");
                        if ($updateStmt) {
                            $updateStmt->bind_param("si", $reply, $issueId);
                            if ($updateStmt->execute()) {
                                $response['success'] = true;
                                $response['message'] = "Issue #$issueId has been resolved successfully.";
                            } else {
                                $response['message'] = "Failed to update issue #$issueId: " . $updateStmt->error;
                            }
                            $updateStmt->close();
                        } else {
                            $response['message'] = "Failed to prepare update statement: " . $conn->error;
                        }
                    }
                    $checkStmt->close();
                } else {
                    $response['message'] = "Failed to prepare check statement: " . $conn->error;
                }
            } catch (Exception $e) {
                $response['message'] = "An error occurred: " . $e->getMessage();
            }
        }
    } elseif ($_POST['action'] === 'fetch_issues') {
        $filter = $_POST['filter'] ?? 'all';
        try {
            $sql = "SELECT * FROM issues WHERE issue_type IN ('bankModification', 'bankChange', 'bankNameChange', 'bankNameModify', 'bankProblem')";
            if ($filter === 'pending') {
                $sql .= " AND status = 'Pending'";
            } elseif ($filter === 'resolved') {
                $sql .= " AND status = 'Resolved'";
            }
            $sql .= " ORDER BY created_at DESC";
            
            $result = $conn->query($sql);
            $issues = [];
            
            if ($result && $result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    $issues[] = $row;
                }
                $response['success'] = true;
                $response['issues'] = $issues;
            } else {
                $response['success'] = true;
                $response['message'] = "No bank modification requests found.";
                $response['issues'] = [];
            }
        } catch (Exception $e) {
            $response['message'] = "An error occurred while fetching issues: " . $e->getMessage();
        }
    }
    
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

include_once 'includes/header.php';
?>

<div id="root" class="min-h-100vh flex grow bg-slate-100 dark:bg-navy-900" x-cloak>
    <?php include('includes/pages/sidebar1.php'); ?>

    <!-- Main Content Wrapper -->
    <main class="main-content w-full pb-8">
        <div class="mt-4 grid grid-cols-12 gap-4 px-[var(--margin-x)] transition-all duration-[.25s] sm:mt-5 sm:gap-5 lg:mt-6 lg:gap-6">
            <div class="col-span-12">
                <div class="flex items-center justify-between space-x-2">
                    <h2 class="text-base font-medium tracking-wide text-slate-800 line-clamp-1 dark:text-navy-100">
                        Bank Name Modification Management
                    </h2>
                </div>
            </div>

            <!-- Alert Message -->
            <div id="alertMessage" class="col-span-12" style="display: none;">
                <div class="alert flex rounded-lg border border-success/30 bg-success/10 text-success p-3">
                    <i class="fa fa-check-circle mr-2 mt-1"></i>
                    <p id="alertText"></p>
                </div>
            </div>

            <!-- Issues Table -->
            <div class="col-span-12">
                <div class="card">
                    <div class="flex items-center justify-between p-4">
                        <h2 class="font-medium tracking-wide text-slate-700 dark:text-navy-100">
                            Bank Name Modification Requests
                        </h2>
                        <div x-data="{activeTab:'all'}" class="tabs">
                            <div class="tabs-list flex">
                                <button @click="activeTab = 'all'; fetchIssues('all')" class="btn shrink-0 px-3 py-1.5 font-medium" :class="activeTab === 'all' ? 'bg-primary/10 text-primary dark:bg-accent-light/10 dark:text-accent-light' : 'hover:text-slate-800 focus:text-slate-800 dark:hover:text-navy-100 dark:focus:text-navy-100'">
                                    All
                                </button>
                                <button @click="activeTab = 'pending'; fetchIssues('pending')" class="btn shrink-0 px-3 py-1.5 font-medium" :class="activeTab === 'pending' ? 'bg-primary/10 text-primary dark:bg-accent-light/10 dark:text-accent-light' : 'hover:text-slate-800 focus:text-slate-800 dark:hover:text-navy-100 dark:focus:text-navy-100'">
                                    Pending
                                </button>
                                <button @click="activeTab = 'resolved'; fetchIssues('resolved')" class="btn shrink-0 px-3 py-1.5 font-medium" :class="activeTab === 'resolved' ? 'bg-primary/10 text-primary dark:bg-accent-light/10 dark:text-accent-light' : 'hover:text-slate-800 focus:text-slate-800 dark:hover:text-navy-100 dark:focus:text-navy-100'">
                                    Resolved
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="p-4">
                        <div class="min-w-full overflow-x-auto">
                            <table class="is-hoverable w-full text-left">
                                <thead>
                                    <tr class="border-y border-transparent border-b-slate-200 dark:border-b-navy-500">
                                        <th class="whitespace-nowrap px-3 py-3 font-semibold text-slate-800 dark:text-navy-100">ID</th>
                                        <th class="whitespace-nowrap px-3 py-3 font-semibold text-slate-800 dark:text-navy-100">User ID</th>
                                        <th class="whitespace-nowrap px-3 py-3 font-semibold text-slate-800 dark:text-navy-100">Order No</th>
                                        <th class="whitespace-nowrap px-3 py-3 font-semibold text-slate-800 dark:text-navy-100">Current Bank Name</th>
                                        <th class="whitespace-nowrap px-3 py-3 font-semibold text-slate-800 dark:text-navy-100">New Bank Name</th>
                                        <th class="whitespace-nowrap px-3 py-3 font-semibold text-slate-800 dark:text-navy-100">Status</th>
                                        <th class="whitespace-nowrap px-3 py-3 font-semibold text-slate-800 dark:text-navy-100">Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="issuesTableBody">
                                    <!-- Table content will be loaded dynamically -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>

<!-- Response Modal -->
<div id="responseModal" class="fixed inset-0 z-[100] flex flex-col items-center justify-center overflow-hidden px-4 py-6 sm:px-5" style="display: none;">
    <div class="absolute inset-0 bg-slate-900/60 backdrop-blur transition-opacity duration-300"></div>
    <div class="relative w-full max-w-lg rounded-lg bg-white px-4 py-10 text-center transition-all duration-300 dark:bg-navy-700 sm:px-5">
        <div class="absolute right-4 top-4">
            <button onclick="closeModal()" class="btn h-7 w-7 rounded-full p-0 hover:bg-slate-300/20 focus:bg-slate-300/20 active:bg-slate-300/25 dark:hover:bg-navy-300/20 dark:focus:bg-navy-300/20 dark:active:bg-navy-300/25">
                <i class="fa fa-times"></i>
            </button>
        </div>
        <div class="mt-4">
            <h3 class="text-xl font-medium text-slate-700 dark:text-navy-100">Send Response</h3>
            <p class="mt-2 text-slate-500 dark:text-navy-300">Enter your response for this bank name modification request</p>
        </div>
        <div class="mt-6">
            <div class="space-y-4">
                <div>
                    <label class="block">
                        <span class="font-medium text-slate-600 dark:text-navy-100">Response Message</span>
                        <textarea id="responseInput" class="form-textarea mt-1.5 w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 placeholder:text-slate-400/70 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" rows="3" placeholder="Enter your response message"></textarea>
                    </label>
                </div>
            </div>
        </div>
        <div class="mt-8 flex justify-center space-x-3">
            <button onclick="closeModal()" class="btn min-w-[7rem] border border-slate-300 font-medium text-slate-700 hover:bg-slate-150 focus:bg-slate-150 active:bg-slate-150/80 dark:border-navy-450 dark:text-navy-100 dark:hover:bg-navy-500 dark:focus:bg-navy-500 dark:active:bg-navy-500/90">
                Cancel
            </button>
            <button onclick="submitResponse()" class="btn min-w-[7rem] bg-primary font-medium text-white hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90 dark:bg-accent dark:hover:bg-accent-focus dark:focus:bg-accent-focus dark:active:bg-accent/90">
                Submit
            </button>
        </div>
    </div>
</div>

<?php include('includes/footer.php'); ?>

<script>
let currentIssueId = null;

// Function to show alert message
function showAlert(message, type = 'success') {
    const alertDiv = document.getElementById('alertMessage');
    const alertText = document.getElementById('alertText');
    alertDiv.className = `col-span-12 alert flex rounded-lg border border-${type}/30 bg-${type}/10 text-${type}`;
    alertText.textContent = message;
    alertDiv.style.display = 'block';
    setTimeout(() => {
        alertDiv.style.display = 'none';
    }, 5000);
}

// Function to format date
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleString();
}

// Function to show modal
function showModal(issueId) {
    currentIssueId = issueId;
    const modal = document.getElementById('responseModal');
    document.getElementById('responseInput').value = '';
    modal.style.display = 'flex';
}

// Function to close modal
function closeModal() {
    const modal = document.getElementById('responseModal');
    modal.style.display = 'none';
    document.getElementById('responseInput').value = '';
    currentIssueId = null;
}

// Function to submit response
function submitResponse() {
    if (!currentIssueId) return;
    
    const reply = document.getElementById('responseInput').value;
    const formData = new FormData();
    formData.append('action', 'update_status');
    formData.append('issue_id', currentIssueId);
    formData.append('reply', reply);

    fetch('', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert(data.message);
            closeModal();
            fetchIssues(); // Refresh the table
        } else {
            showAlert(data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('An error occurred while updating the status.', 'error');
    });
}

// Function to fetch and display issues
function fetchIssues(filter = 'all') {
    const formData = new FormData();
    formData.append('action', 'fetch_issues');
    formData.append('filter', filter);

    fetch('', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        const tableBody = document.getElementById('issuesTableBody');
        tableBody.innerHTML = '';

        if (data.success && data.issues.length > 0) {
            data.issues.forEach(issue => {
                const row = document.createElement('tr');
                row.className = 'border-y border-transparent border-b-slate-200 dark:border-b-navy-500';

                const statusClass = {
                    'Resolved': 'text-success',
                    'Pending': 'text-warning'
                }[issue.status] || 'text-slate-600';

                row.innerHTML = `
                    <td class="whitespace-nowrap px-4 py-3 text-slate-600 dark:text-navy-100">${issue.id}</td>
                    <td class="whitespace-nowrap px-4 py-3 text-slate-600 dark:text-navy-100">${issue.userid}</td>
                    <td class="whitespace-nowrap px-4 py-3 text-slate-600 dark:text-navy-100">${issue.deposit_order_no}</td>
                    <td class="whitespace-nowrap px-4 py-3 text-slate-600 dark:text-navy-100">${issue.current_bank_name}</td>
                    <td class="whitespace-nowrap px-4 py-3 text-slate-600 dark:text-navy-100">${issue.new_bank_name}</td>
                    <td class="whitespace-nowrap px-4 py-3">
                        <div class="badge space-x-2.5 px-0 ${statusClass}">
                            <div class="h-2 w-2 rounded-full bg-current"></div>
                            <span>${issue.status}</span>
                        </div>
                    </td>
                    <td class="whitespace-nowrap px-4 py-3">
                        ${issue.status === 'Pending' ? `
                            <button onclick="showModal(${issue.id})" class="btn bg-primary font-medium text-white hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90">
                                Respond
                            </button>
                        ` : ''}
                    </td>
                `;
                tableBody.appendChild(row);
            });
        } else {
            tableBody.innerHTML = `
                <tr>
                    <td colspan="7" class="px-4 py-3 text-center text-slate-600 dark:text-navy-100">
                        No bank modification requests found.
                    </td>
                </tr>
            `;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('An error occurred while fetching issues.', 'error');
    });
}

// Initial load of issues
document.addEventListener('DOMContentLoaded', () => {
    fetchIssues();
});
</script> 