<?php include "header.php"; ?>
<link href="./assets/vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="./assets/vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet" />
<link href="./assets/vendors/themify-icons/css/themify-icons.css" rel="stylesheet" />
<link href="./assets/vendors/DataTables/datatables.min.css" rel="stylesheet" />
<link href="assets/css/main.min.css" rel="stylesheet" />

<?php
// WhatsApp API Configuration
$apiKey = "bSVJcHDwZeUqkBBlvHZRvn3xuVT7jX";
$sender = "6200218694";
$logFile = "whatsapp_messages.log";

// Function to send WhatsApp message and log it
function sendWhatsAppNotification($mobile, $message, $order_id) {
    global $apiKey, $sender, $logFile, $conn;
    
    // Check if this order ID was already notified
    $check_query = "SELECT COUNT(*) as count FROM whatsapp_logs WHERE order_id = '$order_id'";
    $result = mysqli_query($conn, $check_query);
    $row = mysqli_fetch_assoc($result);
    
    if ($row['count'] > 0) {
        return false; // Already notified
    }
    
    // Encode message for URL
    $encodedMsg = urlencode($message);
    $url = "https://wa.indiaapi.shop/send-message?api_key=$apiKey&sender=$sender&number=91$mobile&message=$encodedMsg";
    
    // Send request to WhatsApp API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    
    // Log the message in database
    $log_query = "INSERT INTO whatsapp_logs (mobile, message, order_id, sent_time) 
                  VALUES ('$mobile', '".mysqli_real_escape_string($conn, $message)."', '$order_id', NOW())";
    mysqli_query($conn, $log_query);
    
    // Log to file
    $logEntry = date("Y-m-d H:i:s") . " | Order ID: $order_id | Mobile: $mobile | Message: $message\n";
    file_put_contents($logFile, $logEntry, FILE_APPEND);
    
    return true;
}
?>

<div class="page-heading">
    <h1 class="page-title">Transactions</h1>
    <ol class="breadcrumb">
        <li class="breadcrumb-item">
            <a href="index.html"><i class="la la-home font-20"></i></a>
        </li>
    </ol>
</div>

<div class="page-content fade-in-up">
    <div class="ibox">
        <div class="ibox-head"></div>
        <div class="table-responsive">
            <table class="table table-striped table-bordered table-hover" id="example-table" cellspacing="0" width="100%">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Mobile</th>
                        <th>Date Time</th>
                        <th>Merchant</th>
                        <th>Gateway Txn</th>
                        <th>Bank RRN</th>
                        <th>Order ID</th>
                        <th>Amount</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if($userdata['role'] == 'User'){
                        $token = $userdata['user_token'];
                        $query = "SELECT `id`, `create_date`, `gateway_txn`, `customer_mobile`, `method`, `utr`, `byteTransactionId`, `order_id`, `amount`, `status` FROM `orders` WHERE user_token = '$token' ORDER BY `create_date` DESC";
                        $query_run = mysqli_query($conn, $query);

                        if ($query_run) {
                            while ($row = mysqli_fetch_assoc($query_run)) {
                                echo "<tr>";
                                echo "<td>" . htmlspecialchars($row['id']) . "</td>";
                                echo "<td>" . htmlspecialchars($row['customer_mobile']) . "</td>";
                                echo "<td>" . htmlspecialchars($row['create_date']) . "</td>";
                                echo "<td>" . htmlspecialchars($row['method']) . "</td>";
                                echo "<td>" . htmlspecialchars($row['gateway_txn']) . "</td>";
                                echo "<td>" . htmlspecialchars($row['utr']) . "</td>";
                                echo "<td>" . htmlspecialchars($row['order_id']) . "</td>";
                                echo "<td>₹" . htmlspecialchars($row['amount']) . "</td>";

                                if($row['status'] == "SUCCESS") {
                                    $sts = 'Success';
                                    $cls = "badge badge-success";
                                    
                                    // Prepare WhatsApp message with emojis and formatting
                                    $date = date("d M Y", strtotime($row['create_date']));
                                    $time = date("h:i A", strtotime($row['create_date']));

                                    $message  = "🟢 *Payment Successful!*\n\n";
                                    $message .= "🏷️ *Merchant:* " . $row['method'] . "\n";
                                    $message .= "💰 *Amount:* ₹" . $row['amount'] . "\n";
                                    $message .= "🧾 *Order ID:* " . $row['order_id'] . "\n";
                                    $message .= "📅 *Date:* " . $date . "\n";
                                    $message .= "⏰ *Time:* " . $time . "\n\n";
                                    $message .= "🔋 *Powered by PayIndia™*\n";
                                    $message .= "🙏 Thank you for your payment.";
                                    
                                    // Send WhatsApp notification
                                    sendWhatsAppNotification($row['customer_mobile'], $message, $row['order_id']);
                                } else {
                                    $sts = 'Pending';
                                    $cls = "badge badge-warning";
                                }
                                
                                echo "<td><button class='$cls'>$sts</button></td>";
                                echo "</tr>";
                            }
                        }
                    } else {
                        // Admin view code
                        $query = "SELECT * FROM `orders` ORDER BY id DESC";
                        $query_run = mysqli_query($conn, $query);

                        if ($query_run) {
                            while ($row = mysqli_fetch_assoc($query_run)) {
                                echo "<tr>";
                                echo "<td>" . htmlspecialchars($row['id']) . "</td>";
                                echo "<td>" . htmlspecialchars($row['customer_mobile']) . "</td>";
                                echo "<td>" . htmlspecialchars($row['create_date']) . "</td>";
                                echo "<td>" . htmlspecialchars($row['method']) . "</td>";
                                echo "<td>" . htmlspecialchars($row['gateway_txn']) . "</td>";
                                echo "<td>" . htmlspecialchars($row['utr']) . "</td>";
                                echo "<td>" . htmlspecialchars($row['order_id']) . "</td>";
                                echo "<td>₹" . htmlspecialchars($row['amount']) . "</td>";

                                if($row['status'] == 'SUCCESS') {
                                    $sts = 'Success';
                                    $cls = "badge badge-success";
                                } else {
                                    $sts = 'Pending';
                                    $cls = "badge badge-warning";
                                }
                                echo "<td><button class='$cls'>$sts</button></td>";
                                echo "</tr>";
                            }
                        }
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- JavaScript dependencies -->
<script src="./assets/vendors/jquery/dist/jquery.min.js"></script>
<script src="./assets/vendors/popper.js/dist/umd/popper.min.js"></script>
<script src="./assets/vendors/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="./assets/vendors/metisMenu/dist/metisMenu.min.js"></script>
<script src="./assets/vendors/jquery-slimscroll/jquery.slimscroll.min.js"></script>
<script src="./assets/js/scripts/dashboard_1_demo.js"></script>
<script src="./assets/vendors/DataTables/datatables.min.js"></script>
<script src="assets/js/app.min.js"></script>
<script>
    $(function() {
        $('#example-table').DataTable({
            pageLength: 10,
            "order": [[0, "desc"]] // Sort by ID descending by default
        });
    });
</script>
</body>
</html>