<?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, "payments" => []]);
    exit;
}

$stmt = $pdo->prepare("SELECT * 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, "payments" => []]);
    exit;
}

/* ── Fetch ALL unread notifications for this partner ──
   This covers:
   1. Customer payments     (from_type = 'customer')
   2. Admin credit approvals/rejections (from_type = 'admin',
      transaction_type IN ('credit_request_approved','credit_request_rejected'))
*/
$stmt = $pdo->prepare("
    SELECT
        t.id,
        t.amount,
        t.created_at,
        t.from_type,
        t.transaction_type,
        t.remarks,
        COALESCE(c.full_name, NULL) AS full_name,
        COALESCE(c.phone,     NULL) AS phone
    FROM transactions t
    LEFT JOIN customers c ON c.id = t.from_id AND t.from_type = 'customer'
    WHERE t.to_type = 'partner'
      AND t.to_id   = ?
      AND t.partner_read_at IS NULL
    ORDER BY t.created_at DESC
    LIMIT 50
");
$stmt->execute([$shop["id"]]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* Shape each row so the dashboard JS can render it */
$payments = array_map(function ($row) {
    $type = $row["transaction_type"] ?? "";

    /* Determine display name and notification style */
    if ($row["from_type"] === "admin") {
        if ($type === "credit_request_approved") {
            $displayName = "✅ Admin";
            $notifType   = "approved";
        } elseif ($type === "credit_request_rejected") {
            $displayName = "❌ Admin";
            $notifType   = "rejected";
        } else {
            $displayName = "Admin";
            $notifType   = "admin";
        }
    } else {
        $displayName = $row["full_name"] ?: "Customer";
        $notifType   = "payment";
    }

    return [
        "id"          => $row["id"],
        "amount"      => $row["amount"],
        "created_at"  => $row["created_at"],
        "full_name"   => $displayName,
        "phone"       => $row["phone"] ?? "",
        "notif_type"  => $notifType,
        "remarks"     => $row["remarks"] ?? "",
    ];
}, $rows);

echo json_encode(["success" => true, "payments" => $payments]);