<?php
/**
 * Update Payment Follow-up AJAX Endpoint
 * LandSales Pro - Mark follow-ups as called, paid, or reschedule
 */
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;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Invalid method']);
    exit;
}

$userId = $_SESSION['user_id'];
$staffId = $_SESSION['staff_user_id'] ?? $_SESSION['user_id'];
$today = date('Y-m-d');

// Get POST data
$input = json_decode(file_get_contents('php://input'), true);

$scheduleId = intval($input['schedule_id'] ?? 0);
$action = $input['action'] ?? '';
$notes = trim($input['notes'] ?? '');
$promisedDate = $input['promised_date'] ?? null;

if (!$scheduleId || !in_array($action, ['called', 'paid', 'rescheduled', 'no_answer', 'promised_today'])) {
    echo json_encode(['success' => false, 'error' => 'Invalid parameters']);
    exit;
}

// Verify the schedule belongs to this user
$schedule = db_fetch_one("
    SELECT ps.*, s.user_id, s.id as sale_id
    FROM payment_schedule ps
    JOIN sales s ON ps.sale_id = s.id
    WHERE ps.id = ? AND s.user_id = ?
", 'ii', [$scheduleId, $userId]);

if (!$schedule) {
    echo json_encode(['success' => false, 'error' => 'Payment schedule not found']);
    exit;
}

// Check if there's an existing followup for today
$existingFollowup = db_fetch_one("
    SELECT id FROM payment_followups
    WHERE payment_schedule_id = ? AND followup_date = ?
", 'is', [$scheduleId, $today]);

if ($existingFollowup) {
    // Update existing followup
    $sql = "UPDATE payment_followups SET
        status = ?,
        notes = ?,
        promised_date = ?,
        called_by = ?,
        called_at = NOW(),
        updated_at = NOW()
        WHERE id = ?";

    $result = db_execute($sql, 'sssii', [
        $action,
        $notes,
        $action === 'rescheduled' ? $promisedDate : null,
        $staffId,
        $existingFollowup['id']
    ]);
} else {
    // Create new followup record
    $sql = "INSERT INTO payment_followups
        (payment_schedule_id, user_id, followup_date, status, notes, promised_date, called_by, called_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";

    $result = db_execute($sql, 'iissssi', [
        $scheduleId,
        $userId,
        $today,
        $action,
        $notes,
        $action === 'rescheduled' ? $promisedDate : null,
        $staffId
    ]);
}

if (!$result) {
    echo json_encode(['success' => false, 'error' => 'Failed to update followup']);
    exit;
}

// If marked as paid, we should also update the payment_schedule status
if ($action === 'paid') {
    // Note: This just marks the followup as paid - actual payment recording
    // should be done through the payments page with proper amount entry
    // But we can update the schedule status
    db_execute("UPDATE payment_schedule SET status = 'paid', paid_date = ? WHERE id = ?", 'si', [$today, $scheduleId]);
}

// If rescheduled, create a followup entry for the promised date
if ($action === 'rescheduled' && $promisedDate) {
    // Check if followup exists for promised date
    $existingPromised = db_fetch_one("
        SELECT id FROM payment_followups
        WHERE payment_schedule_id = ? AND followup_date = ?
    ", 'is', [$scheduleId, $promisedDate]);

    if (!$existingPromised) {
        // Create followup for promised date
        db_execute("
            INSERT INTO payment_followups
            (payment_schedule_id, user_id, followup_date, status, notes)
            VALUES (?, ?, ?, 'pending', ?)
        ", 'iiss', [
            $scheduleId,
            $userId,
            $promisedDate,
            "Rescheduled from {$today}: {$notes}"
        ]);
    }
}

echo json_encode([
    'success' => true,
    'message' => 'Follow-up updated successfully',
    'action' => $action
]);
