<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
require_once "db.php";

if(!isset($_SESSION['admin'])){
    die("Access denied");
}

/* ================= UPDATE ================= */
if(isset($_POST['update'])){

    $id     = $_POST['id'];
    $status = $_POST['status'];
    $reply  = $_POST['reply'];

    // get record
    $get = $conn->prepare("SELECT * FROM ipe_requests WHERE id=?");
    $get->bind_param("i",$id);
    $get->execute();
    $row = $get->get_result()->fetch_assoc();

    // ✅ refund logic
    if($status == "failed" && $row['request_status'] != "failed"){

        $stmt = $conn->prepare("
            UPDATE balance 
            SET amount = amount + ? 
            WHERE user=?
        ");

        $stmt->bind_param("ds", $row['amount'], $row['user']);
        $stmt->execute();
    }

    // update request
    $stmt = $conn->prepare("
        UPDATE ipe_request 
        SET request_status=?, reply=? 
        WHERE id=?
    ");

    $stmt->bind_param("ssi",$status,$reply,$id);
    $stmt->execute();

    $msg = "Updated successfully";
}

/* ================= STATS ================= */
$daily = $conn->query("SELECT COUNT(*) c, SUM(amount) s FROM ipe_requests WHERE DATE(created_at)=CURDATE()")->fetch_assoc();
$weekly = $conn->query("SELECT COUNT(*) c, SUM(amount) s FROM ipe_requests WHERE YEARWEEK(created_at)=YEARWEEK(NOW())")->fetch_assoc();
$monthly = $conn->query("SELECT COUNT(*) c, SUM(amount) s FROM ipe_requests WHERE MONTH(created_at)=MONTH(NOW())")->fetch_assoc();

/* ================= FETCH ================= */
$data = $conn->query("SELECT * FROM ipe_request ORDER BY id DESC");
?>

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>IPE Admin Dashboard</title>

<style>
body{font-family:Arial;background:#eef1f5;margin:0}
.header{padding:20px;font-size:20px;font-weight:bold;color:#00a2c7}
.cards{display:flex;gap:15px;padding:10px;flex-wrap:wrap}
.card{flex:1;min-width:250px;background:#fff;padding:15px;border-radius:12px;border-left:5px solid #00a2c7}
.table{background:#fff;margin:15px;border-radius:10px;overflow:auto}
table{width:100%;border-collapse:collapse}
th{background:#00a2c7;color:#fff;padding:12px;font-size:14px}
td{padding:10px;border-bottom:1px solid #eee;font-size:13px}
.badge{padding:5px 10px;border-radius:20px;color:#fff;font-size:12px}
.pending{background:orange}
.successful{background:green}
.failed{background:red}
select,textarea{width:100%;padding:6px;border-radius:6px;border:1px solid #ccc;font-size:12px}
button{background:#00a2c7;color:#fff;border:none;padding:6px 10px;border-radius:6px;cursor:pointer}
</style>
</head>

<body>

<div class="header">IPE Admin Dashboard</div>

<?php if(isset($msg)): ?>
<div style="padding:10px;color:green"><?= $msg ?></div>
<?php endif; ?>

<div class="cards">

<div class="card">
<b>Transactions</b><br>
Daily: <?= $daily['c'] ?? 0 ?><br>
Weekly: <?= $weekly['c'] ?? 0 ?><br>
Monthly: <?= $monthly['c'] ?? 0 ?>
</div>

<div class="card">
<b>Amount</b><br>
Daily: ₦<?= number_format($daily['s'] ?? 0,2) ?><br>
Weekly: ₦<?= number_format($weekly['s'] ?? 0,2) ?><br>
Monthly: ₦<?= number_format($monthly['s'] ?? 0,2) ?>
</div>

<div class="card">
<b>Profit</b><br>
Daily: ₦<?= number_format(($daily['s'] ?? 0)*0.2,2) ?><br>
Weekly: ₦<?= number_format(($weekly['s'] ?? 0)*0.2,2) ?><br>
Monthly: ₦<?= number_format(($monthly['s'] ?? 0)*0.2,2) ?>
</div>

</div>

<div class="table">
<table>

<tr>
<th>User</th>
<th>Tracking ID</th>
<th>Price</th>
<th>Status</th>
<th>Reply</th>
<th>Action</th>
</tr>

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

<tr>

<td><?= $row['user_email'] ?></td>
<td><?= $row['tracking_id'] ?></td>
<td>₦<?= number_format($row['amount'],2) ?></td>

<td>
<span class="badge <?= $row['request_status'] ?>">
<?= ucfirst($row['request_status']) ?>
</span>
</td>

<td><?= $row['reply'] ?: '-' ?></td>

<td>
<form method="post">
<input type="hidden" name="id" value="<?= $row['id'] ?>">

<select name="status">
<option value="pending">Pending</option>
<option value="successful">Successful</option>
<option value="failed">Failed</option>
</select>

<textarea name="reply" placeholder="Enter reply"></textarea>

<button name="update">Update</button>
</form>
</td>

</tr>

<?php endwhile; ?>

</table>
</div>

</body>
</html>