<?php
session_start();
include 'config.php';
header('Content-Type: application/json');

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true || !isset($_SESSION['admin_user']) || !isset($_SESSION['admin_pass'])) {
    echo json_encode([
        "status" => "error",
        "message" => "Unauthorized access"
    ]);
    exit;
}

$admin_user = $_SESSION['admin_user'];
$admin_pass = $_SESSION['admin_pass'];

$stmt = $conn->prepare("SELECT database_editing FROM modarator_permissions WHERE username=? AND password=? LIMIT 1");
$stmt->bind_param("ss", $admin_user, $admin_pass);
$stmt->execute();
$perm_result = $stmt->get_result();

if ($perm_result->num_rows == 0) {
    echo json_encode([
        "status" => "error",
        "message" => "Invalid moderator credentials"
    ]);
    exit;
}

$perm_row = $perm_result->fetch_assoc();

if ($perm_row['database_editing'] !== 'Yes') {
    echo json_encode([
        "status" => "error",
        "message" => "Permission denied. Database editing is not allowed."
    ]);
    exit;
}

$stmt->close();

if (isset($_POST['id']) || isset($_POST['type'])) {
    
    $id = $_POST['id'] ?? 0;
    $type = $_POST['type'] ?? '';

    if (!$id || !$type) {
        echo json_encode([
            "status" => "error",
            "message" => "Invalid request"
        ]);
        exit;
    }

    $req = $conn->query("SELECT * FROM gift_requests WHERE id='$id' AND status='pending'");

    if ($req->num_rows == 0) {
        echo json_encode([
            "status" => "error",
            "message" => "Request not found"
        ]);
        exit;
    }

    $r = $req->fetch_assoc();

    $sender_uid   = $r['sender_uid'];
    $receiver_uid = $r['receiver_uid'];
    $amount       = $r['amount'];
    $total        = $r['total'];
    $balance_type = $r['type'];

    if ($type == "success") {
        $conn->query("UPDATE users SET balance = balance + $amount WHERE uid='$receiver_uid'");
        $conn->query("UPDATE gift_requests SET status='approved' WHERE id='$id'");

        echo json_encode([
            "status" => "success",
            "message" => "Gift approved"
        ]);
        exit;
    }

    if ($type == "failed") {
        $conn->query("UPDATE users SET $balance_type = $balance_type + $total WHERE uid='$sender_uid'");
        $conn->query("UPDATE gift_requests SET status='failed' WHERE id='$id'");

        echo json_encode([
            "status" => "success",
            "message" => "Gift rejected and refunded"
        ]);
        exit;
    }

    echo json_encode([
        "status" => "error",
        "message" => "Invalid type"
    ]);
    exit;

} else {
    
    $res = $conn->query("SELECT * FROM gift_requests ORDER BY id DESC");
    $data = [];

    while($row = $res->fetch_assoc()){
        $data[] = $row;
    }

    echo json_encode([
        "status" => "success",
        "total" => count($data),
        "data" => $data
    ]);
    exit;
}
?>