<?php
session_start();
require_once '../config/database.php';

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

if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== "partner") {
    echo json_encode(["success" => false, "message" => "Unauthorized"]);
    exit;
}

$transactionId = intval($_POST["transaction_id"] ?? 0);

if ($transactionId <= 0) {
    echo json_encode(["success" => false, "message" => "Missing transaction ID"]);
    exit;
}

$stmt = $pdo->prepare("SELECT id FROM partner_shops WHERE user_id = ? LIMIT 1");
$stmt->execute([$_SESSION["user_id"]]);
$shop = $stmt->fetch(PDO::FETCH_ASSOC);

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

/* ── Mark as read ──
   Accept ALL notification types sent to this partner:
   - from_type = 'customer'  → customer payment
   - from_type = 'admin'     → credit request approved / rejected
   Removed the AND from_type = 'customer' restriction.
*/
$stmt = $pdo->prepare("
    UPDATE transactions
    SET partner_read_at = NOW()
    WHERE id = ?
      AND to_type = 'partner'
      AND to_id = ?
      AND partner_read_at IS NULL
");
$stmt->execute([$transactionId, $shop["id"]]);

if ($stmt->rowCount() < 1) {
    echo json_encode([
        "success"        => false,
        "message"        => "Payment was not updated. Transaction ID or shop ID does not match.",
        "transaction_id" => $transactionId,
        "shop_id"        => $shop["id"]
    ]);
    exit;
}

echo json_encode(["success" => true, "message" => "Marked as read"]);