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

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

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

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

    // ── বিক্রি ────────────────────────────────────────────────────────
    $saleQ = $pdo->prepare(
        "SELECT COUNT(*) cnt,
                COALESCE(SUM(grand_total),0) total,
                COALESCE(SUM(paid_amount),0) paid,
                COALESCE(SUM(due_amount),0)  due
         FROM barcode_sales
         WHERE DATE(sale_date)=:d AND deleted_at IS NULL"
    );
    $saleQ->execute([':d'=>$today]);
    $sale = $saleQ->fetch(PDO::FETCH_ASSOC);

    // ── Cash IN/OUT ───────────────────────────────────────────────────
    $cashQ = $pdo->prepare(
        "SELECT
            SUM(CASE WHEN direction='IN'  AND is_deleted=0 THEN amount ELSE 0 END) cash_in,
            SUM(CASE WHEN direction='OUT' AND is_deleted=0 THEN amount ELSE 0 END) cash_out
         FROM cash_transactions WHERE transaction_date=:d"
    );
    $cashQ->execute([':d'=>$today]);
    $cash = $cashQ->fetch(PDO::FETCH_ASSOC);

    // ── নতুন বন্ধক ───────────────────────────────────────────────────
    $pledgeQ = $pdo->prepare(
        "SELECT COUNT(*) cnt, COALESCE(SUM(outstanding_principal),0) total
         FROM pawn_pledges WHERE DATE(pledge_date)=:d"
    );
    $pledgeQ->execute([':d'=>$today]);
    $newPledge = $pledgeQ->fetch(PDO::FETCH_ASSOC);

    // ── কারিগর pending jobs ───────────────────────────────────────────
    $karigarCnt = (int)$pdo->query(
        "SELECT COUNT(*) FROM karigar_jobs
         WHERE status IN ('OPEN','IN_PROGRESS')"
    )->fetchColumn();

    // ── আগামীকালের কাজ ───────────────────────────────────────────────
    $tomorrow_tasks = [];

    // Gold rate
    $rateRow = $pdo->query(
        "SELECT rate_date FROM gold_rates ORDER BY rate_date DESC LIMIT 1"
    )->fetch(PDO::FETCH_ASSOC);
    if (!$rateRow || $rateRow['rate_date'] < $today) {
        $tomorrow_tasks[] = [
            'icon'     => '💛',
            'task'     => 'Gold Rate আপডেট করুন ('.$today.')',
            'priority' => 'high',
            'link'     => '../ui/gold_rate.html',
        ];
    }

    // বন্ধক ৩ দিনে ৩০ দিন পূর্ণ
    $expCnt = (int)$pdo->query(
        "SELECT COUNT(*) FROM pawn_pledges
         WHERE status='OPEN'
           AND DATE_ADD(pledge_date, INTERVAL 30 DAY)
               BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)"
    )->fetchColumn();
    if ($expCnt > 0) {
        $tomorrow_tasks[] = [
            'icon'     => '🔒',
            'task'     => $expCnt.' টি বন্ধকের মেয়াদ ৩ দিনে শেষ — সুদ নিন',
            'priority' => 'high',
            'link'     => '../ui/pledges.html',
        ];
    }

    // বিক্রির বাকি ৭ দিন পূর্ণ
    $due7Cnt = (int)$pdo->query(
        "SELECT COUNT(*) FROM barcode_sales
         WHERE due_amount > 0 AND deleted_at IS NULL
           AND DATEDIFF(CURDATE(), DATE(sale_date)) = 7"
    )->fetchColumn();
    if ($due7Cnt > 0) {
        $tomorrow_tasks[] = [
            'icon'     => '🏷️',
            'task'     => $due7Cnt.' জন গ্রাহকের বাকি ৭ দিন পূর্ণ — follow up করুন',
            'priority' => 'medium',
            'link'     => '../ui/sales_list.html',
        ];
    }

    // কারিগর pending
    if ($karigarCnt > 0) {
        $tomorrow_tasks[] = [
            'icon'     => '🔨',
            'task'     => $karigarCnt.' টি কারিগর job pending',
            'priority' => 'medium',
            'link'     => '../ui/karigar_pending.html',
        ];
    }

    // ক্রয়ের বাকি
    $purDueCnt = (int)$pdo->query(
        "SELECT COUNT(*) FROM purchases
         WHERE due_amount > 0 AND deleted_at IS NULL"
    )->fetchColumn();
    if ($purDueCnt > 0) {
        $tomorrow_tasks[] = [
            'icon'     => '🛒',
            'task'     => $purDueCnt.' টি ক্রয়ের বাকি পরিশোধ করুন',
            'priority' => 'medium',
            'link'     => '../ui/purchases.html',
        ];
    }

    // স্টক কম
    $stockCnt = (int)$pdo->query(
        "SELECT COUNT(*) FROM barcode_stock WHERE status='in_stock' AND is_deleted=0"
    )->fetchColumn();
    if ($stockCnt < 10) {
        $tomorrow_tasks[] = [
            'icon'     => '📦',
            'task'     => 'স্টক কম ('.$stockCnt.' পিস) — নতুন স্টক যোগ করুন',
            'priority' => 'low',
            'link'     => '../ui/barcode_stock.html',
        ];
    }

    echo json_encode([
        'success' => true,
        'today'   => [
            'date'            => $today,
            'sale_cnt'        => (int)$sale['cnt'],
            'sale_total'      => (float)$sale['total'],
            'sale_paid'       => (float)$sale['paid'],
            'sale_due'        => (float)$sale['due'],
            'cash_in'         => (float)($cash['cash_in']  ?? 0),
            'cash_out'        => (float)($cash['cash_out'] ?? 0),
            'cash_net'        => (float)(($cash['cash_in']??0) - ($cash['cash_out']??0)),
            'new_pledge'      => (int)$newPledge['cnt'],
            'karigar_pending' => $karigarCnt,
        ],
        'tomorrow_tasks' => $tomorrow_tasks,
        'task_count'     => count($tomorrow_tasks),
    ]);

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