<?php
/**
 * ============================================================================
 * ajax/add-reminder.php - Add Farming Reminder
 * ============================================================================
 */
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 ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$userId = getUserId();
$title = $_POST['title'] ?? '';
$description = $_POST['description'] ?? '';
$reminder_date = $_POST['reminder_date'] ?? '';
$reminder_time = $_POST['reminder_time'] ?? null;
$activity_type = $_POST['activity_type'] ?? 'custom';
$schedule_id = $_POST['schedule_id'] ?? null;
$enterprise_id = $_POST['enterprise_id'] ?? null;
$is_recurring = isset($_POST['is_recurring']) ? 1 : 0;
$recurrence_pattern = $_POST['recurrence_pattern'] ?? null;

if (empty($title) || empty($reminder_date)) {
    echo json_encode(['success' => false, 'message' => 'Title and date are required']);
    exit;
}

// Validate date
if (strtotime($reminder_date) < strtotime('today')) {
    echo json_encode(['success' => false, 'message' => 'Reminder date cannot be in the past']);
    exit;
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $sql = "INSERT INTO user_farming_reminders 
            (user_id, enterprise_id, schedule_id, title, description, 
             reminder_date, reminder_time, activity_type, is_recurring, recurrence_pattern) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $db->prepare($sql);
    $stmt->execute([
        $userId,
        $enterprise_id,
        $schedule_id,
        $title,
        $description,
        $reminder_date,
        $reminder_time,
        $activity_type,
        $is_recurring,
        $recurrence_pattern
    ]);
    
    $reminderId = $db->lastInsertId();
    
    // Create notification
    try {
        $notify_sql = "INSERT INTO notifications (user_id, title, message, type, icon, link)
                      VALUES (?, 'Reminder Set', ?, 'success', 'bell', '/learning/schedules.php')";
        $notify_stmt = $db->prepare($notify_sql);
        $notify_stmt->execute([
            $userId,
            "Reminder set for: {$title} on {$reminder_date}"
        ]);
    } catch (PDOException $e) {
        error_log("Error creating notification: " . $e->getMessage());
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Reminder added successfully',
        'reminder_id' => $reminderId
    ]);
    
} catch (PDOException $e) {
    error_log("Database error in add-reminder.php: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Failed to add reminder'
    ]);
}
?>