<?php
session_start();
header('Content-Type: application/json');
header('Cache-Control: no-cache, must-revalidate');
include_once('../includes/config.php');

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors in output, log them instead

function sendJsonResponse($success, $message, $data = null) {
    // Ensure nothing else is in the buffer before outputting JSON
    if (function_exists('ob_get_length') && ob_get_length()) {
        @ob_clean();
    }
    header('Content-Type: application/json');
    $response = ['success' => $success, 'message' => $message];
    if ($data !== null) {
        $response['data'] = $data;
    }
    echo json_encode($response);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Check if data is JSON or form data
        $contentType = $_SERVER['CONTENT_TYPE'] ?? '';
        
        if (strpos($contentType, 'application/json') !== false) {
            // Handle JSON data (from POS system)
            $input = file_get_contents('php://input');
            if (empty($input)) {
                sendJsonResponse(false, 'No input data received');
            }
            
            $data = json_decode($input, true);
            
            if (json_last_error() !== JSON_ERROR_NONE) {
                sendJsonResponse(false, 'Invalid JSON data: ' . json_last_error_msg());
            }
            
            $customerID = intval($data['customer_id'] ?? 0);
            $reminderDateTime = $data['reminder_date'] ?? '';
            $reminderText = trim($data['reminder_text'] ?? '');
            
        } else {
            // Handle form data (from area-customers page)
            $action = $_POST['action'] ?? '';
            
            if ($action !== 'add') {
                sendJsonResponse(false, 'Invalid or missing action');
            }
            
            $customerID = intval($_POST['customerId'] ?? 0);
            $reminderDateTime = $_POST['reminderDateTime'] ?? '';
            $reminderText = trim($_POST['reminderText'] ?? '');
        }
        
        $createdBy = $_SESSION['uid'] ?? 1;
        
        if (empty($customerID) || $customerID <= 0) {
            sendJsonResponse(false, 'Valid customer ID is required');
        }
        
        if (empty($reminderDateTime)) {
            sendJsonResponse(false, 'Reminder date and time is required');
        }
        
    // Allow empty reminder text; store as empty string to avoid NOT NULL constraints
    $reminderText = ($reminderText === '') ? '' : $reminderText;
        
        // Validate datetime format
        $dateTime = DateTime::createFromFormat('Y-m-d H:i:s', $reminderDateTime);
        if (!$dateTime) {
            // Try alternative format
            $dateTime = DateTime::createFromFormat('Y-m-d\TH:i', $reminderDateTime);
            if ($dateTime) {
                $reminderDateTime = $dateTime->format('Y-m-d H:i:s');
            } else {
                sendJsonResponse(false, 'Invalid date/time format');
            }
        }
        
    $sql = "INSERT INTO tblcustomerreminders (CustomerID, ReminderDate, ReminderText, CreatedBy) VALUES (?, ?, ?, ?)";
        $stmt = mysqli_prepare($con, $sql);
        
        if (!$stmt) {
            sendJsonResponse(false, 'Database prepare error: ' . mysqli_error($con));
        }
        
    mysqli_stmt_bind_param($stmt, "issi", $customerID, $reminderDateTime, $reminderText, $createdBy);
        
        if (mysqli_stmt_execute($stmt)) {
            sendJsonResponse(true, 'Reminder added successfully');
        } else {
            sendJsonResponse(false, 'Error adding reminder: ' . mysqli_stmt_error($stmt));
        }
        
    } catch (Exception $e) {
        sendJsonResponse(false, 'Server error: ' . $e->getMessage());
    }
    
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        $customerID = intval($_GET['customer_id'] ?? 0);
        
        if ($customerID <= 0) {
            sendJsonResponse(false, 'Valid customer ID is required');
        }
        
        $sql = "SELECT ID, ReminderDate, ReminderText, IsCompleted, CreatedAt 
                FROM tblcustomerreminders 
                WHERE CustomerID = ? 
                ORDER BY ReminderDate DESC";
        $stmt = mysqli_prepare($con, $sql);
        
        if (!$stmt) {
            sendJsonResponse(false, 'Database prepare error: ' . mysqli_error($con));
        }
        
        mysqli_stmt_bind_param($stmt, "i", $customerID);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        
        $reminders = [];
        while ($row = mysqli_fetch_assoc($result)) {
            $reminders[] = $row;
        }
        
        sendJsonResponse(true, 'Reminders retrieved successfully', $reminders);
        
    } catch (Exception $e) {
        sendJsonResponse(false, 'Server error: ' . $e->getMessage());
    }
    
} elseif ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    try {
        $input = file_get_contents('php://input');
        $data = json_decode($input, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            sendJsonResponse(false, 'Invalid JSON data');
        }
        
        $reminderID = intval($data['reminder_id'] ?? 0);
        $isCompleted = intval($data['is_completed'] ?? 0);
        
        if ($reminderID <= 0) {
            sendJsonResponse(false, 'Valid reminder ID is required');
        }
        
        $sql = "UPDATE tblcustomerreminders SET IsCompleted = ? WHERE ID = ?";
        $stmt = mysqli_prepare($con, $sql);
        
        if (!$stmt) {
            sendJsonResponse(false, 'Database prepare error: ' . mysqli_error($con));
        }
        
        mysqli_stmt_bind_param($stmt, "ii", $isCompleted, $reminderID);
        
        if (mysqli_stmt_execute($stmt)) {
            sendJsonResponse(true, 'Reminder updated successfully');
        } else {
            sendJsonResponse(false, 'Error updating reminder: ' . mysqli_stmt_error($stmt));
        }
        
    } catch (Exception $e) {
        sendJsonResponse(false, 'Server error: ' . $e->getMessage());
    }
    
} else {
    sendJsonResponse(false, 'Method not allowed');
}

