<?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";

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

$success = $conn->query("
    SELECT COUNT(*) t
    FROM ipe_requests
    WHERE status='SUCCESSFUL'
")->fetch_assoc()['t'];

$failed = $conn->query("
    SELECT COUNT(*) t
    FROM ipe_requests
    WHERE status='FAILED'
")->fetch_assoc()['t'];

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

    header("Content-Type: application/json");

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

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

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

        if (!$transaction_id) {
            echo json_encode([
                "success" => false,
                "message" => "Transaction ID not found"
            ]);
            exit;
        }

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

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

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

        $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();

        echo json_encode([
            "success" => true,
            "status" => $status
        ]);
        exit;
    }

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

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

        $stmt = $conn->prepare("
            SELECT tracking_id
            FROM ipe_requests
            WHERE id=?
        ");

        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->bind_result($tracking_id);
        $stmt->fetch();
        $stmt->close();

        if (!$tracking_id) {

            echo json_encode([
                "success" => false,
                "message" => "Tracking ID missing"
            ]);
            exit;
        }

        $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"
            ]
        ]);

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

        $data = json_decode($response, true);

        if (!isset($data['transactions'][0])) {

            echo json_encode([
                "success" => false,
                "message" => "Retry failed"
            ]);
            exit;
        }

        $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();

        echo json_encode([
            "success" => true,
            "status" => $status
        ]);
        exit;
    }

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

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

        $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();

        echo json_encode([
            "success" => true,
            "status" => $status
        ]);
        exit;
    }
}

/* ================= 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:200px;
    background:#0b2545;
    padding:20px;
    border-radius:10px;
    text-align:center;
}

.card h2{
    margin:0;
    font-size:28px;
}

/* ================= 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;
}

/* ================= 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;
}

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

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

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

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

/* ================= 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">
        <h2><?=$total?></h2>
        <p>Total Requests</p>
    </div>

    <div class="card">
        <h2><?=$success?></h2>
        <p>Successful</p>
    </div>

    <div class="card">
        <h2><?=$failed?></h2>
        <p>Failed</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><?=$row['id']?></td>

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

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

<td id="status<?=$row['id']?>">
    <?=$row['status']?>
</td>

<td>

<?php if(!empty($row['raw_response']) || !empty($row['reply'])): ?>

<button
class="btn"
onclick="viewReport(`<?=htmlspecialchars($row['raw_response'] ?: $row['reply'],ENT_QUOTES)?>`)">
View
</button>

<?php else: ?>
--
<?php endif; ?>

</td>

<td>

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

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

</td>

<td>

<form
onsubmit="return updateRequest(event,<?=$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 viewReport(data){

    let html = "";

    try{

        let d = JSON.parse(data);

        html += "<b>Status:</b> "
            +(d.status || "N/A")+"<br><br>";

        html += "<b>Tracking ID:</b> "
            +(d.data?.tracking_id || "N/A")+"<br><br>";

        html += "<pre>"
            + JSON.stringify(d,null,2)
            + "</pre>";

    }catch(e){

        html = data;
    }

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

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

/* ================= CHECK STATUS ================= */

function checkStatus(id){

    let fd = new FormData();

    fd.append("ajax","check");
    fd.append("id",id);

    document.getElementById("status"+id).innerHTML="Checking...";

    fetch("",{
        method:"POST",
        body:fd
    })
    .then(r=>r.json())
    .then(res=>{

        if(res.success){

            document.getElementById(
                "status"+id
            ).innerHTML=res.status;

            alert("Status Updated");

        }else{

            alert(res.message || "Failed");
        }
    });
}

/* ================= RETRY ================= */

function retryRequest(id){

    if(!confirm("Retry this request?")){
        return;
    }

    let fd = new FormData();

    fd.append("ajax","retry");
    fd.append("id",id);

    document.getElementById("status"+id).innerHTML="Retrying...";

    fetch("",{
        method:"POST",
        body:fd
    })
    .then(r=>r.json())
    .then(res=>{

        if(res.success){

            document.getElementById(
                "status"+id
            ).innerHTML=res.status;

            alert("Retry Successful");

        }else{

            alert(res.message || "Retry Failed");
        }
    });
}

/* ================= UPDATE ================= */

function updateRequest(e,id){

    e.preventDefault();

    let form=e.target;

    let fd=new FormData();

    fd.append("ajax","update");
    fd.append("id",id);
    fd.append("status",form.status.value);
    fd.append("reply",form.reply.value);

    fetch("",{
        method:"POST",
        body:fd
    })
    .then(r=>r.json())
    .then(res=>{

        if(res.success){

            document.getElementById(
                "status"+id
            ).innerHTML=form.status.value;

            alert("Saved Successfully");

        }else{

            alert("Update Failed");
        }
    });

    return false;
}

</script>

</body>
</html>