<?php 
// Include session handling
try {
    include_once 'services/session.php';
} catch (Exception $e) {
    die("Error including session.php: " . $e->getMessage());
}

// Check if user is logged in
if (!isset($_SESSION['user']) || empty($_SESSION['user'])) {
    header('Location: auth-login.php?error=session_expired');
    exit();
}

// Get user details
$user_role = $_SESSION['role_name'] ?? 'Customer';
$user_id = $_SESSION['user_id'] ?? 0;
$user_name = $_SESSION['full_name'] ?? $_SESSION['user'];

// Only allow customers
if ($user_role !== 'Customer') {
    header('Location: auth-login.php?error=access_denied');
    exit();
}

// Include database connection
try {
    require_once 'layouts/dbconn.php';
} catch (Exception $e) {
    die("Error including database connection: " . $e->getMessage());
}

// Test database connection
if (!isset($conn) || $conn->connect_error) {
    die("Database connection failed: " . ($conn->connect_error ?? 'Connection object not found'));
}

// Function to safely execute queries
if (!function_exists('safeQuery')) {
    function safeQuery($conn, $query, $params = []) {
        try {
            $stmt = $conn->prepare($query);
            if (!$stmt) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            
            if (!empty($params)) {
                $types = str_repeat('s', count($params));
                $stmt->bind_param($types, ...$params);
            }
            
            $stmt->execute();
            $result = $stmt->get_result();
            $data = $result->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            
            return $data;
        } catch (Exception $e) {
            error_log("Query error: " . $e->getMessage());
            return [];
        }
    }
}

