<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
require_once 'db.php';
$response = [
'success' => false,
'message' => 'Invalid request'
];
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
try {
// Validate and sanitize input
$user_phone = filter_input(INPUT_GET, 'user_phone', FILTER_SANITIZE_STRING);
$partner_level = filter_input(INPUT_GET, 'partner_level', FILTER_SANITIZE_STRING) ?? 'Basic';
if (empty($user_phone)) {
throw new Exception("Missing user phone number");
}
// Prepare SQL to fetch active notifications
$stmt = $pdo->prepare("
SELECT
id,
title,
description,
type,
image_url,
start_date,
end_date,
priority,
created_at
FROM `partner_notifications`
WHERE
is_active = TRUE
AND (target_partner_level = 'All' OR target_partner_level = :partner_level)
AND (start_date IS NULL OR start_date <= CURRENT_DATE)
AND (end_date IS NULL OR end_date >= CURRENT_DATE)
ORDER BY
priority DESC,
created_at DESC
LIMIT 10
");
$stmt->bindParam(':partner_level', $partner_level);
$stmt->execute();
$notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
// If no notifications found, generate some default notifications
if (empty($notifications)) {
$notifications = [
[
'id' => 1,
'title' => 'Welcome to AgriExpert Partner Program',
'description' => 'Stay tuned for exciting updates and offers for our valued partners!',
'type' => 'update',
'image_url' => null,
'start_date' => date('Y-m-d'),
'end_date' => null,
'priority' => 'low',
'created_at' => date('Y-m-d H:i:s')
]
];
}
$response = [
'success' => true,
'message' => 'Notifications retrieved successfully',
'notifications' => $notifications
];
} catch(PDOException $e) {
error_log("Database Error: " . $e->getMessage());
$response = [
'success' => false,
'message' => 'Database error: ' . $e->getMessage()
];
} catch(Exception $e) {
error_log("Validation Error: " . $e->getMessage());
$response = [
'success' => false,
'message' => $e->getMessage()
];
}
}
// Send JSON response
echo json_encode($response);
exit();
?>