<?php
/**
 * Get Payment Follow-ups AJAX Endpoint
 * LandSales Pro - Fetch due payments for follow-up notifications
 */
define('APP_RUNNING', true);
require_once '../db_connect.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

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

initSecureSession();

if (!isAuthenticated()) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

$userId = $_SESSION['user_id'];

// Get today's date
$today = date('Y-m-d');

// Fetch ONLY payments due TODAY (not overdue)
// Group by sale - show one entry per sale with total amount due today
// Also include rescheduled payments where promised_date is today
$sql = "SELECT
    MIN(ps.id) as schedule_id,
    ps.sale_id,
    GROUP_CONCAT(ps.installment_number ORDER BY ps.installment_number) as installment_numbers,
    COUNT(ps.id) as installment_count,
    SUM(ps.amount) as total_amount,
    MIN(ps.due_date) as due_date,
    s.sale_number,
    b.id as buyer_id,
    b.full_name as buyer_name,
    b.phone as buyer_phone,
    p.plot_number,
    pr.name as project_name,
    MAX(pf.id) as followup_id,
    MAX(pf.status) as followup_status,
    MAX(pf.notes) as followup_notes,
    MAX(pf.promised_date) as promised_date,
    MAX(pf.called_at) as called_at
FROM payment_schedule ps
JOIN sales s ON ps.sale_id = s.id
JOIN buyers b ON s.buyer_id = b.id
JOIN plots p ON s.plot_id = p.id
JOIN projects pr ON p.project_id = pr.id
LEFT JOIN payment_followups pf ON ps.id = pf.payment_schedule_id
    AND pf.followup_date = ?
WHERE s.user_id = ?
AND ps.status IN ('pending', 'overdue')
AND (
    ps.due_date = ?
    OR (pf.promised_date = ?)
)
GROUP BY ps.sale_id, s.sale_number, b.id, b.full_name, b.phone, p.plot_number, pr.name
ORDER BY
    CASE WHEN MAX(pf.status) IS NULL OR MAX(pf.status) = 'pending' THEN 0 ELSE 1 END,
    b.full_name ASC";

$followups = db_fetch_all($sql, 'siss', [$today, $userId, $today, $today]);

// Count pending followups (not yet called today)
$pendingCount = 0;
foreach ($followups as $f) {
    if (empty($f['followup_status']) || $f['followup_status'] === 'pending') {
        $pendingCount++;
    }
}

// Format the results
$formatted = [];
foreach ($followups as $f) {
    // Check if this is a rescheduled followup (promised_date = today)
    $isRescheduled = $f['promised_date'] === $today;

    // Format installment display (e.g., "#1" or "#1, #2")
    $installmentDisplay = $f['installment_count'] > 1
        ? $f['installment_count'] . ' installments'
        : 'Inst. #' . $f['installment_numbers'];

    $formatted[] = [
        'schedule_id' => $f['schedule_id'],
        'sale_id' => $f['sale_id'],
        'followup_id' => $f['followup_id'],
        'buyer_id' => $f['buyer_id'],
        'buyer_name' => $f['buyer_name'],
        'buyer_phone' => $f['buyer_phone'],
        'plot_number' => $f['plot_number'],
        'project_name' => $f['project_name'],
        'sale_number' => $f['sale_number'],
        'installment' => $installmentDisplay,
        'installment_count' => $f['installment_count'],
        'amount' => number_format($f['total_amount']),
        'amount_raw' => $f['total_amount'],
        'due_date' => date('M j, Y', strtotime($f['due_date'])),
        'is_rescheduled' => $isRescheduled,
        'followup_status' => $f['followup_status'] ?? 'pending',
        'followup_notes' => $f['followup_notes'] ?? '',
        'promised_date' => $f['promised_date'] ? date('M j, Y', strtotime($f['promised_date'])) : null,
        'called_at' => $f['called_at'] ? date('g:i A', strtotime($f['called_at'])) : null
    ];
}

echo json_encode([
    'success' => true,
    'pending_count' => $pendingCount,
    'total_count' => count($formatted),
    'followups' => $formatted,
    'today' => date('F j, Y')
]);
