<?php
session_start();
require 'db_connection.php'; // Ensure this file contains a valid database connection

if (isset($_GET['consultation_id']) && isset($_SESSION['user_id'])) {
    $consultationId = intval($_GET['consultation_id']);
    $userId = intval($_SESSION['user_id']);

    // Fetch consultation details
    $sql = "SELECT consultation_name, consultation_fee FROM consultations WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $consultationId);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $consultation = $result->fetch_assoc();
        $consultationName = htmlspecialchars($consultation['consultation_name']);
        $consultationFee = floatval($consultation['consultation_fee']);

        // Fetch user's wallet balance
        $walletSql = "SELECT wallet FROM customer WHERE id = ?";
        $walletStmt = $conn->prepare($walletSql);
        $walletStmt->bind_param("i", $userId);
        $walletStmt->execute();
        $walletResult = $walletStmt->get_result();
        $userWallet = $walletResult->fetch_assoc()['wallet'];
        ?>
        
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Consultation Details</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    background-color: #f9f9f9;
                    padding: 20px;
                }
                .container {
                    max-width: 600px;
                    margin: 0 auto;
                    background: #fff;
                    padding: 20px;
                    border-radius: 10px;
                    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                }
                .btn {
                    padding: 10px 20px;
                    margin: 10px 5px 0;
                    font-size: 14px;
                    border: none;
                    border-radius: 5px;
                    cursor: pointer;
                }
                .btn-confirm {
                    background-color: #28a745;
                    color: #fff;
                }
                .btn-cancel {
                    background-color: #dc3545;
                    color: #fff;
                }
                .btn-confirm:hover {
                    background-color: #218838;
                }
                .btn-cancel:hover {
                    background-color: #c82333;
                }
            </style>
        </head>
        <body>
            <div class="container">
                <h1>Consultation Details</h1>
                <p><strong>Consultation Name:</strong> <?= $consultationName ?></p>
                <p><strong>Consultation Fee:</strong> ₦<?= number_format($consultationFee, 2) ?></p>
                <p><strong>Your Wallet Balance:</strong> ₦<?= number_format($userWallet, 2) ?></p>

                <?php if ($userWallet >= $consultationFee): ?>
                    <form method="POST">
                        <button type="submit" name="confirm" class="btn btn-confirm">Confirm</button>
                        <button type="submit" name="cancel" class="btn btn-cancel">Cancel</button>
                    </form>
                <?php else: ?>
                    <p style="color: red;">Insufficient balance. <a href="account.php">Recharge your wallet</a>.</p>
                <?php endif; ?>
            </div>
        </body>
        </html>

        <?php
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (isset($_POST['confirm'])) {
                // Deduct fee from wallet
                $newWalletBalance = $userWallet - $consultationFee;
                $updateWalletSql = "UPDATE customer SET wallet = ? WHERE id = ?";
                $updateWalletStmt = $conn->prepare($updateWalletSql);
                $updateWalletStmt->bind_param("di", $newWalletBalance, $userId);

                if ($updateWalletStmt->execute()) {
                    // Insert consultation record
                    $insertConsultationSql = "INSERT INTO consultation_records (user_id, consultation_id, consultation_date) VALUES (?, ?, NOW())";
                    $insertConsultationStmt = $conn->prepare($insertConsultationSql);
                    $insertConsultationStmt->bind_param("ii", $userId, $consultationId);

                    if ($insertConsultationStmt->execute()) {
                        echo "<script>alert('Consultation applied successfully!'); window.location.href = 'dashboard.php';</script>";
                    } else {
                        echo "<script>alert('Error applying consultation. Please try again.');</script>";
                    }
                } else {
                    echo "<script>alert('Error updating wallet balance. Please try again.');</script>";
                }
            } elseif (isset($_POST['cancel'])) {
                echo "<script>window.location.href = 'dashboard.php';</script>";
            }
        }
    } else {
        echo "<p>Consultation not found.</p>";
    }
} else {
    header("Location: login.php");
    exit();
}
?>
