<?php
// cPanel path: /home/jewellersbd/public_html/erp.jewellersbd.com/api/notifications/get_notifications.php

require_once __DIR__ . '/../../api/_core.php';
require_once __DIR__ . '/../../config/db.php';

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

try {
    $today = date('Y-m-d');
    $notifications = [];

    // ── ১. বন্ধক overdue ─────────────────────────────────────────────
    $overdueQ = $pdo->query(
        "SELECT p.id, p.pledge_code, p.outstanding_principal, p.interest_rate,
                p.pledge_date, DATEDIFF(CURDATE(), p.pledge_date) AS days,
                pa.name AS party_name
         FROM pawn_pledges p
         LEFT JOIN parties pa ON pa.id = p.party_id
         WHERE p.status = 'OPEN'
           AND DATEDIFF(CURDATE(), p.pledge_date) > 30
           AND NOT EXISTS (
               SELECT 1 FROM pawn_payments pp
               WHERE pp.pledge_id = p.id
               AND pp.payment_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
           )
         ORDER BY days DESC
         LIMIT 20"
    );
    foreach ($overdueQ->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $int = round($row['outstanding_principal'] * ($row['interest_rate']/100) * ($row['days']/30), 0);
        $notifications[] = [
            'type'     => 'pledge_overdue',
            'priority' => 'high',
            'icon'     => '🔒',
            'title'    => 'বন্ধক Overdue: '.$row['party_name'],
            'body'     => $row['pledge_code'].' · '.$row['days'].' দিন · সুদ: ৳'.number_format($int,0),
            'link'     => '../pledge_payment.php?pledge_id='.$row['id'],
            'created_at' => $today,
        ];
    }

    // ── ২. বিক্রির বাকি ৭+ দিন ──────────────────────────────────────
    $dueQ = $pdo->query(
        "SELECT id, invoice_no, customer_name, due_amount, sale_date,
                DATEDIFF(CURDATE(), DATE(sale_date)) AS days
         FROM barcode_sales
         WHERE due_amount > 0
           AND status != 'paid'
           AND deleted_at IS NULL
           AND DATEDIFF(CURDATE(), DATE(sale_date)) >= 7
         ORDER BY days DESC
         LIMIT 15"
    );
    foreach ($dueQ->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $notifications[] = [
            'type'     => 'sale_due',
            'priority' => 'medium',
            'icon'     => '🏷️',
            'title'    => 'বিক্রির বাকি: '.($row['customer_name']?:'নগদ গ্রাহক'),
            'body'     => $row['invoice_no'].' · '.$row['days'].' দিন · বাকি: ৳'.number_format($row['due_amount'],0),
            'link'     => '../ui/sales_list.html',
            'created_at' => $today,
        ];
    }

    // ── ৩. Gold rate আজকে আপডেট হয়নি ────────────────────────────────
    $rateQ = $pdo->query(
        "SELECT rate_date FROM gold_rates ORDER BY rate_date DESC, id DESC LIMIT 1"
    )->fetch(PDO::FETCH_ASSOC);
    if (!$rateQ || $rateQ['rate_date'] < $today) {
        $notifications[] = [
            'type'     => 'gold_rate',
            'priority' => 'low',
            'icon'     => '💛',
            'title'    => 'Gold Rate আপডেট করুন',
            'body'     => 'আজকের ('.$today.') স্বর্ণ মূল্য এখনো দেওয়া হয়নি',
            'link'     => '../ui/gold_rate.html',
            'created_at' => $today,
        ];
    }

    // ── ৪. স্টক শূন্য বা খুব কম (< 5) ──────────────────────────────
    $stockCnt = (int)$pdo->query(
        "SELECT COUNT(*) FROM barcode_stock WHERE status='in_stock' AND is_deleted=0"
    )->fetchColumn();
    if ($stockCnt < 5) {
        $notifications[] = [
            'type'     => 'low_stock',
            'priority' => 'medium',
            'icon'     => '📦',
            'title'    => 'স্টক কমে গেছে!',
            'body'     => 'মাত্র '.$stockCnt.' টি আইটেম in_stock আছে',
            'link'     => '../ui/barcode_stock.html',
            'created_at' => $today,
        ];
    }

    // ── ৫. Purchase due বাকি ─────────────────────────────────────────
    $purDueQ = $pdo->query(
        "SELECT COUNT(*) cnt, SUM(due_amount) total_due
         FROM purchases
         WHERE due_amount > 0 AND payment_status != 'paid' AND deleted_at IS NULL"
    )->fetch(PDO::FETCH_ASSOC);
    if ($purDueQ && (int)$purDueQ['cnt'] > 0) {
        $notifications[] = [
            'type'     => 'purchase_due',
            'priority' => 'medium',
            'icon'     => '🛒',
            'title'    => 'ক্রয়ের বাকি পরিশোধ করুন',
            'body'     => $purDueQ['cnt'].' টি ক্রয়ে বাকি আছে: ৳'.number_format($purDueQ['total_due'],0),
            'link'     => '../ui/purchases.html',
            'created_at' => $today,
        ];
    }

    // Priority sort: high → medium → low
    $order = ['high'=>0,'medium'=>1,'low'=>2];
    usort($notifications, fn($a,$b) => ($order[$a['priority']]??9) - ($order[$b['priority']]??9));

    echo json_encode([
        'success' => true,
        'count'   => count($notifications),
        'high'    => count(array_filter($notifications, fn($n)=>$n['priority']==='high')),
        'data'    => $notifications,
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}