// Handle form submission
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_customization') {
    $license_id = $_POST['license_id'] ?? '';
    $company_name = $_POST['company_name'] ?? '';
    $logo_url = $_POST['logo_url'] ?? '';
    $primary_color = $_POST['primary_color'] ?? '#3b82f6';
    $secondary_color = $_POST['secondary_color'] ?? '#6b7280';
    $payment_description = $_POST['payment_description'] ?? '';
    
    // Validate license belongs to user
    $license_check = safeQuery($conn, "
        SELECT license_id FROM licenses 
        WHERE license_id = ? AND user_id = ? AND status = 'active'
    ", [$license_id, $user_id]);
    
    if (empty($license_check)) {
        $error_message = "Invalid license or access denied.";
    } else {
        // Save customization settings
        $customization_data = json_encode([
            'company_name' => $company_name,
            'logo_url' => $logo_url,
            'primary_color' => $primary_color,
            'secondary_color' => $secondary_color,
            'payment_description' => $payment_description
        ]);
        
        $save_result = safeQuery($conn, "
            INSERT INTO license_customizations (license_id, customization_data, updated_at)
            VALUES (?, ?, NOW())
            ON DUPLICATE KEY UPDATE 
                customization_data = VALUES(customization_data),
                updated_at = NOW()
        ", [$license_id, $customization_data]);
        
        if ($save_result !== false) {
            $success_message = "Customization settings saved successfully!";
        } else {
            $error_message = "Failed to save customization settings.";
        }
    }
}

// Get customer's active licenses
$licenses = safeQuery($conn, "
    SELECT 
        l.license_id,
        l.license_key,
        l.status,
        l.expires_at,
        p.name as product_name,
        p.product_id,
        pp.tier_name as plan_name
    FROM licenses l
    JOIN products p ON l.product_id = p.product_id
    LEFT JOIN product_pricing pp ON l.pricing_id = pp.pricing_id
    WHERE l.user_id = ? AND l.status = 'active'
    ORDER BY l.created_at DESC
", [$user_id]);

// Get existing customizations
$customizations = [];
if (!empty($licenses)) {
    $license_ids = array_column($licenses, 'license_id');
    $placeholders = str_repeat('?,', count($license_ids) - 1) . '?';
    
    $custom_data = safeQuery($conn, "
        SELECT license_id, customization_data 
        FROM license_customizations 
        WHERE license_id IN ($placeholders)
    ", $license_ids);
    
    foreach ($custom_data as $custom) {
        $customizations[$custom['license_id']] = json_decode($custom['customization_data'], true) ?? [];
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php 
    $title = "Plugin Customization Settings";
    if (file_exists('partials/title-meta.php')) {
        try {
            include_once 'partials/title-meta.php';
        } catch (Exception $e) {
            echo "<title>$title - ConnectPay</title>\n";
        }
    } else {
        echo "<title>$title - ConnectPay</title>\n";
    }
    ?>
    
    <?php 
    if (file_exists('partials/head-css.php')) {
        try {
            include_once 'partials/head-css.php';
        } catch (Exception $e) {
            echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">' . "\n";
        }
    } else {
        echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">' . "\n";
    }
    ?>
    
    <style>
        body {
            background-color: #f8f9fa;
        }
        
        .customization-card {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            background: white;
            transition: box-shadow 0.2s ease;
        }
        
        .customization-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .preview-section {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            padding: 1.5rem;
        }
        
        .color-input {
            width: 80px;
            height: 40px;
            border: 2px solid #e2e8f0;
            border-radius: 6px;
            cursor: pointer;
        }
        
        .form-control {
            border: 1px solid #d1d5db;
            border-radius: 6px;
            padding: 0.75rem;
            transition: border-color 0.2s ease;
        }
        
        .form-control:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            outline: none;
        }
        
        .btn-primary {
            background-color: #3b82f6;
            border-color: #3b82f6;
            border-radius: 6px;
            padding: 0.75rem 1.5rem;
            font-weight: 500;
        }
        
        .btn-primary:hover {
            background-color: #2563eb;
            border-color: #2563eb;
        }
        
        .btn-outline-secondary {
            border: 1px solid #d1d5db;
            color: #6b7280;
            border-radius: 6px;
            padding: 0.75rem 1.5rem;
        }
        
        .alert {
            border-radius: 6px;
            border: none;
            padding: 1rem 1.25rem;
        }
        
        .alert-success {
            background-color: #dcfce7;
            color: #166534;
            border-left: 4px solid #16a34a;
        }
        
        .alert-danger {
            background-color: #fef2f2;
            color: #dc2626;
            border-left: 4px solid #ef4444;
        }
        
        .page-title-box {
            background: white;
            border-radius: 8px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid #e2e8f0;
        }
    </style>
</head>

<body>

<div id="wrapper">
    <?php 
    $pagetitle = "Plugin Customization Settings"; 
    if (file_exists('partials/menu.php')) {
        try {
            include_once 'partials/menu.php';
        } catch (Exception $e) {
            echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                    <div class="container">
                        <a class="navbar-brand" href="customer-dashboard.php">ConnectPay</a>
                        <span class="navbar-text">Welcome, ' . htmlspecialchars($user_name) . '</span>
                    </div>
                  </nav>';
        }
    }
    ?>

    <div class="content-page">
        <div class="content">
            <div class="container-fluid">
                
                <!-- Page Title -->
                <div class="row">
                    <div class="col-12">
                        <div class="page-title-box">
                            <div class="page-title-right">
                                <ol class="breadcrumb m-0">
                                    <li class="breadcrumb-item"><a href="customer-dashboard.php">Dashboard</a></li>
                                    <li class="breadcrumb-item"><a href="my-licenses.php">Licenses</a></li>
                                    <li class="breadcrumb-item active">Customization Settings</li>
                                </ol>
                            </div>
                            <h4 class="page-title">
                                <i class="fas fa-palette me-2"></i>
                                Plugin Customization Settings
                            </h4>
                        </div>
                    </div>
                </div>
                
                <!-- Alert Messages -->
                <?php if (!empty($success_message)): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle me-2"></i>
                    <?php echo htmlspecialchars($success_message); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($error_message)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-circle me-2"></i>
                    <?php echo htmlspecialchars($error_message); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>
                
                <?php if (empty($licenses)): ?>
                <!-- No Active Licenses -->
                <div class="row">
                    <div class="col-12">
                        <div class="text-center py-5">
                            <div class="mb-4">
                                <i class="fas fa-key fa-4x text-muted"></i>
                            </div>
                            <h5 class="text-muted">No Active Licenses Found</h5>
                            <p class="text-muted mb-4">You need an active license to customize your plugin settings.</p>
                            <a href="browse-plugins.php" class="btn btn-primary">
                                <i class="fas fa-shopping-cart me-2"></i>
                                Browse Plugins
                            </a>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                
                <!-- Customization Forms -->
                <div class="row">
                    <?php foreach ($licenses as $license): ?>
                    <div class="col-lg-6 mb-4">
                        <div class="customization-card h-100">
                            <div class="card-header border-bottom bg-light">
                                <h5 class="card-title mb-0">
                                    <i class="fas fa-puzzle-piece me-2"></i>
                                    <?php echo htmlspecialchars($license['product_name']); ?>
                                </h5>
                                <small class="text-muted">License: <?php echo htmlspecialchars($license['license_key']); ?></small>
                            </div>
                            
                            <div class="card-body p-4">
                                <form method="POST" action="">
                                    <input type="hidden" name="action" value="save_customization">
                                    <input type="hidden" name="license_id" value="<?php echo htmlspecialchars($license['license_id']); ?>">
                                    
                                    <!-- Company Branding -->
                                    <div class="mb-4">
                                        <h6 class="fw-bold mb-3">
                                            <i class="fas fa-building me-2"></i>
                                            Company Branding
                                        </h6>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Company Name</label>
                                            <input type="text" 
                                                   class="form-control" 
                                                   name="company_name" 
                                                   value="<?php echo htmlspecialchars($customizations[$license['license_id']]['company_name'] ?? ''); ?>"
                                                   placeholder="Your Company Name">
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Logo URL</label>
                                            <input type="url" 
                                                   class="form-control" 
                                                   name="logo_url" 
                                                   value="<?php echo htmlspecialchars($customizations[$license['license_id']]['logo_url'] ?? ''); ?>"
                                                   placeholder="https://example.com/logo.png">
                                            <small class="text-muted">Recommended size: 200x60px</small>
                                        </div>
                                    </div>
                                    
                                    <!-- Color Scheme -->
                                    <div class="mb-4">
                                        <h6 class="fw-bold mb-3">
                                            <i class="fas fa-palette me-2"></i>
                                            Color Scheme
                                        </h6>
                                        
                                        <div class="row">
                                            <div class="col-6">
                                                <label class="form-label">Primary Color</label>
                                                <div class="d-flex align-items-center gap-2">
                                                    <input type="color" 
                                                           class="color-input" 
                                                           name="primary_color" 
                                                           value="<?php echo $customizations[$license['license_id']]['primary_color'] ?? '#3b82f6'; ?>"
                                                           onchange="updatePreview(this)">
                                                    <input type="text" 
                                                           class="form-control" 
                                                           value="<?php echo $customizations[$license['license_id']]['primary_color'] ?? '#3b82f6'; ?>"
                                                           readonly>
                                                </div>
                                            </div>
                                            <div class="col-6">
                                                <label class="form-label">Secondary Color</label>
                                                <div class="d-flex align-items-center gap-2">
                                                    <input type="color" 
                                                           class="color-input" 
                                                           name="secondary_color" 
                                                           value="<?php echo $customizations[$license['license_id']]['secondary_color'] ?? '#6b7280'; ?>"
                                                           onchange="updatePreview(this)">
                                                    <input type="text" 
                                                           class="form-control" 
                                                           value="<?php echo $customizations[$license['license_id']]['secondary_color'] ?? '#6b7280'; ?>"
                                                           readonly>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Payment Description -->
                                    <div class="mb-4">
                                        <h6 class="fw-bold mb-3">
                                            <i class="fas fa-comment-alt me-2"></i>
                                            Payment Description
                                        </h6>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Custom Payment Description</label>
                                            <textarea class="form-control" 
                                                      name="payment_description" 
                                                      rows="3" 
                                                      placeholder="Custom message displayed during checkout"><?php echo htmlspecialchars($customizations[$license['license_id']]['payment_description'] ?? ''); ?></textarea>
                                            <small class="text-muted">This will appear on your payment forms</small>
                                        </div>
                                    </div>
                                    
                                    <!-- Preview Section -->
                                    <div class="preview-section mb-4">
                                        <h6 class="fw-bold mb-3">
                                            <i class="fas fa-eye me-2"></i>
                                            Preview
                                        </h6>
                                        <div class="text-center">
                                            <div class="d-inline-block p-3 border rounded preview-box" 
                                                 style="background-color: <?php echo $customizations[$license['license_id']]['primary_color'] ?? '#3b82f6'; ?>; color: white;">
                                                <strong class="company-preview"><?php echo htmlspecialchars($customizations[$license['license_id']]['company_name'] ?? 'Your Company'); ?></strong>
                                                <br>
                                                <small>Mobile Money Payment</small>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Action Buttons -->
                                    <div class="d-flex gap-2">
                                        <button type="submit" class="btn btn-primary flex-fill">
                                            <i class="fas fa-save me-2"></i>
                                            Save Settings
                                        </button>
                                        <a href="download-plugins.php?license=<?php echo $license['license_id']; ?>" 
                                           class="btn btn-outline-secondary">
                                            <i class="fas fa-download me-2"></i>
                                            Download
                                        </a>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                
                <!-- Customization Tips -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header border-bottom bg-light">
                                <h5 class="card-title mb-0">
                                    <i class="fas fa-lightbulb me-2"></i>
                                    Customization Tips
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <ul class="list-unstyled">
                                            <li class="mb-2">
                                                <i class="fas fa-check-circle text-success me-2"></i>
                                                Use high-contrast colors for better readability
                                            </li>
                                            <li class="mb-2">
                                                <i class="fas fa-check-circle text-success me-2"></i>
                                                Keep your logo dimensions under 200x60px
                                            </li>
                                            <li class="mb-2">
                                                <i class="fas fa-check-circle text-success me-2"></i>
                                                Test your colors on both light and dark backgrounds
                                            </li>
                                        </ul>
                                    </div>
                                    <div class="col-md-6">
                                        <ul class="list-unstyled">
                                            <li class="mb-2">
                                                <i class="fas fa-check-circle text-success me-2"></i>
                                                Use your brand colors consistently
                                            </li>
                                            <li class="mb-2">
                                                <i class="fas fa-check-circle text-success me-2"></i>
                                                Keep payment descriptions clear and concise
                                            </li>
                                            <li class="mb-2">
                                                <i class="fas fa-check-circle text-success me-2"></i>
                                                Download updated plugin after making changes
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <?php endif; ?>
                
            </div>
        </div>
    </div>
</div>

<?php 
if (file_exists('partials/footer.php')) {
    try {
        include_once 'partials/footer.php';
    } catch (Exception $e) {
        echo '<footer class="bg-light text-center py-3 mt-5"><p>&copy; 2024 ConnectPay Platform</p></footer>';
    }
}
?>

<?php 
if (file_exists('partials/footer-scripts.php')) {
    try {
        include_once 'partials/footer-scripts.php';
    } catch (Exception $e) {
        echo '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>' . "\n";
    }
}
?>

<script>
function updatePreview(colorInput) {
    const form = colorInput.closest('form');
    const primaryColor = form.querySelector('input[name="primary_color"]').value;
    const companyName = form.querySelector('input[name="company_name"]').value || 'Your Company';
    const previewBox = form.querySelector('.preview-box');
    const companyPreview = form.querySelector('.company-preview');
    
    if (previewBox) {
        previewBox.style.backgroundColor = primaryColor;
    }
    
    if (companyPreview) {
        companyPreview.textContent = companyName;
    }
    
    // Update text input
    const textInput = colorInput.parentNode.querySelector('input[type="text"]');
    if (textInput) {
        textInput.value = colorInput.value;
    }
}

document.addEventListener('DOMContentLoaded', function() {
    // Real-time preview updates
    const companyInputs = document.querySelectorAll('input[name="company_name"]');
    companyInputs.forEach(input => {
        input.addEventListener('input', function() {
            const form = this.closest('form');
            const companyPreview = form.querySelector('.company-preview');
            if (companyPreview) {
                companyPreview.textContent = this.value || 'Your Company';
            }
        });
    });
});
</script>

</body>
</html>