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

// Require login for this page
requireLogin();

// Handle AJAX requests
if(isset($_POST['action'])) {
    $response = ['status' => 'error', 'message' => 'Invalid action'];
    
    switch($_POST['action']) {
        case 'search':
            $userid = $conn->real_escape_string($_POST['userid']);
            if(!empty($userid)) {
                $query = "SELECT * FROM khate WHERE byabaharkarta = ?";
                $stmt = $conn->prepare($query);
                $stmt->bind_param("s", $userid);
                $stmt->execute();
                $result = $stmt->get_result();
                
                if($result->num_rows > 0) {
                    $data = $result->fetch_assoc();
                    $response = [
                        'status' => 'success',
                        'data' => $data
                    ];
                } else {
                    $response = [
                        'status' => 'error',
                        'message' => 'No records found for this User ID!'
                    ];
                }
            }
            break;
            
        case 'update':
            $userid = $conn->real_escape_string($_POST['userid']);
            $account = $conn->real_escape_string($_POST['khatehesaru']);
            $number = $conn->real_escape_string($_POST['duravani']);
            $ifsc = $conn->real_escape_string($_POST['kod']);
            
            $update_sql = "UPDATE khate SET khatehesaru = ?, duravani = ?, kod = ? WHERE byabaharkarta = ?";
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("ssss", $account, $number, $ifsc, $userid);
            
            if($stmt->execute()) {
                $response = [
                    'status' => 'success',
                    'message' => 'Bank details updated successfully!'
                ];
            } else {
                $response = [
                    'status' => 'error',
                    'message' => 'Failed to update bank details!'
                ];
            }
            break;
    }
    
    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">
                        Modify Bank Details
                    </h2>
                </div>
            </div>

            <!-- Search Form -->
            <div class="col-span-12 lg:col-span-12">
                <div class="card">
                    <div class="flex flex-col items-center space-y-4 border-b border-slate-200 p-4 dark:border-navy-500 sm:flex-row sm:justify-between sm:space-y-0 sm:px-5">
                        <h2 class="text-lg font-medium tracking-wide text-slate-700 dark:text-navy-100">
                            Search User
                        </h2>
                    </div>
                    <div class="p-4 sm:p-5">
                        <div class="flex flex-col space-y-4">
                            <label class="block">
                                <span class="font-medium text-slate-600 dark:text-navy-100">User ID</span>
                                <div class="flex space-x-2">
                                    <input type="number" 
                                           id="userid"
                                           class="form-input 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"
                                           placeholder="Enter User ID"
                                           required>
                                    <button type="button"
                                            id="searchUser"
                                            class="btn mt-1.5 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">
                                        Search
                                    </button>
                                </div>
                            </label>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Results Table -->
            <div class="col-span-12" id="resultsSection" style="display: none;">
                <div class="card">
                    <div class="flex flex-col justify-between space-y-4 px-4 py-4 sm:flex-row sm:items-center sm:space-y-0 sm:px-5">
                        <h2 class="text-lg font-medium tracking-wide text-slate-700 dark:text-navy-100">
                            Bank Details
                        </h2>
                    </div>
                    <div class="border-t border-slate-200 dark:border-navy-500">
                        <div class="min-w-full overflow-x-auto">
                            <table class="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 lg:px-5">Bank Name</th>
                                        <th class="whitespace-nowrap px-3 py-3 font-semibold text-slate-800 dark:text-navy-100 lg:px-5">Account Number</th>
                                        <th class="whitespace-nowrap px-3 py-3 font-semibold text-slate-800 dark:text-navy-100 lg:px-5">IFSC Code</th>
                                        <th class="whitespace-nowrap px-3 py-3 font-semibold text-slate-800 dark:text-navy-100 lg:px-5">Action</th>
                                    </tr>
                                </thead>
                                <tbody id="resultsBody">
                                    <!-- Results will be inserted here -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>

<!-- Modal -->
<div id="updateModal" 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 transition-opacity duration-300"></div>
    <div class="relative w-full max-w-lg origin-top rounded-lg bg-white transition-all duration-300 dark:bg-navy-700">
        <div class="flex justify-between rounded-t-lg bg-slate-200 px-4 py-3 dark:bg-navy-800 sm:px-5">
            <h3 class="text-base font-medium text-slate-700 dark:text-navy-100">
                Update Bank Details
            </h3>
            <button onclick="closeModal()" class="btn -mr-1.5 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">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-4.5 w-4.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
            </button>
        </div>
        <div class="px-4 py-4 sm:px-5">
            <form id="updateForm" class="space-y-4">
                <input type="hidden" id="update_userid">
                <label class="block">
                    <span class="font-medium text-slate-600 dark:text-navy-100">Bank Name</span>
                    <input type="text" 
                           id="update_khatehesaru"
                           class="form-input mt-1.5 w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2"
                           required>
                </label>
                <label class="block">
                    <span class="font-medium text-slate-600 dark:text-navy-100">Account Number</span>
                    <input type="text" 
                           id="update_duravani"
                           class="form-input mt-1.5 w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2"
                           required>
                </label>
                <label class="block">
                    <span class="font-medium text-slate-600 dark:text-navy-100">IFSC Code</span>
                    <input type="text" 
                           id="update_kod"
                           class="form-input mt-1.5 w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2"
                           required>
                </label>
                <div class="flex justify-end space-x-2">
                    <button type="button"
                            onclick="closeModal()"
                            class="btn space-x-2 bg-slate-150 font-medium text-slate-800 hover:bg-slate-200 focus:bg-slate-200 active:bg-slate-200/80 dark:bg-navy-500 dark:text-navy-50 dark:hover:bg-navy-450 dark:focus:bg-navy-450 dark:active:bg-navy-450/90">
                        Cancel
                    </button>
                    <button type="submit"
                            class="btn space-x-2 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">
                        Update
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

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

<script>
// Function to show alert messages
function showAlert(message, type = 'error') {
    const alertClass = type === 'success' ? 'bg-success/10 text-success' : 'bg-error/10 text-error';
    const alertHtml = `
        <div class="alert col-span-12 lg:col-span-12 flex rounded-lg border border-${type}/30 ${alertClass} py-4 px-4 my-4">
            <div class="flex flex-1 items-center space-x-3">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                        d="${type === 'success' ? 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z' : 'M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z'}" />
                </svg>
                <span class="text-base">${message}</span>
            </div>
        </div>
    `;
    
    const mainContent = document.querySelector('.grid.grid-cols-12');
    const searchForm = document.querySelector('.col-span-12.lg\\:col-span-12');
    mainContent.insertBefore(document.createRange().createContextualFragment(alertHtml), searchForm);
    
    // Remove alert after 5 seconds
    setTimeout(() => {
        document.querySelector('.alert').remove();
    }, 5000);
}

// Function to update the results table
function updateResultsTable(data) {
    const resultsBody = document.getElementById('resultsBody');
    const resultsSection = document.getElementById('resultsSection');
    
    resultsBody.innerHTML = `
        <tr class="border-y border-transparent border-b-slate-200 dark:border-b-navy-500">
            <td class="whitespace-nowrap px-4 py-3 sm:px-5">${data.khatehesaru}</td>
            <td class="whitespace-nowrap px-4 py-3 sm:px-5">${data.duravani}</td>
            <td class="whitespace-nowrap px-4 py-3 sm:px-5">${data.kod}</td>
            <td class="whitespace-nowrap px-4 py-3 sm:px-5">
                <button onclick="openUpdateModal('${data.byabaharkarta}', '${data.khatehesaru}', '${data.duravani}', '${data.kod}')"
                        class="btn h-8 w-8 rounded-full p-0 text-info hover:bg-info/20 focus:bg-info/20 active:bg-info/25">
                    <i class="fa fa-edit"></i>
                </button>
            </td>
        </tr>
    `;
    
    resultsSection.style.display = 'block';
}

// Function to open update modal
function openUpdateModal(userid, khatehesaru, duravani, kod) {
    document.getElementById('update_userid').value = userid;
    document.getElementById('update_khatehesaru').value = khatehesaru;
    document.getElementById('update_duravani').value = duravani;
    document.getElementById('update_kod').value = kod;
    document.getElementById('updateModal').style.display = 'flex';
}

// Function to close modal
function closeModal() {
    document.getElementById('updateModal').style.display = 'none';
}

// Handle search button click
document.getElementById('searchUser').addEventListener('click', function() {
    const userid = document.getElementById('userid').value;
    if (!userid) {
        showAlert('Please enter a User ID');
        return;
    }

    // Show loading state
    this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Searching...';
    this.disabled = true;

    const formData = new FormData();
    formData.append('action', 'search');
    formData.append('userid', userid);

    fetch(window.location.href, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        // Reset button state
        this.innerHTML = 'Search';
        this.disabled = false;

        if (data.status === 'success') {
            updateResultsTable(data.data);
        } else {
            showAlert(data.message);
            document.getElementById('resultsSection').style.display = 'none';
        }
    })
    .catch(error => {
        // Reset button state
        this.innerHTML = 'Search';
        this.disabled = false;
        showAlert('Failed to search. Please try again.');
        console.error('Error:', error);
    });
});

// Handle update form submission
document.getElementById('updateForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const submitBtn = this.querySelector('button[type="submit"]');
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';
    submitBtn.disabled = true;

    const formData = new FormData();
    formData.append('action', 'update');
    formData.append('userid', document.getElementById('update_userid').value);
    formData.append('khatehesaru', document.getElementById('update_khatehesaru').value);
    formData.append('duravani', document.getElementById('update_duravani').value);
    formData.append('kod', document.getElementById('update_kod').value);

    fetch(window.location.href, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        // Reset button state
        submitBtn.innerHTML = 'Update';
        submitBtn.disabled = false;

        if (data.status === 'success') {
            closeModal();
            showAlert(data.message, 'success');
            // Refresh the results
            document.getElementById('searchUser').click();
        } else {
            showAlert(data.message);
        }
    })
    .catch(error => {
        // Reset button state
        submitBtn.innerHTML = 'Update';
        submitBtn.disabled = false;
        showAlert('Failed to update. Please try again.');
        console.error('Error:', error);
    });
});

// Close modal when clicking outside
document.getElementById('updateModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeModal();
    }
});
</script> 