<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Booking Confirmation Email Template
 * Developer: JOACHIM'S INNOTECH
 */

// Initialize system
require_once dirname(__DIR__, 3) . '/config/config.php';
require_once dirname(__DIR__, 3) . '/config/constants.php';
require_once dirname(__DIR__, 3) . '/config/database.php';
require_once dirname(__DIR__, 3) . '/config/helpers.php';
require_once dirname(__DIR__, 3) . '/config/auth.php';
require_once dirname(__DIR__, 3) . '/config/mailer.php';

// Require authentication
require_auth();

// Get reservation ID from URL
$reservation_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$preview = isset($_GET['preview']) && $_GET['preview'] == 1;
$send = isset($_GET['send']) && $_GET['send'] == 1;

if (!$reservation_id && !$preview) {
    die('Invalid reservation ID');
}

// Get reservation data
if ($reservation_id) {
    $reservation = db_fetch_one("
        SELECT 
            r.*,
            g.guest_id, g.first_name, g.last_name, g.email,
            rt.type_name, rt.type_code,
            rm.room_number,
            DATEDIFF(r.check_out_date, r.check_in_date) as nights
        FROM reservations r
        JOIN guests g ON r.guest_id = g.guest_id
        JOIN room_types rt ON r.room_type_id = rt.room_type_id
        LEFT JOIN rooms rm ON r.room_id = rm.room_id
        WHERE r.reservation_id = ?
    ", [$reservation_id]);

    if (!$reservation) {
        die('Reservation not found');
    }
} else {
    // Preview mode with sample data
    $reservation = [
        'first_name' => 'John',
        'last_name' => 'Doe',
        'email' => 'john.doe@example.com',
        'booking_code' => 'BK-2024-1234',
        'check_in_date' => date('Y-m-d', strtotime('+7 days')),
        'check_out_date' => date('Y-m-d', strtotime('+10 days')),
        'nights' => 3,
        'type_name' => 'Deluxe Room',
        'room_number' => '205',
        'adults' => 2,
        'children' => 1,
        'total_amount' => 750.00,
        'paid_amount' => 0,
        'booking_status' => 'confirmed',
        'booking_source' => 'website'
    ];
}

// Get resort settings
$resort = db_fetch_one("SELECT * FROM resort_settings LIMIT 1");

// Handle send email request
if ($send && $reservation_id) {
    if (!verify_csrf_token($_GET['csrf_token'] ?? '')) {
        die('Invalid security token');
    }
    
    $sent = send_booking_confirmation_email($reservation_id);
    
    if ($sent) {
        set_flash_message('success', 'Confirmation email sent to ' . $reservation['email']);
    } else {
        set_flash_message('danger', 'Failed to send confirmation email');
    }
    
    redirect('../reservations/view.php?id=' . $reservation_id);
}

// Email template
$subject = "Booking Confirmation - {$reservation['booking_code']} - Ruhondo Beach Resort";

$email_html = '
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Booking Confirmation</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            margin: 0;
            padding: 0;
        }
        .container {
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            background: #007bff;
            color: white;
            padding: 30px 20px;
            text-align: center;
        }
        .header h1 {
            margin: 0;
            font-size: 28px;
        }
        .header p {
            margin: 5px 0 0;
            opacity: 0.9;
        }
        .content {
            padding: 30px 20px;
            background: #f9f9f9;
        }
        .booking-details {
            background: white;
            border-radius: 5px;
            padding: 20px;
            margin: 20px 0;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .booking-details h2 {
            color: #007bff;
            margin-top: 0;
            border-bottom: 2px solid #007bff;
            padding-bottom: 10px;
        }
        .detail-row {
            display: flex;
            margin-bottom: 10px;
            border-bottom: 1px solid #eee;
            padding-bottom: 5px;
        }
        .detail-label {
            width: 150px;
            font-weight: bold;
        }
        .detail-value {
            flex: 1;
        }
        .guest-info {
            background: #e3f2fd;
            padding: 15px;
            border-radius: 5px;
            margin: 20px 0;
        }
        .payment-summary {
            background: #f0f0f0;
            padding: 15px;
            border-radius: 5px;
            margin: 20px 0;
        }
        .total-amount {
            font-size: 18px;
            font-weight: bold;
            color: #28a745;
        }
        .button {
            display: inline-block;
            padding: 10px 20px;
            background: #007bff;
            color: white;
            text-decoration: none;
            border-radius: 5px;
            margin: 10px 5px 0 0;
        }
        .button:hover {
            background: #0056b3;
        }
        .footer {
            text-align: center;
            padding: 20px;
            font-size: 12px;
            color: #666;
            background: #f0f0f0;
        }
        .social-links {
            margin: 20px 0;
        }
        .social-links a {
            color: #007bff;
            text-decoration: none;
            margin: 0 10px;
        }
        .hotel-address {
            margin-top: 20px;
            font-style: italic;
        }
        .badge {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 3px;
            font-size: 12px;
            font-weight: bold;
        }
        .badge-success {
            background: #28a745;
            color: white;
        }
        .badge-warning {
            background: #ffc107;
            color: #333;
        }
        @media only screen and (max-width: 600px) {
            .detail-row {
                flex-direction: column;
            }
            .detail-label {
                width: auto;
                margin-bottom: 5px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <h1>' . ($resort['resort_name'] ?? 'Ruhondo Beach Resort') . '</h1>
            <p>Your booking has been confirmed!</p>
        </div>

        <!-- Content -->
        <div class="content">
            <p>Dear <strong>' . $reservation['first_name'] . ' ' . $reservation['last_name'] . '</strong>,</p>
            
            <p>Thank you for choosing ' . ($resort['resort_name'] ?? 'Ruhondo Beach Resort') . '. Your reservation has been confirmed as follows:</p>

            <!-- Booking Details -->
            <div class="booking-details">
                <h2>Booking Details</h2>
                
                <div class="detail-row">
                    <span class="detail-label">Booking Code:</span>
                    <span class="detail-value"><strong>' . $reservation['booking_code'] . '</strong></span>
                </div>
                
                <div class="detail-row">
                    <span class="detail-label">Check-in Date:</span>
                    <span class="detail-value">' . format_date($reservation['check_in_date'], 'l, F j, Y') . '</span>
                </div>
                
                <div class="detail-row">
                    <span class="detail-label">Check-out Date:</span>
                    <span class="detail-value">' . format_date($reservation['check_out_date'], 'l, F j, Y') . '</span>
                </div>
                
                <div class="detail-row">
                    <span class="detail-label">Number of Nights:</span>
                    <span class="detail-value">' . $reservation['nights'] . '</span>
                </div>
                
                <div class="detail-row">
                    <span class="detail-label">Room Type:</span>
                    <span class="detail-value">' . $reservation['type_name'] . '</span>
                </div>';
                
                if (!empty($reservation['room_number'])) {
                    $email_html .= '
                <div class="detail-row">
                    <span class="detail-label">Room Number:</span>
                    <span class="detail-value">' . $reservation['room_number'] . '</span>
                </div>';
                }
                
                $email_html .= '
                <div class="detail-row">
                    <span class="detail-label">Guests:</span>
                    <span class="detail-value">' . $reservation['adults'] . ' Adult(s)';
                    
                    if ($reservation['children'] > 0) {
                        $email_html .= ', ' . $reservation['children'] . ' Child(ren)';
                    }
                    
                    $email_html .= '</span>
                </div>
                
                <div class="detail-row">
                    <span class="detail-label">Booking Status:</span>
                    <span class="detail-value">
                        <span class="badge ' . ($reservation['booking_status'] == 'confirmed' ? 'badge-success' : 'badge-warning') . '">
                            ' . ucfirst($reservation['booking_status']) . '
                        </span>
                    </span>
                </div>
            </div>

            <!-- Guest Information -->
            <div class="guest-info">
                <h3 style="margin-top: 0;">Guest Information</h3>
                <p><strong>Name:</strong> ' . $reservation['first_name'] . ' ' . $reservation['last_name'] . '</p>
                <p><strong>Email:</strong> ' . $reservation['email'] . '</p>
                <p><strong>Booking Source:</strong> ' . ucfirst(str_replace('_', ' ', $reservation['booking_source'])) . '</p>
            </div>

            <!-- Payment Summary -->
            <div class="payment-summary">
                <h3 style="margin-top: 0;">Payment Summary</h3>
                <p><strong>Total Amount:</strong> <span class="total-amount">' . format_currency($reservation['total_amount']) . '</span></p>
                <p><strong>Amount Paid:</strong> ' . format_currency($reservation['paid_amount']) . '</p>
                <p><strong>Balance Due:</strong> ' . format_currency($reservation['total_amount'] - $reservation['paid_amount']) . '</p>';
                
                if (($reservation['total_amount'] - $reservation['paid_amount']) > 0) {
                    $email_html .= '<p><em>Balance to be settled at check-in</em></p>';
                }
                
                $email_html .= '
            </div>

            <!-- Important Information -->
            <div style="background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0;">
                <h4 style="margin-top: 0; color: #856404;">Important Information</h4>
                <ul style="margin-bottom: 0;">
                    <li>Check-in time: ' . substr($resort['checkin_time'] ?? '14:00:00', 0, 5) . '</li>
                    <li>Check-out time: ' . substr($resort['checkout_time'] ?? '11:00:00', 0, 5) . '</li>
                    <li>Please present a valid ID at check-in</li>
                    <li>Cancellation policy applies as per your rate plan</li>
                </ul>
            </div>

            <!-- Action Buttons -->
            <div style="text-align: center; margin: 30px 0;">
                <a href="' . base_url('reservations/view.php?id=' . $reservation_id) . '" class="button">View Booking Online</a>
                <a href="' . base_url('reservations/cancel.php?id=' . $reservation_id) . '" class="button" style="background: #dc3545;">Cancel Booking</a>
            </div>

            <!-- Contact Information -->
            <div style="text-align: center; margin: 20px 0;">
                <p><strong>Need assistance?</strong><br>
                Phone: ' . ($resort['resort_phone'] ?? '+250 788 888 888') . '<br>
                Email: ' . ($resort['resort_email'] ?? 'reservations@ruhondo.com') . '</p>
            </div>
        </div>

        <!-- Footer -->
        <div class="footer">
            <div class="social-links">
                <a href="#">Facebook</a> |
                <a href="#">Instagram</a> |
                <a href="#">Twitter</a>
            </div>
            
            <div class="hotel-address">
                ' . ($resort['resort_address'] ?? 'Lake Ruhondo, Musanze, Rwanda') . '<br>
                ' . ($resort['resort_city'] ?? 'Northern Province') . ', ' . ($resort['resort_country'] ?? 'Rwanda') . '
            </div>
            
            <p style="margin-top: 20px;">
                This email was sent on ' . date('F j, Y \a\t H:i') . '<br>
                &copy; ' . date('Y') . ' ' . ($resort['resort_name'] ?? 'Ruhondo Beach Resort') . '. All rights reserved.
            </p>
        </div>
    </div>
</body>
</html>
';

// Plain text version
$plain_text = "BOOKING CONFIRMATION - {$reservation['booking_code']}\n";
$plain_text .= str_repeat("=", 50) . "\n\n";
$plain_text .= "Dear {$reservation['first_name']} {$reservation['last_name']},\n\n";
$plain_text .= "Thank you for choosing " . ($resort['resort_name'] ?? 'Ruhondo Beach Resort') . ". Your reservation has been confirmed.\n\n";
$plain_text .= "BOOKING DETAILS:\n";
$plain_text .= "- Booking Code: {$reservation['booking_code']}\n";
$plain_text .= "- Check-in: " . format_date($reservation['check_in_date']) . "\n";
$plain_text .= "- Check-out: " . format_date($reservation['check_out_date']) . "\n";
$plain_text .= "- Nights: {$reservation['nights']}\n";
$plain_text .= "- Room Type: {$reservation['type_name']}\n";
if (!empty($reservation['room_number'])) {
    $plain_text .= "- Room Number: {$reservation['room_number']}\n";
}
$plain_text .= "- Guests: {$reservation['adults']} Adult(s)";
if ($reservation['children'] > 0) {
    $plain_text .= ", {$reservation['children']} Child(ren)";
}
$plain_text .= "\n\n";
$plain_text .= "PAYMENT SUMMARY:\n";
$plain_text .= "- Total Amount: " . format_currency($reservation['total_amount']) . "\n";
$plain_text .= "- Amount Paid: " . format_currency($reservation['paid_amount']) . "\n";
$plain_text .= "- Balance Due: " . format_currency($reservation['total_amount'] - $reservation['paid_amount']) . "\n\n";
$plain_text .= "IMPORTANT INFORMATION:\n";
$plain_text .= "- Check-in time: " . substr($resort['checkin_time'] ?? '14:00:00', 0, 5) . "\n";
$plain_text .= "- Check-out time: " . substr($resort['checkout_time'] ?? '11:00:00', 0, 5) . "\n";
$plain_text .= "- Please present a valid ID at check-in\n\n";
$plain_text .= "View your booking online: " . base_url('reservations/view.php?id=' . $reservation_id) . "\n";
$plain_text .= "Need to cancel? " . base_url('reservations/cancel.php?id=' . $reservation_id) . "\n\n";
$plain_text .= "Contact us:\n";
$plain_text .= "Phone: " . ($resort['resort_phone'] ?? '+250 788 888 888') . "\n";
$plain_text .= "Email: " . ($resort['resort_email'] ?? 'reservations@ruhondo.com') . "\n\n";
$plain_text .= "Thank you for choosing " . ($resort['resort_name'] ?? 'Ruhondo Beach Resort') . "!\n";
$plain_text .= str_repeat("=", 50) . "\n";
$plain_text .= "This email was sent on " . date('Y-m-d H:i') . "\n";

// If preview mode, display the HTML
if ($preview) {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Email Preview - Booking Confirmation</title>
        <style>
            body {
                background: #f0f0f0;
                font-family: Arial, sans-serif;
                padding: 20px;
            }
            .email-container {
                max-width: 650px;
                margin: 0 auto;
                background: white;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            }
            .toolbar {
                background: #333;
                color: white;
                padding: 10px;
                text-align: center;
                margin-bottom: 20px;
            }
            .toolbar button {
                margin: 0 5px;
            }
            .plain-text-preview {
                margin-top: 20px;
                background: #f9f9f9;
                padding: 15px;
                border: 1px solid #ddd;
                white-space: pre-wrap;
                font-family: monospace;
                font-size: 12px;
            }
        </style>
    </head>
    <body>
        <div class="toolbar">
            <button onclick="window.print()" class="btn btn-primary">Print Preview</button>
            <button onclick="window.close()" class="btn btn-secondary">Close</button>
        </div>
        
        <div class="email-container">
            <?php echo $email_html; ?>
        </div>
        
        <div class="plain-text-preview">
            <strong>Plain Text Version:</strong><br>
            <?php echo nl2br($plain_text); ?>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// If we're here, we're sending the email
function send_booking_confirmation_email($reservation_id) {
    global $email_html, $plain_text;
    
    $reservation = db_fetch_one("
        SELECT r.*, g.email, g.first_name, g.last_name
        FROM reservations r
        JOIN guests g ON r.guest_id = g.guest_id
        WHERE r.reservation_id = ?
    ", [$reservation_id]);
    
    if (!$reservation || !$reservation['email']) {
        return false;
    }
    
    $subject = "Booking Confirmation - {$reservation['booking_code']} - Ruhondo Beach Resort";
    
    return send_email($reservation['email'], $subject, $email_html, $plain_text);
}

// If this file is accessed directly without preview or send, show usage info
if (!$preview && !$send) {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Email Template - Booking Confirmation</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <div class="container mt-5">
            <div class="card">
                <div class="card-header">
                    <h3>Booking Confirmation Email Template</h3>
                </div>
                <div class="card-body">
                    <p>This template is used for sending booking confirmations to guests.</p>
                    
                    <h5>Usage:</h5>
                    <ul>
                        <li><a href="?id=<?php echo $reservation_id; ?>&preview=1" target="_blank">Preview Email</a></li>
                        <li><a href="?id=<?php echo $reservation_id; ?>&send=1&csrf_token=<?php echo csrf_token(); ?>" onclick="return confirm('Send confirmation email to guest?')">Send to Guest</a></li>
                    </ul>
                    
                    <hr>
                    
                    <h5>Available Variables:</h5>
                    <ul>
                        <li>{guest_name} - Guest full name</li>
                        <li>{booking_code} - Booking reference</li>
                        <li>{check_in_date} - Check-in date</li>
                        <li>{check_out_date} - Check-out date</li>
                        <li>{nights} - Number of nights</li>
                        <li>{room_type} - Room type name</li>
                        <li>{room_number} - Assigned room (if any)</li>
                        <li>{adults} - Number of adults</li>
                        <li>{children} - Number of children</li>
                        <li>{total_amount} - Total amount</li>
                        <li>{paid_amount} - Amount paid</li>
                        <li>{balance} - Balance due</li>
                        <li>{booking_status} - Booking status</li>
                        <li>{booking_source} - Booking source</li>
                    </ul>
                </div>
            </div>
        </div>
    </body>
    </html>
    <?php
}
?>