<?php
/**
 * ============================================================================
 * ajax/complete-reminder.php - Mark Reminder as Completed
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

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

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

if (!isset($_POST['id'])) {
    echo json_encode(['success' => false, 'message' => 'Reminder ID required']);
    exit;
}

$reminderId = intval($_POST['id']);
$userId = getUserId();

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Verify ownership
    $check_sql = "SELECT id FROM user_farming_reminders WHERE id = ? AND user_id = ?";
    $check_stmt = $db->prepare($check_sql);
    $check_stmt->execute([$reminderId, $userId]);
    
    if (!$check_stmt->fetch()) {
        echo json_encode(['success' => false, 'message' => 'Reminder not found']);
        exit;
    }
    
    // Update reminder status
    $sql = "UPDATE user_farming_reminders 
            SET status = 'completed', completed_at = NOW() 
            WHERE id = ? AND user_id = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute([$reminderId, $userId]);
    
    echo json_encode([
        'success' => true,
        'message' => 'Reminder marked as completed'
    ]);
    
} catch (PDOException $e) {
    error_log("Database error in complete-reminder.php: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Failed to update reminder'
    ]);
}
?>