<?php
/**
 * ADMIN MESSAGE COMPOSER
 * File: admin/messages-compose.php
 * Send messages to vendors, customers, and system-wide announcements
 */

require_once '../app/Core/init.php';

// Check admin authentication
Auth::requireAdmin();

$page_title = "Compose Message";
$active_menu = "messages";

// Initialize models - FIXED: Proper initialization
$notification = new NotificationService();
$vendor_model = new Vendor();
$customer_model = new Customer();
$message_model = new Message();

// Handle message sending
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_message'])) {
    $recipient_type = $_POST['recipient_type'] ?? '';
    $subject = trim($_POST['subject'] ?? '');
    $message = trim($_POST['message'] ?? '');
    
    if (empty($subject) || empty($message)) {
        flash('error', 'Subject and message are required', 'danger');
    } else {
        try {
            $success_count = 0;
            $recipient_name = null;
            $recipient_id = null;
            
            switch ($recipient_type) {
                case 'individual_vendor':
                    $vendor_id = (int)($_POST['vendor_id'] ?? 0);
                    if ($vendor_id > 0) {
                        $vendor = $vendor_model->find($vendor_id);
                        if ($vendor) {
                            $notification->send($vendor['user_id'], $subject, $message, 'info', 'vendor');
                            $success_count = 1;
                            $recipient_name = $vendor['business_name'];
                            $recipient_id = $vendor['user_id'];
                            
                            // Save to messages table
                            $message_model->create([
                                'subject' => $subject,
                                'content' => $message,
                                'recipient_type' => $recipient_type,
                                'recipient_id' => $recipient_id,
                                'recipient_name' => $recipient_name,
                                'sender_id' => $_SESSION['user_id'],
                                'status' => 'sent'
                            ]);
                        }
                    }
                    break;
                    
                case 'individual_customer':
                    $customer_id = (int)($_POST['customer_id'] ?? 0);
                    if ($customer_id > 0) {
                        $customer = $customer_model->find($customer_id);
                        if ($customer) {
                            $notification->send($customer['user_id'], $subject, $message, 'info', 'customer');
                            $success_count = 1;
                            $recipient_name = $customer['first_name'] . ' ' . $customer['last_name'];
                            $recipient_id = $customer['user_id'];
                            
                            // Save to messages table
                            $message_model->create([
                                'subject' => $subject,
                                'content' => $message,
                                'recipient_type' => $recipient_type,
                                'recipient_id' => $recipient_id,
                                'recipient_name' => $recipient_name,
                                'sender_id' => $_SESSION['user_id'],
                                'status' => 'sent'
                            ]);
                        }
                    }
                    break;
                    
                case 'all_vendors':
                    $notification->sendToVendors($subject, $message);
                    $success_count = -1; // Will be updated after count
                    
                    // Save to messages table
                    $message_model->create([
                        'subject' => $subject,
                        'content' => $message,
                        'recipient_type' => $recipient_type,
                        'recipient_id' => null,
                        'recipient_name' => null,
                        'sender_id' => $_SESSION['user_id'],
                        'status' => 'sent'
                    ]);
                    break;
                    
                case 'all_customers':
                    $notification->sendToCustomers($subject, $message);
                    $success_count = -1; // Will be updated after count
                    
                    // Save to messages table
                    $message_model->create([
                        'subject' => $subject,
                        'content' => $message,
                        'recipient_type' => $recipient_type,
                        'recipient_id' => null,
                        'recipient_name' => null,
                        'sender_id' => $_SESSION['user_id'],
                        'status' => 'sent'
                    ]);
                    break;
                    
                case 'all_admins':
                    $notification->sendToAdmins($subject, $message);
                    $success_count = -1; // Will be updated after count
                    
                    // Save to messages table
                    $message_model->create([
                        'subject' => $subject,
                        'content' => $message,
                        'recipient_type' => $recipient_type,
                        'recipient_id' => null,
                        'recipient_name' => null,
                        'sender_id' => $_SESSION['user_id'],
                        'status' => 'sent'
                    ]);
                    break;
            }
            
            if ($success_count !== 0) {
                $recipient_text = [
                    'individual_vendor' => 'vendor',
                    'individual_customer' => 'customer',
                    'all_vendors' => 'all vendors',
                    'all_customers' => 'all customers',
                    'all_admins' => 'all administrators'
                ];
                
                flash('success', "Message sent successfully to {$recipient_text[$recipient_type]}", 'success');
                redirect('messages.php');
            } else {
                flash('error', 'Failed to send message. Please try again.', 'danger');
            }
        } catch (Exception $e) {
            flash('error', 'An error occurred: ' . $e->getMessage(), 'danger');
        }
    }
}

