<?php
// admin/update_paybills.php - Update M-Pesa Paybills
require_once '../src/Database.php';
require_once '../src/Auth.php';

$auth = new Auth();
$auth->requireLogin();

$db = new Database();
$conn = $db->getConnection();

// Handle form submission
$update_message = '';
$update_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    if ($action === 'update_paybill') {
        $id = $_POST['paybill_id'] ?? null;
        $business_name = $_POST['business_name'] ?? '';
        $account_ref = $_POST['account_ref'] ?? '';
        $transaction_type = $_POST['transaction_type'] ?? '';

        if ($id && $account_ref && $transaction_type) {
            try {
                $stmt = $conn->prepare('UPDATE ussd_mpesa_credentials SET name = ?, party_b = ?, transaction_type = ? WHERE id = ?');
                $stmt->execute([$business_name, $account_ref, $transaction_type, $id]);
                $update_message = 'Paybill updated successfully!';
                $update_type = 'success';
            } catch (Exception $e) {
                $update_message = 'Error updating paybill: ' . $e->getMessage();
                $update_type = 'error';
            }
        } else {
            $update_message = 'Please fill in all required fields';
            $update_type = 'error';
        }
    }
}

// Fetch all paybills
$paybills = [];
try {
    $stmt = $conn->query('SELECT * FROM ussd_mpesa_credentials ORDER BY id DESC');
    $paybills = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // Handle error
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Update Paybills - USSD System</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100">
    <?php include 'sidebar.php'; ?>
    <div class="md:ml-64 min-h-screen">
        <!-- Header -->
        <div class="bg-white shadow-md p-4 md:p-6 border-b border-gray-200">
            <div>
                <h1 class="text-3xl font-bold text-gray-800">Update Paybills</h1>
                <p class="text-gray-600 text-sm mt-1">Manage M-Pesa paybill credentials and transaction types</p>
            </div>
        </div>

        <!-- Content -->
        <div class="p-4 md:p-8">
            <!-- Messages -->
            <?php if ($update_message): ?>
            <div class="mb-6 p-4 rounded-lg border-l-4 <?php echo $update_type === 'success' ? 'bg-green-50 border-green-500 text-green-700' : 'bg-red-50 border-red-500 text-red-700'; ?>">
                <div class="flex items-center">
                    <svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>
                    </svg>
                    <?php echo htmlspecialchars($update_message); ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Paybills Table -->
            <div class="bg-white rounded-lg shadow-md overflow-hidden">
                <div class="p-6 border-b border-gray-200">
                    <h2 class="text-xl font-bold text-gray-800">Paybills List</h2>
                    <p class="text-gray-600 text-sm mt-1">Click on a paybill to edit it</p>
                </div>

                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50 border-b border-gray-200">
                            <tr>
                                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">ID</th>
                                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">Business Name</th>
                                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">Paybill Number</th>
                                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">Account Reference</th>
                                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">Transaction Type</th>
                                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($paybills)): ?>
                                <?php foreach ($paybills as $paybill): ?>
                                <tr class="border-b border-gray-200 hover:bg-gray-50 transition">
                                    <td class="px-6 py-3 text-sm text-gray-900"><?php echo htmlspecialchars($paybill['id']); ?></td>
                                    <td class="px-6 py-3 text-sm text-gray-700"><?php echo htmlspecialchars($paybill['name'] ?? '-'); ?></td>
                                    <td class="px-6 py-3 text-sm font-mono text-gray-900"><?php echo htmlspecialchars($paybill['shortcode']); ?></td>
                                    <td class="px-6 py-3 text-sm text-gray-700"><?php echo htmlspecialchars($paybill['party_b'] ?? '-'); ?></td>
                                    <td class="px-6 py-3 text-sm">
                                        <span class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-xs font-semibold">
                                            <?php echo htmlspecialchars($paybill['transaction_type'] ?? 'Not Set'); ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-3 text-sm">
                                        <button onclick="editPaybill(<?php echo htmlspecialchars(json_encode($paybill)); ?>)" class="text-blue-600 hover:text-blue-800 font-semibold">Edit</button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                            <tr>
                                <td colspan="6" class="px-6 py-8 text-center text-gray-500">
                                    <svg class="w-12 h-12 mx-auto mb-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                                    </svg>
                                    <p class="text-lg">No paybills found</p>
                                    <p class="text-sm">Add a paybill to get started</p>
                                </td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Edit Modal -->
            <div id="editModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
                <div class="bg-white rounded-lg shadow-xl max-w-md w-full">
                    <div class="bg-gradient-to-r from-blue-600 to-blue-700 px-6 py-4">
                        <h3 class="text-xl font-bold text-white">Edit Paybill</h3>
                    </div>

                    <form method="POST" class="p-6 space-y-4">
                        <input type="hidden" name="action" value="update_paybill">
                        <input type="hidden" name="paybill_id" id="paybill_id" value="">

                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-1">Business Name</label>
                            <input type="text" name="business_name" id="business_name" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>

                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-1">Account Reference *</label>
                            <input type="text" name="account_ref" id="account_ref" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>

                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-1">Transaction Type *</label>
                            <select name="transaction_type" id="transaction_type" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="">Select Transaction Type</option>
                                <option value="CustomerBuyGoodsOnline">Customer Buy Goods Online</option>
                                <option value="CustomerPayBillOnline">Customer Pay Bill Online</option>
                            </select>
                        </div>

                        <div class="flex gap-3 pt-4">
                            <button type="submit" class="flex-1 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg font-semibold transition">Update</button>
                            <button type="button" onclick="closeEditModal()" class="flex-1 bg-gray-300 hover:bg-gray-400 text-gray-800 px-4 py-2 rounded-lg font-semibold transition">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        function editPaybill(paybill) {
            document.getElementById('paybill_id').value = paybill.id;
            document.getElementById('business_name').value = paybill.business_name || '';
            document.getElementById('account_ref').value = paybill.account_ref || '';
            document.getElementById('transaction_type').value = paybill.transaction_type || '';
            document.getElementById('editModal').classList.remove('hidden');
        }

        function closeEditModal() {
            document.getElementById('editModal').classList.add('hidden');
        }

        // Close modal when clicking outside
        document.getElementById('editModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeEditModal();
            }
        });

        // Close message after 5 seconds
        window.addEventListener('load', function() {
            const messageElement = document.querySelector('[class*="bg-green-50"], [class*="bg-red-50"]');
            if (messageElement) {
                setTimeout(() => {
                    messageElement.style.display = 'none';
                }, 5000);
            }
        });
    </script>
</body>
</html>
