<?php
/**
 * Email Settings - Admin Panel
 * Path: admin/email-settings.php
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../includes/config.php';

$user_role = $_SESSION['admin_role'] ?? 'admin';
$is_worker = ($user_role == 'worker');

// ============================================
// BLLOKO WORKER NGA EMAIL SETTINGS
// ============================================
if($is_worker) {
    header('Location: dashboard.php?error=access_denied');
    exit();
}

if(!isset($_SESSION['admin_logged_in'])) {
    header('Location: login.php');
    exit();
}

$message = '';
$error = '';

// Include email functions
require_once '../includes/email-functions.php';

// Handle test connection
if(isset($_POST['test_connection'])) {
    $result = testSmtpConnection();
    if($result['success']) {
        $message = $result['message'];
    } else {
        $error = $result['message'];
    }
}

// Handle save settings
if(isset($_POST['save_settings'])) {
    $config_content = '<?php
/**
 * Email Configuration File
 * Last updated: ' . date('Y-m-d H:i:s') . '
 */

// ============================================
// SMTP SETTINGS
// ============================================

define(\'SMTP_HOST\', \'' . addslashes($_POST['smtp_host']) . '\');
define(\'SMTP_AUTH\', true);
define(\'SMTP_USERNAME\', \'' . addslashes($_POST['smtp_username']) . '\');
define(\'SMTP_PASSWORD\', \'' . addslashes($_POST['smtp_password']) . '\');
define(\'SMTP_SECURE\', \'' . addslashes($_POST['smtp_secure']) . '\');
define(\'SMTP_PORT\', ' . (int)$_POST['smtp_port'] . ');

// ============================================
// SENDER INFORMATION
// ============================================

define(\'SENDER_EMAIL\', \'' . addslashes($_POST['sender_email']) . '\');
define(\'SENDER_NAME\', \'' . addslashes($_POST['sender_name']) . '\');

// ============================================
// ADMIN NOTIFICATIONS
// ============================================

define(\'ADMIN_EMAIL\', \'' . addslashes($_POST['admin_email']) . '\');
define(\'ADMIN_NAME\', \'' . addslashes($_POST['admin_name']) . '\');

// ============================================
// EMAIL SETTINGS
// ============================================

define(\'EMAIL_ENABLED\', ' . (isset($_POST['email_enabled']) ? 'true' : 'false') . ');
define(\'EMAIL_ADMIN_ON_BOOKING\', ' . (isset($_POST['email_admin_on_booking']) ? 'true' : 'false') . ');
define(\'EMAIL_CUSTOMER_ON_BOOKING\', ' . (isset($_POST['email_customer_on_booking']) ? 'true' : 'false') . ');

// ============================================
// EMAIL TEMPLATES
// ============================================

function getCustomerBookingTemplate($booking_data, $car_data, $price_data) {
    $site_name = SENDER_NAME;
    $reservation_code = $booking_data[\'reservation_code\'];
    $customer_name = htmlspecialchars($booking_data[\'customer_name\']);
    $car_name = htmlspecialchars($car_data[\'brand\'] . \' \' . $car_data[\'model\']);
    $license_plate = htmlspecialchars($car_data[\'license_plate\']);
    $pickup_date = date(\'d/m/Y\', strtotime($booking_data[\'pickup_date\']));
    $pickup_time = substr($booking_data[\'pickup_time\'], 0, 5);
    $dropoff_date = date(\'d/m/Y\', strtotime($booking_data[\'dropoff_date\']));
    $dropoff_time = substr($booking_data[\'dropoff_time\'], 0, 5);
    $total_price = number_format($price_data[\'grand_total\'], 2);
    
    return <<<HTML
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Booking Confirmation</title></head>
<body style="font-family: Arial, sans-serif;">
    <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
        <div style="background: #0066cc; color: white; padding: 20px; text-align: center;">
            <h2>Booking Confirmation</h2>
            <p>Thank you for choosing {$site_name}!</p>
        </div>
        <div style="background: #f8fafc; padding: 30px; border: 1px solid #e5e7eb;">
            <p>Dear <strong>{$customer_name}</strong>,</p>
            <p>Your reservation has been successfully confirmed.</p>
            <div style="background: #e5e7eb; padding: 10px; text-align: center; font-size: 18px; font-weight: bold; margin: 20px 0;">
                Reservation Code: {$reservation_code}
            </div>
            <p><strong>Vehicle:</strong> {$car_name} ({$license_plate})<br>
            <strong>Pickup:</strong> {$pickup_date} at {$pickup_time}<br>
            <strong>Return:</strong> {$dropoff_date} at {$dropoff_time}<br>
            <strong>Total:</strong> €{$total_price}</p>
            <p>Please bring your driver\'s license and ID at pickup.</p>
            <p>Best regards,<br><strong>{$site_name} Team</strong></p>
        </div>
        <div style="text-align: center; font-size: 12px; color: #6b7280; margin-top: 30px;">
            <p>This is an automated confirmation. Please do not reply.</p>
        </div>
    </div>
</body>
</html>
HTML;
}

function getAdminNotificationTemplate($booking_data, $car_data, $price_data) {
    $reservation_code = $booking_data[\'reservation_code\'];
    $customer_name = htmlspecialchars($booking_data[\'customer_name\']);
    $customer_email = htmlspecialchars($booking_data[\'customer_email\']);
    $customer_phone = htmlspecialchars($booking_data[\'customer_phone\']);
    $car_name = htmlspecialchars($car_data[\'brand\'] . \' \' . $car_data[\'model\']);
    $total_price = number_format($price_data[\'grand_total\'], 2);
    
    return <<<HTML
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>New Reservation</title></head>
<body>
    <h2>🔔 New Reservation Created!</h2>
    <p><strong>Code:</strong> {$reservation_code}</p>
    <p><strong>Customer:</strong> {$customer_name}<br>
    <strong>Email:</strong> {$customer_email}<br>
    <strong>Phone:</strong> {$customer_phone}</p>
    <p><strong>Vehicle:</strong> {$car_name}<br>
    <strong>Total:</strong> €{$total_price}</p>
    <p><a href="http://rent.esc.al/admin/reservations.php?search={$reservation_code}">View in Admin Panel →</a></p>
</body>
</html>
HTML;
}

function getCustomerBookingText($booking_data, $car_data, $price_data) {
    return "Booking Confirmation\n\n" .
           "Reservation Code: {$booking_data[\'reservation_code\']}\n" .
           "Vehicle: {$car_data[\'brand\']} {$car_data[\'model\']}\n" .
           "Pickup: {$booking_data[\'pickup_date\']} at {$booking_data[\'pickup_time\']}\n" .
           "Return: {$booking_data[\'dropoff_date\']} at {$booking_data[\'dropoff_time\']}\n" .
           "Total: €" . number_format($price_data[\'grand_total\'], 2);
}

function getAdminNotificationText($booking_data, $car_data, $price_data) {
    return "New Reservation: {$booking_data[\'reservation_code\']}\n" .
           "Customer: {$booking_data[\'customer_name\']} - {$booking_data[\'customer_phone\']}\n" .
           "Vehicle: {$car_data[\'brand\']} {$car_data[\'model\']}\n" .
           "Total: €" . number_format($price_data[\'grand_total\'], 2);
}
?>';
    
    if(file_put_contents('../includes/email-config.php', $config_content)) {
        $message = "Settings saved successfully!";
        // Refresh the page to load new settings
        header('Location: email-settings.php?msg=saved');
        exit();
    } else {
        $error = "Failed to save settings. Please check file permissions.";
    }
}

// Load current settings
$smtp_host = defined('SMTP_HOST') ? SMTP_HOST : 'smtp.gmail.com';
$smtp_username = defined('SMTP_USERNAME') ? SMTP_USERNAME : '';
$smtp_password = defined('SMTP_PASSWORD') ? SMTP_PASSWORD : '';
$smtp_secure = defined('SMTP_SECURE') ? SMTP_SECURE : 'tls';
$smtp_port = defined('SMTP_PORT') ? SMTP_PORT : 587;
$sender_email = defined('SENDER_EMAIL') ? SENDER_EMAIL : '';
$sender_name = defined('SENDER_NAME') ? SENDER_NAME : 'ESC Rental';
$admin_email = defined('ADMIN_EMAIL') ? ADMIN_EMAIL : '';
$admin_name = defined('ADMIN_NAME') ? ADMIN_NAME : 'ESC Rental Admin';
$email_enabled = !defined('EMAIL_ENABLED') || EMAIL_ENABLED;
$email_admin_on_booking = !defined('EMAIL_ADMIN_ON_BOOKING') || EMAIL_ADMIN_ON_BOOKING;
$email_customer_on_booking = !defined('EMAIL_CUSTOMER_ON_BOOKING') || EMAIL_CUSTOMER_ON_BOOKING;

if(isset($_GET['msg']) && $_GET['msg'] == 'saved') {
    $message = "Settings saved successfully!";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Settings - Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; }
        
        .sidebar {
            width: 260px;
            background: #1a1a2e;
            color: white;
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
        }
        .sidebar-header { padding: 24px 20px; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .sidebar-header h2 { font-size: 18px; font-weight: 600; }
        .sidebar-nav { padding: 20px 0; }
        .sidebar-nav a {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 20px;
            color: #cbd5e1;
            text-decoration: none;
            font-size: 14px;
        }
        .sidebar-nav a i { width: 20px; }
        .sidebar-nav a:hover, .sidebar-nav a.active { background: #0066cc; color: white; }
        
        .main-content { margin-left: 260px; padding: 24px; }
        .page-header { margin-bottom: 24px; }
        .page-header h1 { font-size: 24px; font-weight: 600; }
        
        .settings-container { max-width: 700px; margin: 0 auto; }
        
        .card {
            background: white;
            border-radius: 16px;
            border: 1px solid #e5e7eb;
            overflow: hidden;
            margin-bottom: 24px;
        }
        .card-header {
            background: #f8fafc;
            padding: 16px 20px;
            border-bottom: 1px solid #e5e7eb;
        }
        .card-header h2 {
            font-size: 16px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .card-header h2 i { color: #0066cc; }
        .card-body { padding: 20px; }
        
        .form-group { margin-bottom: 18px; }
        .form-group label {
            display: block;
            margin-bottom: 6px;
            font-weight: 500;
            font-size: 13px;
            color: #374151;
        }
        .form-group input, .form-group select {
            width: 100%;
            padding: 10px 14px;
            border: 1px solid #d1d5db;
            border-radius: 10px;
            font-size: 14px;
        }
        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        
        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 16px;
        }
        .checkbox-group input { width: 18px; height: 18px; }
        
        .btn-primary {
            background: #0066cc;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
        }
        .btn-primary:hover { background: #0052a3; }
        .btn-test { background: #10b981; }
        .btn-test:hover { background: #059669; }
        
        .alert-success {
            background: #d1fae5;
            color: #065f46;
            padding: 14px 18px;
            border-radius: 12px;
            margin-bottom: 20px;
            border-left: 4px solid #10b981;
        }
        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            padding: 14px 18px;
            border-radius: 12px;
            margin-bottom: 20px;
            border-left: 4px solid #dc2626;
        }
        .alert-info {
            background: #eff6ff;
            color: #1e40af;
            padding: 14px 18px;
            border-radius: 12px;
            margin-bottom: 20px;
            border-left: 4px solid #3b82f6;
        }
        
        @media (max-width: 768px) {
            .sidebar { width: 100%; position: relative; height: auto; }
            .main-content { margin-left: 0; }
            .form-row { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="sidebar-header"><h2><i class="fas fa-car"></i> Car Rental Admin</h2></div>
        <div class="sidebar-nav">
            <a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
            <a href="cars.php"><i class="fas fa-car"></i> Cars</a>
            <a href="create-reservation.php"><i class="fas fa-plus-square"></i> Create Reservation</a>
            <a href="reservations.php"><i class="fas fa-calendar-check"></i> Reservations</a>
            <a href="calendar.php"><i class="fas fa-calendar-alt"></i> Calendar</a>
            <a href="price-list.php"><i class="fas fa-tags"></i> Price Rules</a>
            <a href="extras.php"><i class="fas fa-cogs"></i> Extras</a>
            <a href="email-settings.php" class="active"><i class="fas fa-envelope"></i> Email Settings</a>
            <a href="settings.php"><i class="fas fa-cog"></i> Settings</a>
            <a href="manage-admins.php"><i class="fas fa-user-shield"></i> Users</a>
            <a href="clients.php"><i class="fas fa-users"></i> Clients</a>
            <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>
    
    <div class="main-content">
        <div class="page-header">
            <h1><i class="fas fa-envelope"></i> Email Settings</h1>
        </div>
        
        <div class="settings-container">
            <?php if($message): ?>
                <div class="alert-success"><i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($message); ?></div>
            <?php endif; ?>
            <?php if($error): ?>
                <div class="alert-error"><i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>
            
            <div class="alert-info">
                <i class="fas fa-info-circle"></i> 
                <strong>Për Gmail:</strong> Përdorni <strong>App Password</strong>. 
                <a href="https://support.google.com/accounts/answer/185833" target="_blank" style="color: #1e40af;">Si të krijoni →</a>
            </div>
            
            <form method="POST">
                <div class="card">
                    <div class="card-header">
                        <h2><i class="fas fa-server"></i> SMTP Settings</h2>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label>SMTP Host</label>
                            <input type="text" name="smtp_host" value="<?php echo htmlspecialchars($smtp_host); ?>" required>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label>SMTP Username (Email)</label>
                                <input type="email" name="smtp_username" value="<?php echo htmlspecialchars($smtp_username); ?>" required>
                            </div>
                            <div class="form-group">
                                <label>SMTP Password (App Password)</label>
                                <input type="password" name="smtp_password" value="<?php echo htmlspecialchars($smtp_password); ?>" required>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label>Encryption</label>
                                <select name="smtp_secure">
                                    <option value="tls" <?php echo $smtp_secure == 'tls' ? 'selected' : ''; ?>>TLS (Port 587)</option>
                                    <option value="ssl" <?php echo $smtp_secure == 'ssl' ? 'selected' : ''; ?>>SSL (Port 465)</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>Port</label>
                                <input type="number" name="smtp_port" value="<?php echo $smtp_port; ?>" required>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        <h2><i class="fas fa-user"></i> Sender Information</h2>
                    </div>
                    <div class="card-body">
                        <div class="form-row">
                            <div class="form-group">
                                <label>Sender Email</label>
                                <input type="email" name="sender_email" value="<?php echo htmlspecialchars($sender_email); ?>" required>
                            </div>
                            <div class="form-group">
                                <label>Sender Name</label>
                                <input type="text" name="sender_name" value="<?php echo htmlspecialchars($sender_name); ?>" required>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        <h2><i class="fas fa-user-shield"></i> Admin Notifications</h2>
                    </div>
                    <div class="card-body">
                        <div class="form-row">
                            <div class="form-group">
                                <label>Admin Email</label>
                                <input type="email" name="admin_email" value="<?php echo htmlspecialchars($admin_email); ?>" required>
                            </div>
                            <div class="form-group">
                                <label>Admin Name</label>
                                <input type="text" name="admin_name" value="<?php echo htmlspecialchars($admin_name); ?>" required>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        <h2><i class="fas fa-toggle-on"></i> Notification Settings</h2>
                    </div>
                    <div class="card-body">
                        <div class="checkbox-group">
                            <input type="checkbox" name="email_enabled" id="email_enabled" <?php echo $email_enabled ? 'checked' : ''; ?>>
                            <label for="email_enabled">Enable all emails</label>
                        </div>
                        <div class="checkbox-group">
                            <input type="checkbox" name="email_customer_on_booking" id="email_customer" <?php echo $email_customer_on_booking ? 'checked' : ''; ?>>
                            <label for="email_customer">Send confirmation email to customer</label>
                        </div>
                        <div class="checkbox-group">
                            <input type="checkbox" name="email_admin_on_booking" id="email_admin" <?php echo $email_admin_on_booking ? 'checked' : ''; ?>>
                            <label for="email_admin">Send notification email to admin</label>
                        </div>
                    </div>
                </div>
                
                <div style="display: flex; gap: 16px; margin-top: 20px;">
                    <button type="submit" name="save_settings" class="btn-primary"><i class="fas fa-save"></i> Save Settings</button>
                    <button type="submit" name="test_connection" class="btn-primary btn-test"><i class="fas fa-paper-plane"></i> Test Connection</button>
                </div>
            </form>
        </div>
    </div>
</body>
</html>