<?php
session_start();
header('Content-Type: application/json');

include '../layouts/dbconn.php';

// Check authentication
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Check permissions
$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ACCOUNTANT'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

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

$reminder_type = isset($_POST['reminder_type']) ? $_POST['reminder_type'] : 'SMS'; // SMS or EMAIL
$min_balance = isset($_POST['min_balance']) ? floatval($_POST['min_balance']) : 1000;
$days_overdue = isset($_POST['days_overdue']) ? intval($_POST['days_overdue']) : 7;

try {
    // Get hospital settings
    $settings_query = "SELECT * FROM hospital_settings LIMIT 1";
    $settings_result = mysqli_query($conn, $settings_query);
    $hospital = mysqli_fetch_assoc($settings_result);
    
    // Get invoices with outstanding balances
    $query = "SELECT i.*, 
              u.full_name as patient_name, u.phone_number, u.email,
              pat.patient_number,
              DATEDIFF(CURDATE(), i.due_date) as days_past_due
              FROM invoices i
              JOIN patients pat ON i.patient_id = pat.patient_id
              JOIN users u ON pat.user_id = u.user_id
              WHERE i.balance >= $min_balance
              AND i.status IN ('PENDING', 'PARTIAL')
              AND DATEDIFF(CURDATE(), i.due_date) >= $days_overdue
              ORDER BY i.balance DESC";
    
    $result = mysqli_query($conn, $query);
    
    if (mysqli_num_rows($result) == 0) {
        throw new Exception("No invoices found matching the criteria");
    }
    
    $sent_count = 0;
    $failed_count = 0;
    $total_count = mysqli_num_rows($result);
    
    while ($invoice = mysqli_fetch_assoc($result)) {
        // Prepare message
        $message = "Dear {$invoice['patient_name']},\n\n";
        $message .= "Payment Reminder - Invoice #{$invoice['invoice_number']}\n\n";
        $message .= "Your payment is {$invoice['days_past_due']} days overdue.\n\n";
        $message .= "Outstanding Balance: KES " . number_format($invoice['balance'], 2) . "\n";
        $message .= "Due Date: " . date('d M Y', strtotime($invoice['due_date'])) . "\n\n";
        $message .= "Please settle this amount immediately to avoid service interruption.\n\n";
        $message .= "Contact: {$hospital['phone']}\n\n";
        $message .= "Thank you,\n{$hospital['hospital_name']}";
        
        $sent = false;
        
        // Send SMS
        if (($reminder_type == 'SMS' || $reminder_type == 'BOTH') && !empty($invoice['phone_number'])) {
            // SMS API integration here
            $sent = true; // Simulated success
        }
        
        // Send Email
        if (($reminder_type == 'EMAIL' || $reminder_type == 'BOTH') && !empty($invoice['email'])) {
            $subject = "URGENT: Payment Reminder - Invoice #{$invoice['invoice_number']}";
            $headers = "From: {$hospital['email']}\r\n";
            $headers .= "Reply-To: {$hospital['email']}\r\n";
            $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
            
            if (mail($invoice['email'], $subject, $message, $headers)) {
                $sent = true;
            }
        }
        
        if ($sent) {
            $sent_count++;
            
            // Log the reminder
            $log_query = "INSERT INTO activity_logs 
                         (user_id, action, entity_type, entity_id, description, ip_address)
                         VALUES 
                         ({$_SESSION['user_id']}, 'SEND', 'INVOICE', {$invoice['invoice_id']}, 
                          'Bulk reminder sent via $reminder_type - Invoice {$invoice['invoice_number']}', 
                          '{$_SERVER['REMOTE_ADDR']}')";
            mysqli_query($conn, $log_query);
        } else {
            $failed_count++;
        }
    }
    
    echo json_encode([
        'success' => true,
        'message' => "Bulk reminders sent successfully",
        'sent_count' => $sent_count,
        'failed_count' => $failed_count,
        'total_count' => $total_count
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

mysqli_close($conn);
?>