
<?php
session_start();

// Prevent session fixation
session_regenerate_id(true);

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}
require 'require/conn.php';
// Sanitize session data before displaying
function sanitizeOutput($data) {
    return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
}

$fullname = sanitizeOutput($_SESSION['firstName']) . ' ' . sanitizeOutput($_SESSION['lastName']);
$email = sanitizeOutput($_SESSION['email']);
$phone = sanitizeOutput($_SESSION['phone']);
$user_type = sanitizeOutput($_SESSION['type']);


$stmt = $conn->prepare("SELECT firstName, lastName, wallet_balance FROM jamaa WHERE phone = ?");
$stmt->bind_param("s", $phone);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 1) {
    $user = $result->fetch_assoc();
    $firstName = htmlspecialchars($user['firstName']);
    $lastName = htmlspecialchars($user['lastName']);
    $wallet_balance = htmlspecialchars($user['wallet_balance']);
} else {
    echo "User not found.";
    exit();
}

?>


<?php
// Start session securely
session_start([
    'cookie_secure' => true, // Ensure cookies are only sent over HTTPS
    'cookie_httponly' => true, // Prevent JavaScript access to session cookies
    'use_strict_mode' => true, // Prevent session fixation
]);

// Regenerate session ID to prevent session fixation
session_regenerate_id(true);

// Session expiration (30 min timeout)
if (!isset($_SESSION['LAST_ACTIVITY'])) {
    $_SESSION['LAST_ACTIVITY'] = time();
} elseif (time() - $_SESSION['LAST_ACTIVITY'] > 1800) { // 30 min timeout
    session_unset();
    session_destroy();
    header("Location: login.php");
    exit();
}
$_SESSION['LAST_ACTIVITY'] = time();

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Set security headers
header("X-Frame-Options: SAMEORIGIN");
header("X-XSS-Protection: 1; mode=block");
header("X-Content-Type-Options: nosniff");

// Disable error display in production
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error.log'); // Secure error log path

// Include database connection
require 'require/conn.php';

// Generate CSRF token if not set
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Handle AJAX request to fetch data statuses
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['fetch_data_statuses'])) {
    $network = filter_input(INPUT_POST, 'network', FILTER_SANITIZE_STRING);

    if ($network) {
        $query = "SELECT DISTINCT ds.plan_name FROM data_status ds 
                  JOIN data_plans dp ON ds.network_name = dp.network
                  WHERE ds.status = 'On' AND dp.network = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("s", $network);
        $stmt->execute();
        $result = $stmt->get_result();

        $options = '<option value="">-- Select Data Status --</option>';
        while ($row = $result->fetch_assoc()) {
            $options .= '<option value="' . htmlspecialchars($row['plan_name'], ENT_QUOTES, 'UTF-8') . '">' . htmlspecialchars($row['plan_name'], ENT_QUOTES, 'UTF-8') . '</option>';
        }
        echo $options;
    }
    exit;
}

// Handle AJAX request to fetch plan names
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['fetch_plan_names'])) {
    $data_status = filter_input(INPUT_POST, 'data_status', FILTER_SANITIZE_STRING);
    $network = filter_input(INPUT_POST, 'network', FILTER_SANITIZE_STRING);

    if ($data_status && $network) {
        $query = "SELECT dataplan_id, data_name, user_price, api_price FROM data_plans 
                  WHERE network = ? AND data_status = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("ss", $network, $data_status);
        $stmt->execute();
        $result = $stmt->get_result();

        $options = '<option value="">-- Select Plan Name --</option>';
        while ($row = $result->fetch_assoc()) {
            $price = ($_SESSION['user_type'] === 'api') ? $row['api_price'] : $row['user_price'];
            $options .= '<option value="' . htmlspecialchars($row['dataplan_id'], ENT_QUOTES, 'UTF-8') . '" 
                         data-user-price="' . htmlspecialchars($row['user_price'], ENT_QUOTES, 'UTF-8') . '" 
                         data-api-price="' . htmlspecialchars($row['api_price'], ENT_QUOTES, 'UTF-8') . '">' . 
                         htmlspecialchars($row['data_name'], ENT_QUOTES, 'UTF-8') . ' - N' . $price . '</option>';
        }
        echo $options;
    }
    exit;
}

