<?php
/**
 * Send Quotation via Email
 */

require_once dirname(__DIR__) . '/config/init.php';
require_auth();

// Check permission
if (!has_permission('quotations.send')) {
    $_SESSION['error'] = "You don't have permission to send quotations";
    header("Location: index.php");
    exit;
}

// Get quotation ID from POST
$quotation_id = $_POST['quotation_id'] ?? $_GET['id'] ?? 0;

// Fetch quotation details
$quotation = db_fetch_one("
    SELECT q.*, u.username as created_by_name
    FROM quotations q
    LEFT JOIN users u ON q.created_by = u.user_id
    WHERE q.quotation_id = ?
", [$quotation_id]);

if (!$quotation) {
    $_SESSION['error'] = "Quotation not found";
    header("Location: index.php");
    exit;
}

// Fetch quotation items
$items = db_fetch_all("
    SELECT * FROM quotation_items 
    WHERE quotation_id = ?
    ORDER BY item_id
", [$quotation_id]) ?: [];

// Check if customer has email
if (empty($quotation['customer_email'])) {
    $_SESSION['error'] = "Customer email address is required to send quotation";
    header("Location: view.php?id=" . $quotation_id);
    exit;
}

// Handle email sending
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_email'])) {
    try {
        $to = $quotation['customer_email'];
        $subject = "Quotation: " . $quotation['quotation_number'] . " from Ruhondo Beach Resort";
        
        // Build email content
        $message = "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; }
                .header { background-color: #007bff; color: white; padding: 20px; text-align: center; }
                .content { padding: 20px; }
                table { width: 100%; border-collapse: collapse; margin: 20px 0; }
                th { background-color: #f2f2f2; padding: 10px; text-align: left; }
                td { padding: 10px; border-bottom: 1px solid #ddd; }
                .total { font-size: 18px; font-weight: bold; }
                .footer { margin-top: 30px; padding: 20px; background-color: #f8f9fa; text-align: center; }
            </style>
        </head>
        <body>
            <div class='header'>
                <h2>Ruhondo Beach Resort</h2>
                <h3>Price Quotation</h3>
            </div>
            
            <div class='content'>
                <p>Dear <strong>" . htmlspecialchars($quotation['customer_name']) . "</strong>,</p>
                
                <p>Thank you for choosing Ruhondo Beach Resort. Please find below your quotation details:</p>
                
                <table>
                    <tr>
                        <td><strong>Quotation Number:</strong></td>
                        <td>" . $quotation['quotation_number'] . "</td>
                    </tr>
                    <tr>
                        <td><strong>Issue Date:</strong></td>
                        <td>" . date('d M Y', strtotime($quotation['issue_date'])) . "</td>
                    </tr>
                    <tr>
                        <td><strong>Valid Until:</strong></td>
                        <td>" . date('d M Y', strtotime($quotation['valid_until'])) . "</td>
                    </tr>
                </table>
                
                <h4>Quotation Items</h4>
                <table>
                    <thead>
                        <tr>
                            <th>QTY</th>
                            <th>Description</th>
                            <th>Unit Price</th>
                            <th>Subtotal</th>
                        </tr>
                    </thead>
                    <tbody>";
        
        foreach ($items as $item) {
            $message .= "
                        <tr>
                            <td>" . $item['quantity'] . "</td>
                            <td>" . htmlspecialchars($item['description']) . "</td>
                            <td>" . format_currency($item['unit_price']) . "</td>
                            <td>" . format_currency($item['subtotal']) . "</td>
                        </tr>";
        }
        
        $message .= "
                    </tbody>
                </table>
                
                <table style='width: 300px; float: right;'>
                    <tr>
                        <td><strong>Subtotal:</strong></td>
                        <td>" . format_currency($quotation['subtotal']) . "</td>
                    </tr>
                    <tr>
                        <td><strong>VAT (15%):</strong></td>
                        <td>" . format_currency($quotation['vat_amount']) . "</td>
                    </tr>
                    <tr class='total'>
                        <td><strong>TOTAL:</strong></td>
                        <td><strong>" . format_currency($quotation['total_amount']) . "</strong></td>
                    </tr>
                </table>
                
                <div style='clear: both;'></div>";
        
        if (!empty($quotation['notes'])) {
            $message .= "
                <div style='margin-top: 30px;'>
                    <h4>Notes:</h4>
                    <p>" . nl2br(htmlspecialchars($quotation['notes'])) . "</p>
                </div>";
        }
        
        $message .= "
                <p>You can view and download the full quotation by clicking the button below:</p>
                
                <p style='text-align: center;'>
                    <a href='" . base_url("quotations/view.php?id=" . $quotation_id) . "' 
                       style='background-color: #28a745; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>
                        View Full Quotation
                    </a>
                </p>
                
                <p>If you have any questions, please don't hesitate to contact us.</p>
                
                <p>Best regards,<br>
                <strong>Ruhondo Beach Resort Team</strong><br>
                Lake Ruhondo, Musanze<br>
                Tel: +250 123 456 789<br>
                Email: reservations@ruhondobeach.com</p>
            </div>
            
            <div class='footer'>
                <small>This is an automated message from Ruhondo Beach Resort HMS System. Please do not reply to this email.</small>
            </div>
        </body>
        </html>";
        
        // Email headers
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        $headers .= "From: reservations@ruhondobeach.com" . "\r\n";
        $headers .= "Reply-To: reservations@ruhondobeach.com" . "\r\n";
        
        // Send email
        if (mail($to, $subject, $message, $headers)) {
            // Update quotation status to 'sent'
            db_update('quotations', ['status' => 'sent'], 'quotation_id = ?', [$quotation_id]);
            
            // Log activity
            $current_user = current_user();
            log_activity($current_user['user_id'], 'send', 'quotation', $quotation_id, "Sent quotation {$quotation['quotation_number']} to {$quotation['customer_email']}");
            
            $_SESSION['success'] = "Quotation sent successfully to " . $quotation['customer_email'];
        } else {
            throw new Exception("Failed to send email");
        }
        
    } catch (Exception $e) {
        $_SESSION['error'] = "Error sending quotation: " . $e->getMessage();
    }
    
    header("Location: view.php?id=" . $quotation_id);
    exit;
}

// Include header
include dirname(__DIR__) . '/views/partials/header.php';
?>

<div class="content-wrapper">
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Send Quotation</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                        <li class="breadcrumb-item"><a href="index.php">Quotations</a></li>
                        <li class="breadcrumb-item"><a href="view.php?id=<?php echo $quotation_id; ?>">View</a></li>
                        <li class="breadcrumb-item active">Send</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-8 offset-md-2">
                    <div class="card card-info">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-paper-plane"></i>
                                Send Quotation via Email
                            </h3>
                        </div>
                        <div class="card-body">
                            <div class="alert alert-info">
                                <i class="icon fas fa-info"></i>
                                You are about to send quotation <strong><?php echo $quotation['quotation_number']; ?></strong> to the customer.
                            </div>
                            
                            <table class="table table-bordered">
                                <tr>
                                    <th style="width: 200px;">Quotation Number</th>
                                    <td><?php echo htmlspecialchars($quotation['quotation_number']); ?></td>
                                </tr>
                                <tr>
                                    <th>Customer</th>
                                    <td><?php echo htmlspecialchars($quotation['customer_name']); ?></td>
                                </tr>
                                <tr>
                                    <th>Customer Email</th>
                                    <td>
                                        <span class="badge badge-info"><?php echo htmlspecialchars($quotation['customer_email']); ?></span>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Total Amount</th>
                                    <td><?php echo format_currency($quotation['total_amount']); ?></td>
                                </tr>
                                <tr>
                                    <th>Valid Until</th>
                                    <td><?php echo date('d M Y', strtotime($quotation['valid_until'])); ?></td>
                                </tr>
                            </table>
                            
                            <div class="card card-primary mt-4">
                                <div class="card-header">
                                    <h3 class="card-title">Email Preview</h3>
                                </div>
                                <div class="card-body">
                                    <div class="form-group">
                                        <label>To:</label>
                                        <input type="email" class="form-control" value="<?php echo htmlspecialchars($quotation['customer_email']); ?>" readonly>
                                    </div>
                                    <div class="form-group">
                                        <label>Subject:</label>
                                        <input type="text" class="form-control" value="Quotation: <?php echo $quotation['quotation_number']; ?> from Ruhondo Beach Resort" readonly>
                                    </div>
                                    <div class="form-group">
                                        <label>Message Preview:</label>
                                        <div class="border p-3" style="max-height: 300px; overflow-y: auto;">
                                            <p>Dear <strong><?php echo htmlspecialchars($quotation['customer_name']); ?></strong>,</p>
                                            <p>Thank you for choosing Ruhondo Beach Resort. Please find below your quotation details:</p>
                                            <p>Quotation Number: <?php echo $quotation['quotation_number']; ?><br>
                                            Valid Until: <?php echo date('d M Y', strtotime($quotation['valid_until'])); ?></p>
                                            <p>Total Amount: <?php echo format_currency($quotation['total_amount']); ?></p>
                                            <p>A PDF version of this quotation is attached to this email.</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <form method="POST">
                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                <input type="hidden" name="quotation_id" value="<?php echo $quotation_id; ?>">
                                <input type="hidden" name="send_email" value="1">
                                
                                <div class="text-center">
                                    <button type="submit" class="btn btn-info btn-lg">
                                        <i class="fas fa-paper-plane"></i> Send Quotation Now
                                    </button>
                                    <a href="view.php?id=<?php echo $quotation_id; ?>" class="btn btn-secondary btn-lg">
                                        <i class="fas fa-times"></i> Cancel
                                    </a>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<?php include dirname(__DIR__) . '/views/partials/footer.php'; ?>