<?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', 'FRONT_OFFICE'];
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();
}

$invoice_id = isset($_POST['invoice_id']) ? intval($_POST['invoice_id']) : 0;
$reminder_type = isset($_POST['reminder_type']) ? $_POST['reminder_type'] : 'SMS'; // SMS or EMAIL

if ($invoice_id == 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid invoice ID']);
    exit();
}

try {
    // Get invoice and patient details
    $query = "SELECT i.*, 
              u.full_name as patient_name, u.phone_number, u.email,
              pat.patient_number,
              hs.hospital_name, hs.phone as hospital_phone, hs.email as hospital_email
              FROM invoices i
              JOIN patients pat ON i.patient_id = pat.patient_id
              JOIN users u ON pat.user_id = u.user_id
              CROSS JOIN hospital_settings hs
              WHERE i.invoice_id = $invoice_id AND i.balance > 0";
    
    $result = mysqli_query($conn, $query);
    
    if (mysqli_num_rows($result) == 0) {
        throw new Exception("Invoice not found or has no outstanding balance");
    }
    
    $invoice = mysqli_fetch_assoc($result);
    
    // Prepare message
    $message = "Dear {$invoice['patient_name']},\n\n";
    $message .= "This is a payment reminder for Invoice #{$invoice['invoice_number']}.\n\n";
    $message .= "Invoice Date: " . date('d M Y', strtotime($invoice['invoice_date'])) . "\n";
    $message .= "Total Amount: KES " . number_format($invoice['total_amount'], 2) . "\n";
    $message .= "Amount Paid: KES " . number_format($invoice['amount_paid'], 2) . "\n";
    $message .= "Outstanding Balance: KES " . number_format($invoice['balance'], 2) . "\n\n";
    $message .= "Please settle this amount at your earliest convenience.\n\n";
    $message .= "For inquiries, contact us at {$invoice['hospital_phone']}.\n\n";
    $message .= "Thank you,\n{$invoice['hospital_name']}";
    
    $sent = false;
    $send_method = '';
    
    // Send SMS
    if ($reminder_type == 'SMS' || $reminder_type == 'BOTH') {
        if (!empty($invoice['phone_number'])) {
            // SMS sending logic here - integrate with your SMS provider
            // For now, we'll simulate success
            
            // Example SMS API call (uncomment and configure for your SMS provider)
            /*
            $sms_api_url = "https://your-sms-provider.com/api/send";
            $sms_data = [
                'phone' => $invoice['phone_number'],
                'message' => $message,
                'sender_id' => 'HOSPITAL'
            ];
            
            $ch = curl_init($sms_api_url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($sms_data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'Authorization: Bearer YOUR_SMS_API_KEY'
            ]);
            
            $response = curl_exec($ch);
            curl_close($ch);
            */
            
            $sent = true;
            $send_method = 'SMS';
        }
    }
    
    // Send Email
    if ($reminder_type == 'EMAIL' || $reminder_type == 'BOTH') {
        if (!empty($invoice['email'])) {
            $subject = "Payment Reminder - Invoice #{$invoice['invoice_number']}";
            $headers = "From: {$invoice['hospital_email']}\r\n";
            $headers .= "Reply-To: {$invoice['hospital_email']}\r\n";
            $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
            
            if (mail($invoice['email'], $subject, $message, $headers)) {
                $sent = true;
                $send_method = ($send_method == 'SMS') ? 'SMS & EMAIL' : 'EMAIL';
            }
        }
    }
    
    if ($sent) {
        // 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_id, 
                      'Sent payment reminder via $send_method to {$invoice['patient_name']} for invoice {$invoice['invoice_number']}', 
                      '{$_SERVER['REMOTE_ADDR']}')";
        mysqli_query($conn, $log_query);
        
        // Update invoice with reminder sent date
        mysqli_query($conn, "UPDATE invoices SET updated_at = NOW() WHERE invoice_id = $invoice_id");
        
        echo json_encode([
            'success' => true,
            'message' => "Payment reminder sent successfully via $send_method",
            'send_method' => $send_method
        ]);
    } else {
        throw new Exception("Failed to send reminder. Please check contact information.");
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

mysqli_close($conn);
?>