<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

require "db.php";

/* ================= ADMIN CHECK ================= */
if (!isset($_SESSION['admin'])) {
    die("Access Denied");
}

$apiKey = "sk_live_uqSkHKwJDJjKgrQZR8knNJHHtsSOFK3dybnD";

/*
|--------------------------------------------------------------------------
| SETTINGS
|--------------------------------------------------------------------------
*/
$profitPerRequest = 170;
$spentPerRequest  = 500; // change this if each request has a cost

/*
|--------------------------------------------------------------------------
| NOTE
|--------------------------------------------------------------------------
| This assumes your table has a DATETIME/TIMESTAMP column called created_at.
| If your date column is different, replace created_at everywhere below.
*/

/* ================= STATS ================= */

// Total count
$total = $conn->query("
    SELECT COUNT(*) AS t
    FROM ipe_requests
")->fetch_assoc()['t'];

// Today count
$todayCount = $conn->query("
    SELECT COUNT(*) AS t
    FROM ipe_requests
    WHERE DATE(created_at) = CURDATE()
")->fetch_assoc()['t'];

// This month count
$monthlyCount = $conn->query("
    SELECT COUNT(*) AS t
    FROM ipe_requests
    WHERE YEAR(created_at) = YEAR(CURDATE())
      AND MONTH(created_at) = MONTH(CURDATE())
")->fetch_assoc()['t'];

// Last month count
$lastMonthCount = $conn->query("
    SELECT COUNT(*) AS t
    FROM ipe_requests
    WHERE YEAR(created_at) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 MONTH))
      AND MONTH(created_at) = MONTH(DATE_SUB(CURDATE(), INTERVAL 1 MONTH))
")->fetch_assoc()['t'];

// Calculations
$todaySpent     = $todayCount * $spentPerRequest;
$todayProfit    = $todayCount * $profitPerRequest;

$monthlySpent   = $monthlyCount * $spentPerRequest;
$lastMonthSpent = $lastMonthCount * $spentPerRequest;

$totalSpent     = $total * $spentPerRequest;
$totalProfit    = $total * $profitPerRequest;

/* ================= AJAX RESPONSE HELPER ================= */
function jsonResponse($arr) {
    if (ob_get_length()) {
        ob_clean();
    }
    header("Content-Type: application/json");
    echo json_encode($arr);
    exit;
}

/* ================= AJAX HANDLER ================= */
if (isset($_POST['ajax'])) {

    /* ================= CHECK STATUS ================= */
    if ($_POST['ajax'] === "check") {

        $id = (int)($_POST['id'] ?? 0);

        $stmt = $conn->prepare("
            SELECT transaction_id
            FROM ipe_requests
            WHERE id=?
            LIMIT 1
        ");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->bind_result($transaction_id);
        $stmt->fetch();
        $stmt->close();

        if (empty($transaction_id)) {
            jsonResponse([
                "success" => false,
                "message" => "Transaction ID not found"
            ]);
        }

        $ch = curl_init("https://new.unifyxpress.com/api/v4/transaction/" . urlencode($transaction_id));

        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                "X-API-Key: $apiKey"
            ],
            CURLOPT_TIMEOUT => 30
        ]);

        $response = curl_exec($ch);
        $curlError = curl_error($ch);
        curl_close($ch);

        if ($response === false || !empty($curlError)) {
            jsonResponse([
                "success" => false,
                "message" => "Unable to check status"
            ]);
        }

        $data = json_decode($response, true);
        $status = strtoupper($data['status'] ?? 'FAILED');
        $raw = json_encode($data);

        $up = $conn->prepare("
            UPDATE ipe_requests
            SET status=?,
                raw_response=?
            WHERE id=?
        ");
        $up->bind_param("ssi", $status, $raw, $id);
        $up->execute();
        $up->close();

        jsonResponse([
            "success" => true,
            "status" => $status
        ]);
    }

    /* ================= RETRY ================= */
    if ($_POST['ajax'] === "retry") {

        $id = (int)($_POST['id'] ?? 0);

        $stmt = $conn->prepare("
            SELECT tracking_id
            FROM ipe_requests
            WHERE id=?
            LIMIT 1
        ");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->bind_result($tracking_id);
        $stmt->fetch();
        $stmt->close();

        if (empty($tracking_id)) {
            jsonResponse([
                "success" => false,
                "message" => "Tracking ID missing"
            ]);
        }

        $payload = json_encode([
            "tracking_ids" => [$tracking_id]
        ]);

        $ch = curl_init("https://new.unifyxpress.com/api/v4/nin/ipe");

        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => [
                "Content-Type: application/json",
                "X-API-Key: $apiKey"
            ],
            CURLOPT_TIMEOUT => 30
        ]);

        $response = curl_exec($ch);
        $curlError = curl_error($ch);
        curl_close($ch);

        if ($response === false || !empty($curlError)) {
            jsonResponse([
                "success" => false,
                "message" => "Retry request failed"
            ]);
        }

        $data = json_decode($response, true);

        if (!isset($data['transactions'][0])) {
            jsonResponse([
                "success" => false,
                "message" => "Retry failed"
            ]);
        }

        $t = $data['transactions'][0];

        $transaction_id = $t['id'] ?? '';
        $status         = strtoupper($t['status'] ?? 'PENDING');
        $raw            = json_encode($t);

        $up = $conn->prepare("
            UPDATE ipe_requests
            SET transaction_id=?,
                status=?,
                raw_response=?
            WHERE id=?
        ");
        $up->bind_param("sssi", $transaction_id, $status, $raw, $id);
        $up->execute();
        $up->close();

        jsonResponse([
            "success" => true,
            "status" => $status
        ]);
    }

    /* ================= UPDATE STATUS ================= */
    if ($_POST['ajax'] === "update") {

        $id     = (int)($_POST['id'] ?? 0);
        $status = trim($_POST['status'] ?? 'PENDING');
        $reply  = trim($_POST['reply'] ?? '');

        $up = $conn->prepare("
            UPDATE ipe_requests
            SET status=?,
                reply=?
            WHERE id=?
        ");
        $up->bind_param("ssi", $status, $reply, $id);
        $up->execute();
        $up->close();

        jsonResponse([
            "success" => true,
            "status" => $status
        ]);
    }

    jsonResponse([
        "success" => false,
        "message" => "Invalid request"
    ]);
}

/* ================= FETCH DATA ================= */
$data = $conn->query("
    SELECT *
    FROM ipe_requests
    ORDER BY id DESC
");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Admin IPE Dashboard</title>

<style>
body{
    background:#071a2f;
    color:#fff;
    font-family:Arial,sans-serif;
    padding:20px;
    margin:0;
}

h2{
    margin-bottom:20px;
}

/* ================= STATS ================= */

.top-box{
    display:flex;
    gap:15px;
    flex-wrap:wrap;
    margin-bottom:20px;
}

.card{
    flex:1;
    min-width:220px;
    background:#0b2545;
    padding:20px;
    border-radius:10px;
    text-align:left;
    box-shadow:0 4px 12px rgba(0,0,0,.2);
}

.card h3{
    margin:0 0 15px;
    font-size:22px;
    color:#00c896;
}

.card p{
    margin:8px 0;
    font-size:15px;
    line-height:1.6;
}

/* ================= TABLE ================= */

.table-wrap{
    overflow-x:auto;
}

table{
    width:100%;
    border-collapse:collapse;
    background:#0b2545;
}

th{
    background:#13345f;
}

th, td{
    padding:10px;
    border-bottom:1px solid #2c4d75;
    text-align:center;
}

/* ================= BUTTONS ================= */

.btn{
    border:none;
    padding:7px 12px;
    cursor:pointer;
    border-radius:4px;
    margin:2px;
}

.check{
    background:#f39c12;
    color:#fff;
}

.retry{
    background:#00c896;
    color:#fff;
}

.update{
    background:#007bff;
    color:#fff;
}

.view-btn{
    background:#6c757d;
    color:#fff;
}

/* ================= INPUTS ================= */

input, select{
    padding:6px;
    width:95%;
    border-radius:4px;
    border:none;
}

/* ================= POPUP ================= */

.popup{
    display:none;
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background:rgba(0,0,0,.7);
    justify-content:center;
    align-items:center;
    z-index:9999;
}

.popup-box{
    width:90%;
    max-width:700px;
    background:#fff;
    border-radius:8px;
    overflow:hidden;
}

.popup-header{
    background:#0b2545;
    color:#fff;
    padding:12px;
    display:flex;
    justify-content:space-between;
    align-items:center;
}

.popup-body{
    padding:15px;
    color:#000;
    max-height:500px;
    overflow:auto;
    word-break:break-word;
}

.close{
    cursor:pointer;
    font-weight:bold;
    font-size:18px;
}

/* ================= MOBILE ================= */

@media(max-width:768px){
    body{
        padding:10px;
    }

    th, td{
        font-size:12px;
        padding:6px;
    }

    .btn{
        width:100%;
        margin-top:3px;
    }

    input, select{
        width:100%;
    }
}
</style>
</head>

<body>

<h2>Admin IPE Dashboard</h2>

<div class="top-box">

    <div class="card">
        <h3>1st Box</h3>
        <p><strong>Today Count:</strong> <?= number_format($todayCount) ?></p>
        <p><strong>Today Spent:</strong> <?= number_format($todaySpent) ?></p>
        <p><strong>Today Profit:</strong> <?= number_format($todayProfit) ?></p>
    </div>

    <div class="card">
        <h3>2nd Box</h3>
        <p><strong>Monthly Count:</strong> <?= number_format($monthlyCount) ?></p>
        <p><strong>Monthly Spent:</strong> <?= number_format($monthlySpent) ?></p>
        <p><strong>Last Month Spent:</strong> <?= number_format($lastMonthSpent) ?></p>
    </div>

    <div class="card">
        <h3>3rd Box</h3>
        <p><strong>Total Spent:</strong> <?= number_format($totalSpent) ?></p>
        <p><strong>Total Profit:</strong> <?= number_format($totalProfit) ?></p>
    </div>

</div>

<div class="table-wrap">
<table>
    <tr>
        <th>ID</th>
        <th>User</th>
        <th>Tracking ID</th>
        <th>Status</th>
        <th>Report</th>
        <th>Actions</th>
        <th>Update</th>
    </tr>

    <?php while($row = $data->fetch_assoc()): ?>
    <tr>

        <td><?= (int)$row['id'] ?></td>

        <td><?= htmlspecialchars($row['user']) ?></td>

        <td><?= htmlspecialchars($row['tracking_id']) ?></td>

        <td id="status<?= (int)$row['id'] ?>">
            <?= htmlspecialchars($row['status']) ?>
        </td>

        <td>
            <?php if (!empty($row['raw_response']) || !empty($row['reply'])): ?>
                <button
                    type="button"
                    class="btn view-btn"
                    data-report='<?= htmlspecialchars($row["raw_response"] ?: $row["reply"], ENT_QUOTES, "UTF-8") ?>'
                    onclick="viewReport(this)">
                    View
                </button>
            <?php else: ?>
                --
            <?php endif; ?>
        </td>

        <td>
            <button
                type="button"
                class="btn check"
                onclick="checkStatus(<?= (int)$row['id'] ?>)">
                Check
            </button>

            <button
                type="button"
                class="btn retry"
                onclick="retryRequest(<?= (int)$row['id'] ?>)">
                Retry
            </button>
        </td>

        <td>
            <form onsubmit="return updateRequest(event, <?= (int)$row['id'] ?>)">

                <select name="status">
                    <option value="PENDING" <?= $row['status'] == "PENDING" ? "selected" : "" ?>>
                        PENDING
                    </option>
                    <option value="SUCCESSFUL" <?= $row['status'] == "SUCCESSFUL" ? "selected" : "" ?>>
                        SUCCESSFUL
                    </option>
                    <option value="FAILED" <?= $row['status'] == "FAILED" ? "selected" : "" ?>>
                        FAILED
                    </option>
                </select>

                <br><br>

                <input
                    type="text"
                    name="reply"
                    value="<?= htmlspecialchars($row['reply'] ?? '') ?>"
                    placeholder="Reply">

                <br><br>

                <button type="submit" class="btn update">Save</button>
            </form>
        </td>

    </tr>
    <?php endwhile; ?>
</table>
</div>

<!-- REPORT POPUP -->
<div id="popup" class="popup">
    <div class="popup-box">
        <div class="popup-header">
            <span>Request Report</span>
            <span class="close" onclick="closePop()">✖</span>
        </div>
        <div class="popup-body" id="content"></div>
    </div>
</div>

<script>
function escapeHtml(text) {
    if (text === null || text === undefined) {
        return "";
    }

    return String(text)
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;");
}

function viewReport(btn) {
    var data = btn.getAttribute("data-report") || "";
    var html = "";

    if (!data) {
        document.getElementById("content").innerHTML = "No report found";
        document.getElementById("popup").style.display = "flex";
        return;
    }

    try {
        var d = JSON.parse(data);
        var trackingId = "N/A";

        if (d.data && d.data.tracking_id) {
            trackingId = d.data.tracking_id;
        } else if (d.tracking_id) {
            trackingId = d.tracking_id;
        }

        html += "<b>Status:</b> " + escapeHtml(d.status || "N/A") + "<br><br>";
        html += "<b>Tracking ID:</b> " + escapeHtml(trackingId) + "<br><br>";
        html += "<pre>" + escapeHtml(JSON.stringify(d, null, 2)) + "</pre>";
    } catch (e) {
        html = "<pre>" + escapeHtml(data) + "</pre>";
    }

    document.getElementById("content").innerHTML = html;
    document.getElementById("popup").style.display = "flex";
}

function closePop() {
    document.getElementById("popup").style.display = "none";
}

function postAjax(formData, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", window.location.href, true);

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            var responseText = xhr.responseText;

            try {
                var res = JSON.parse(responseText);
                callback(res);
            } catch (e) {
                callback({
                    success: false,
                    message: "Invalid server response",
                    raw: responseText
                });
            }
        }
    };

    xhr.send(formData);
}

/* ================= CHECK STATUS ================= */
function checkStatus(id) {
    var statusCell = document.getElementById("status" + id);
    var oldStatus = statusCell.innerHTML;

    var fd = new FormData();
    fd.append("ajax", "check");
    fd.append("id", id);

    statusCell.innerHTML = "Checking...";

    postAjax(fd, function(res) {
        if (res.success) {
            statusCell.innerHTML = res.status;
            alert("Status Updated");
        } else {
            statusCell.innerHTML = oldStatus;
            alert(res.message || "Failed");
        }
    });
}

/* ================= RETRY ================= */
function retryRequest(id) {
    if (!confirm("Retry this request?")) {
        return;
    }

    var statusCell = document.getElementById("status" + id);
    var oldStatus = statusCell.innerHTML;

    var fd = new FormData();
    fd.append("ajax", "retry");
    fd.append("id", id);

    statusCell.innerHTML = "Retrying...";

    postAjax(fd, function(res) {
        if (res.success) {
            statusCell.innerHTML = res.status;
            alert("Retry Successful");
        } else {
            statusCell.innerHTML = oldStatus;
            alert(res.message || "Retry Failed");
        }
    });
}

/* ================= UPDATE ================= */
function updateRequest(e, id) {
    e.preventDefault();

    var form = e.target;

    var fd = new FormData();
    fd.append("ajax", "update");
    fd.append("id", id);
    fd.append("status", form.status.value);
    fd.append("reply", form.reply.value);

    postAjax(fd, function(res) {
        if (res.success) {
            document.getElementById("status" + id).innerHTML = form.status.value;
            alert("Saved Successfully");
        } else {
            alert(res.message || "Update Failed");
        }
    });

    return false;
}
</script>

</body>
</html>