// Fetch available networks
$network_query = "SELECT id, network_name FROM network WHERE status = 'On'";
$network_result = $conn->query($network_query);
if (!$network_result) {
    die("Network query failed: " . $conn->error);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Buy Data</title>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
     <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- Mobile Specific Metas -->
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, viewport-fit=cover">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <title>Dashboard</title>
    <!-- Favicon and Touch Icons  -->
    <link rel="shortcut icon" href="images/logo.png" />
    <link rel="apple-touch-icon-precomposed" href="images/logo.png" />
    <!-- Font -->
    <link rel="stylesheet" href="fonts/fonts.css" />
    <!-- Icons -->
    <link rel="stylesheet" href="fonts/icons-alipay.css">
    <link rel="stylesheet" href="styles/bootstrap.css">
    <link rel="stylesheet" href="styles/swiper-bundle.min.css">
    <link rel="stylesheet" type="text/css" href="styles/styles.css" />
    <link rel="manifest" href="_manifest.json" data-pwa-version="set_in_manifest_and_pwa_js">
    <link rel="apple-touch-icon" sizes="192x192" href="app/icons/icon-192x192.png">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        /* Add this CSS to create a 3x3 grid layout */
        .box-service {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 16px; /* Adjust the gap between grid items as needed */
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .box-service li {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            text-align: center;
            background-color: #f9f9f9; /* Optional: Add background color */
            padding: 16px;
            border-radius: 8px; /* Optional: Add rounded corners */
        }

        .box-service li a {
            text-decoration: none;
            color: inherit;
        }

        .icon-box {
            font-size: 24px; /* Adjust the size of the icon */
            margin-bottom: 8px; /* Space between icon and text */
        }
    </style>
</head>
<body>
        <div class="app-header">
        <div class="tf-container">
            <div class="tf-topbar d-flex justify-content-between align-items-center">
                <a class="user-info d-flex justify-content-between align-items-center" href="profile.php">
                    <img src="images/user/user1.jpg" alt="image">

                    <div class="content">
                        <h4 class="white_color"> <?php echo $fullname; ?></h4>
                        <p class="white_color fw_4"><?php echo ucfirst($user_type); ?></p>
                    </div>
                </a>
               
            </div>
        </div>
    </div>
    <div class="card-secton">
        <div class="tf-container">
            <div class="tf-balance-box">
                <div class="balance">
                    <div class="row">
                        <div class="col-6 br-right">
                            <div class="inner-left">
                                <p>Your Balance:</p>
                               <h2>
    <span id="wallet-balance">₦****</span>
    <span id="toggle-eye" class="eye-icon" style="cursor: pointer;">👁️</span>
</h2>

<script>
    const eyeIcon = document.getElementById('toggle-eye');
    const walletBalance = document.getElementById('wallet-balance');

    // Replace with actual wallet balance from PHP
    const rawBalance = "<?php echo $wallet_balance; ?>"; // e.g., 25000.75

    // Format the balance with comma separators and two decimal points
    const formattedBalance = "₦" + parseFloat(rawBalance).toLocaleString('en-NG', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });

    let isVisible = false;

    eyeIcon.addEventListener('click', () => {
        if (isVisible) {
            walletBalance.textContent = '****';
            eyeIcon.textContent = '👁️';
        } else {
            walletBalance.textContent = formattedBalance; // Show formatted number with ₦
            eyeIcon.textContent = '🙈';
        }
        isVisible = !isVisible;
    });
</script>

                            </div>
                        </div>
                        
                    </div>
                </div>
                <div class="wallet-footer">
                    <!-- Include Font Awesome CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

<ul class="d-flex justify-content-between align-items-center" style="list-style: none; padding: 0;">
    
    <!-- Fund Account -->
    <li class="wallet-card-item" style="text-align: center;">
        <a href="account.php" class="fw_6 text-center" id="btn-popup-down" style="text-decoration: none; color: inherit;">
            <div class="icon-container">
                <i class="fas fa-wallet fa-2x"></i>
            </div>
            <div>Fund Account</div>
        </a>
    </li>

    <!-- Buy Data -->
    <li class="wallet-card-item" style="text-align: center;">
        <a href="buy_data.php" class="fw_6 btn-card-popup" style="text-decoration: none; color: inherit;">
            <div class="icon-container">
                <i class="fas fa-signal fa-2x"></i>
            </div>
            <div>Buy Data</div>
        </a>
    </li>

    <!-- Airtime -->
    <li class="wallet-card-item" style="text-align: center;">
        <a href="buyairtime.php" class="fw_6" style="text-decoration: none; color: inherit;">
            <div class="icon-container">
                <i class="fas fa-mobile-alt fa-2x"></i>
            </div>
            <div>Airtime</div>
        </a>
    </li>

</ul>

                </div>
            </div>
        </div>

    </div>
    
    
    <style>
        .uu{
            width: 100%;
            padding: 6px;
        }
        
    </style>
    
     <div class="mt-5 mb-9">
        <div class="tf-container">
    <div class="uu">
    <h4>Buy Data</h4>
    <form method="post" action="process_buy_data.php" id="buy-data-form">
        <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">

        <label for="network">Select Network:</label>
        <select id="network" name="network" required>
            <option value="">-- Select Network --</option>
            <?php while ($row = $network_result->fetch_assoc()) { ?>
                <option value="<?= htmlspecialchars($row['network_name'], ENT_QUOTES, 'UTF-8') ?>">
                    <?= htmlspecialchars($row['network_name'], ENT_QUOTES, 'UTF-8') ?>
                </option>
            <?php } ?>
        </select>

        <label for="data_status">Select Data Status:</label>
        <select id="data_status" name="data_status" required>
            <option value="">-- Select Data Status --</option>
        </select>

        <label for="plan_name">Select Plan Name:</label>
        <select id="plan_name" name="plan_name" required>
            <option value="">-- Select Plan Name --</option>
        </select>

        <div id="price-display"></div>
        <input type="hidden" id="dataplan_id" name="dataplan_id">

 <label for="plan_name">Mobile No.:</label>
      
        <input type="tel" id="mobile_no" name="mobile_no" placeholder="Input No." required>

      <label for="plan_name">Transaction Pin:</label>
        <input type="password" id="transaction_pin" name="transaction_pin" placeholder="Transaction Pin." required>
<hr>
        <button style="background-color: green;" type="submit" name="buy_data">Buy Data</button>
    </form>

    <script>
        $(document).ready(function() {
            $('#network').change(function() {
                var network = $(this).val();
                if (network) {
                    $.post('', { fetch_data_statuses: true, network: network }, function(response) {
                        $('#data_status').html(response);
                        $('#plan_name').html('<option value="">-- Select Plan Name --</option>');
                        $('#price-display').text('');
                    });
                }
            });

            $('#data_status').change(function() {
                var data_status = $(this).val();
                var network = $('#network').val();
                if (data_status && network) {
                    $.post('', { fetch_plan_names: true, data_status: data_status, network: network }, function(response) {
                        $('#plan_name').html(response);
                        $('#price-display').text('');
                    });
                }
            });

            $('#plan_name').change(function() {
                var selected = $(this).find('option:selected');
                var userPrice = selected.data('user-price');
                var apiPrice = selected.data('api-price');
                var price = (<?= json_encode($_SESSION['user_type'] ?? 'user') ?> === 'api') ? apiPrice : userPrice;
          
                $('#dataplan_id').val(selected.val());
            });

            // Handle form submission
            $('#buy-data-form').on('submit', function(e) {
                e.preventDefault(); // Prevent default form submission

                // Get form data
                var formData = $(this).serialize();

                // Submit form via AJAX
                $.post('process_buy_data.php', formData, function(response) {
                    var result = JSON.parse(response);
                    if (result.status === 'success') {
                        // Display SweetAlert2 popup on success
                        Swal.fire({
                            title: 'Transaction Successful',
                            html: `
                                <p><strong>Mobile Number:</strong> ${$('#mobile_no').val()}</p>
                                <p><strong>Plan Name:</strong> ${$('#plan_name option:selected').text().split(' - ')[0]}</p>
                                <p><strong>Price:</strong> $${$('#price-display').text().split('$')[1]}</p>
                            `,
                            icon: 'success',
                            showCancelButton: true,
                            confirmButtonText: 'OK',
                            cancelButtonText: 'Cancel'
                        }).then((result) => {
                            if (result.isConfirmed) {
                                // Redirect or perform another action
                                window.location.href = 'dashboard.php';
                            }
                        });
                    } else {
                        // Display error message
                        Swal.fire({
                            title: 'Error',
                            text: result.message,
                            icon: 'error',
                            confirmButtonText: 'OK'
                        });
                    }
                });
            });
        });
    </script>
      
   
   </div>
   </div>
      </div>
   <div class="bottom-navigation-bar">
        <div class="tf-container">
            <ul class="tf-navigation-bar">
                <li ><a class="fw_6 d-flex justify-content-center align-items-center flex-column"
                        href="account.php"> <i class="fas fa-wallet fa-2x"></i> Fund</a> </li>
                <li><a class="fw_4 d-flex justify-content-center align-items-center flex-column" href="history.php"><i
                            class="icon-history"></i> History</a> </li>
                <li class="active"><a class="fw_4 d-flex justify-content-center align-items-center flex-column" href="dashboard.php"><i
                            class="icon-home2"></i> </a>  </li>
                <li><a class="fw_4 d-flex justify-content-center align-items-center flex-column"
                        href="privacy.php">  <i class="fas fa-flag fa-2x"></i></i>
                        Privacy</a> </li>
                <li><a class="fw_4 d-flex justify-content-center align-items-center flex-column" href="profile.php"><i
                            class="icon-user-outline"></i> Profile</a> </li>
            </ul>
            <!-- <span class="line"></span> -->
        </div>
    </div>
  


 </div>   </div>
    <script type="text/javascript" src="javascript/jquery.min.js"></script>
    <script type="text/javascript" src="javascript/bootstrap.min.js"></script>
    <script type="text/javascript" src="javascript/swiper-bundle.min.js"></script>
    <script type="text/javascript" src="javascript/swiper.js"></script>
    <script type="text/javascript" src="javascript/main.js"></script>
</body>
</html>