// Get recent data for dropdowns - FIXED: Use proper methods
try {
    $vendors = $vendor_model->getForMessageDropdown(100);
    $customers = $customer_model->getForMessageDropdown(100);
} catch (Exception $e) {
    error_log("Error loading dropdown data: " . $e->getMessage());
    $vendors = [];
    $customers = [];
}

// Handle flash messages
$flash_message = flash('message');

include '../templates/layouts/admin/head.php';
?>

<div class="main-content">
    <?php include '../templates/layouts/admin/header.php'; ?>
    
    <!-- Page Header -->
    <div style="padding: 30px; background: white; border-bottom: 1px solid #eee;">
        <h1 style="font-size: 28px; font-weight: 700; color: var(--dark); margin-bottom: 5px;">
            <i class="fas fa-pen"></i> Compose Message
        </h1>
        <div style="display: flex; gap: 8px; font-size: 14px; color: #666;">
            <a href="index.php" style="color: var(--primary); text-decoration: none;">Home</a>
            <span>/</span>
            <a href="messages.php" style="color: var(--primary); text-decoration: none;">Messages</a>
            <span>/</span>
            <span>Compose</span>
        </div>
    </div>
    
    <!-- Content -->
    <div style="padding: 30px;">
        
        <!-- Flash Messages -->
        <?php if ($flash_message): ?>
            <div class="alert alert-<?= $flash_message['type'] ?>">
                <?= Security::escapeOutput($flash_message['message']) ?>
            </div>
        <?php endif; ?>
        
        <div class="row">
            <div class="col-lg-8">
                <!-- Message Composer -->
                <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                    <h3 style="font-size: 18px; font-weight: 600; margin-bottom: 20px; color: var(--dark);">
                        <i class="fas fa-envelope"></i> New Message
                    </h3>
                    
                    <form method="POST">
                        <input type="hidden" name="send_message" value="1">
                        
                        <!-- Recipient Selection -->
                        <div style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Send To <span style="color: var(--danger);">*</span></label>
                            <select name="recipient_type" id="recipientType" class="form-control" required onchange="toggleRecipientFields()">
                                <option value="">Select recipients...</option>
                                <option value="individual_vendor">Individual Vendor</option>
                                <option value="individual_customer">Individual Customer</option>
                                <option value="all_vendors">All Vendors</option>
                                <option value="all_customers">All Customers</option>
                                <option value="all_admins">All Administrators</option>
                            </select>
                        </div>
                        
                        <!-- Individual Vendor Selection -->
                        <div id="vendorField" style="margin-bottom: 20px; display: none;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Select Vendor</label>
                            <select name="vendor_id" class="form-control">
                                <option value="">Choose a vendor...</option>
                                <?php foreach ($vendors as $vendor): ?>
                                    <option value="<?= $vendor['id'] ?>">
                                        <?= Security::escapeOutput($vendor['business_name'] ?? $vendor['name']) ?> 
                                        (<?= Security::escapeOutput($vendor['email']) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <!-- Individual Customer Selection -->
                        <div id="customerField" style="margin-bottom: 20px; display: none;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Select Customer</label>
                            <select name="customer_id" class="form-control">
                                <option value="">Choose a customer...</option>
                                <?php foreach ($customers as $customer): ?>
                                    <option value="<?= $customer['id'] ?>">
                                        <?= Security::escapeOutput(($customer['first_name'] ?? '') . ' ' . ($customer['last_name'] ?? $customer['name'])) ?> 
                                        (<?= Security::escapeOutput($customer['email']) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <!-- Subject -->
                        <div style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Subject <span style="color: var(--danger);">*</span></label>
                            <input type="text" name="subject" class="form-control" required 
                                   placeholder="Enter message subject..." value="<?= old('subject') ?>">
                        </div>
                        
                        <!-- Message Content -->
                        <div style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Message <span style="color: var(--danger);">*</span></label>
                            <textarea name="message" class="form-control" rows="8" required
                                      placeholder="Enter your message here..."><?= old('message') ?></textarea>
                            <small style="color: #666; font-size: 12px;">
                                Be clear and professional. This message will be sent as a notification.
                            </small>
                        </div>
                        
                        <!-- Quick Templates -->
                        <div style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Quick Templates</label>
                            <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                                <button type="button" class="btn btn-sm btn-outline-primary" onclick="useTemplate('welcome')">Welcome Message</button>
                                <button type="button" class="btn btn-sm btn-outline-primary" onclick="useTemplate('maintenance')">Maintenance Notice</button>
                                <button type="button" class="btn btn-sm btn-outline-primary" onclick="useTemplate('promotion')">Promotional Offer</button>
                                <button type="button" class="btn btn-sm btn-outline-primary" onclick="useTemplate('policy')">Policy Update</button>
                            </div>
                        </div>
                        
                        <!-- Action Buttons -->
                        <div style="display: flex; gap: 15px; align-items: center;">
                            <button type="submit" class="btn btn-primary" style="padding: 12px 30px;">
                                <i class="fas fa-paper-plane"></i> Send Message
                            </button>
                            <a href="messages.php" class="btn btn-secondary" style="padding: 12px 20px;">
                                <i class="fas fa-arrow-left"></i> Back to Messages
                            </a>
                        </div>
                    </form>
                </div>
            </div>
            
            <div class="col-lg-4">
                <!-- Message Guidelines -->
                <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 20px;">
                    <h3 style="font-size: 18px; font-weight: 600; margin-bottom: 20px; color: var(--dark);">
                        <i class="fas fa-lightbulb"></i> Guidelines
                    </h3>
                    
                    <div style="font-size: 14px; color: #666; line-height: 1.6;">
                        <p style="margin-bottom: 15px;"><strong>Best Practices:</strong></p>
                        <ul style="margin: 0 0 15px 20px; padding: 0;">
                            <li>Keep messages clear and concise</li>
                            <li>Use professional language</li>
                            <li>Include actionable information</li>
                            <li>Avoid sensitive topics</li>
                        </ul>
                        
                        <p style="margin-bottom: 15px;"><strong>Message Types:</strong></p>
                        <ul style="margin: 0; padding: 0; list-style: none;">
                            <li><i class="fas fa-info-circle" style="color: var(--info); margin-right: 8px;"></i> Informational</li>
                            <li><i class="fas fa-exclamation-triangle" style="color: var(--warning); margin-right: 8px;"></i> Urgent Notice</li>
                            <li><i class="fas fa-bullhorn" style="color: var(--primary); margin-right: 8px;"></i> Promotional</li>
                            <li><i class="fas fa-tools" style="color: var(--secondary); margin-right: 8px;"></i> Maintenance</li>
                        </ul>
                    </div>
                </div>
                
                <!-- Message Templates -->
                <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                    <h3 style="font-size: 18px; font-weight: 600; margin-bottom: 20px; color: var(--dark);">
                        <i class="fas fa-file-alt"></i> Template Library
                    </h3>
                    
                    <div style="font-size: 14px; color: #666;">
                        <p style="margin-bottom: 15px;">Quick message templates for common scenarios:</p>
                        <ul style="margin: 0; padding: 0; list-style: none;">
                            <li style="margin-bottom: 8px;">
                                <strong>Welcome Message</strong>
                                <br>
                                <small style="color: #999;">For new vendors and customers</small>
                            </li>
                            <li style="margin-bottom: 8px;">
                                <strong>Maintenance Notice</strong>
                                <br>
                                <small style="color: #999;">System downtime announcements</small>
                            </li>
                            <li style="margin-bottom: 8px;">
                                <strong>Promotional Offer</strong>
                                <br>
                                <small style="color: #999;">Special deals and discounts</small>
                            </li>
                            <li style="margin-bottom: 8px;">
                                <strong>Policy Update</strong>
                                <br>
                                <small style="color: #999;">Terms and condition changes</small>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function toggleRecipientFields() {
    const recipientType = document.getElementById('recipientType').value;
    const vendorField = document.getElementById('vendorField');
    const customerField = document.getElementById('customerField');
    
    // Hide all fields first
    vendorField.style.display = 'none';
    customerField.style.display = 'none';
    
    // Show relevant field
    if (recipientType === 'individual_vendor') {
        vendorField.style.display = 'block';
    } else if (recipientType === 'individual_customer') {
        customerField.style.display = 'block';
    }
}

function useTemplate(templateType) {
    const subjectField = document.querySelector('input[name="subject"]');
    const messageField = document.querySelector('textarea[name="message"]');
    
    const templates = {
        welcome: {
            subject: 'Welcome to rentidium!',
            message: 'Welcome to our platform! We\'re excited to have you as part of our community. If you have any questions or need assistance, please don\'t hesitate to contact our support team.'
        },
        maintenance: {
            subject: 'Scheduled Maintenance Notice',
            message: 'We will be performing scheduled maintenance on our platform. During this time, some features may be temporarily unavailable. We apologize for any inconvenience and thank you for your patience.'
        },
        promotion: {
            subject: 'Special Offer for You!',
            message: 'We have an exclusive offer that we\'d love to share with you. Take advantage of this limited-time promotion and make the most of your experience on our platform.'
        },
        policy: {
            subject: 'Important Policy Update',
            message: 'Please be advised that we have updated our terms of service and privacy policy. We recommend reviewing these changes to ensure you\'re aware of any new provisions.'
        }
    };
    
    if (templates[templateType]) {
        subjectField.value = templates[templateType].subject;
        messageField.value = templates[templateType].message;
    }
}

// Validate form before submission
document.querySelector('form').addEventListener('submit', function(e) {
    const recipientType = document.getElementById('recipientType').value;
    const vendorField = document.getElementById('vendorField');
    const customerField = document.getElementById('customerField');
    
    if (recipientType === 'individual_vendor' && vendorField.style.display === 'block') {
        const vendorId = document.querySelector('select[name="vendor_id"]').value;
        if (!vendorId) {
            e.preventDefault();
            alert('Please select a vendor to send the message to.');
            return false;
        }
    }
    
    if (recipientType === 'individual_customer' && customerField.style.display === 'block') {
        const customerId = document.querySelector('select[name="customer_id"]').value;
        if (!customerId) {
            e.preventDefault();
            alert('Please select a customer to send the message to.');
            return false;
        }
    }
});
</script>

<style>
.form-control {
    border: 1px solid #ddd;
    border-radius: 6px;
    padding: 10px 12px;
    font-size: 14px;
    transition: border-color 0.3s;
    width: 100%;
    box-sizing: border-box;
}

.form-control:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.btn {
    border: none;
    border-radius: 6px;
    padding: 10px 20px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    text-decoration: none;
    display: inline-block;
    font-size: 14px;
}

.btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.btn-primary {
    background: var(--primary);
    color: white;
}

.btn-primary:hover {
    background: #0056b3;
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-secondary:hover {
    background: #545b62;
}

.btn-outline-primary {
    background: transparent;
    color: var(--primary);
    border: 1px solid var(--primary);
    padding: 6px 12px;
    font-size: 12px;
}

.btn-outline-primary:hover {
    background: var(--primary);
    color: white;
}

.btn-sm {
    padding: 6px 12px;
    font-size: 12px;
}

.alert {
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert-danger {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

@media (max-width: 768px) {
    .col-lg-4 {
        margin-top: 20px;
    }
}
</style>

<?php include '../templates/layouts/admin/footer.php'; ?>