<?php
require_once __DIR__ . '/../includes/auth_check.php'; // Ensures user is logged in
require_once __DIR__ . '/../config/db_connect.php';   // Database connection
require_once __DIR__ . '/../includes/header.php';     // HTML header

$user_id = $_SESSION['user_id'];
$user_email = $_SESSION['email'] ?? 'User';

$errors = [];
$success_message = '';

// Check for checkout errors
if (isset($_SESSION['checkout_errors'])) {
    $errors = array_merge($errors, $_SESSION['checkout_errors']);
    unset($_SESSION['checkout_errors']);
    error_log("Dashboard: Found checkout errors: " . print_r($_SESSION['checkout_errors'] ?? [], true));
}

// Fetch user's single website configuration (they manage only one active widget/domain)
$user_website = null;
$stmt_get_website = $mysqli->prepare("SELECT id, domain_name, widget_id, plan_type, subscription_status, created_at FROM websites WHERE user_id = ? LIMIT 1");
if ($stmt_get_website) {
    $stmt_get_website->bind_param("i", $user_id);
    $stmt_get_website->execute();
    $result = $stmt_get_website->get_result();
    if ($result->num_rows > 0) {
        $user_website = $result->fetch_assoc();
    }
    $stmt_get_website->close();
} else {
    // This error might be too strong if displayed directly, consider logging for admin
    $errors[] = "Error fetching your website configuration. Please contact support if this persists.";
    error_log("Dashboard: User ID ".$user_id." - Error fetching website config: " . $mysqli->error); // Example server-side logging
}

// Handle "Add New Website" form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_website'])) {
    if ($user_website) {
        // This should ideally not happen if the form is only shown when $user_website is null
        $errors[] = "You already have a website configured. Please use the 'Change Domain' option.";
    } else {
        $domain_name = trim(filter_input(INPUT_POST, 'domain_name', FILTER_SANITIZE_URL));
        // Remove http(s):// prefix if present for consistency, as we're storing just the domain.
        $domain_name = preg_replace('#^https?://#', '', $domain_name);

        // Basic validation for domain name
        if (empty($domain_name)) {
            $errors[] = "Domain name cannot be empty.";
        } elseif (strlen($domain_name) > 255 || !preg_match('/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$/i', $domain_name)) {
            // A more forgiving regex might be needed depending on what types of domains (e.g. IDNs) are allowed.
            // This regex checks for basic structure like something.com, sub.example.co.uk
            $errors[] = "Invalid domain name format. Please enter a valid domain (e.g., example.com).";
        }

        if (empty($errors)) {
            $widget_id = bin2hex(random_bytes(16)); // Generate a unique widget ID

            $stmt_insert_website = $mysqli->prepare("INSERT INTO websites (user_id, domain_name, widget_id, subscription_status, plan_type) VALUES (?, ?, ?, 'pending_payment', NULL)");
            if ($stmt_insert_website) {
                $stmt_insert_website->bind_param("iss", $user_id, $domain_name, $widget_id);
                if ($stmt_insert_website->execute()) {
                    $success_message = "Website '" . htmlspecialchars($domain_name) . "' added successfully! Your widget ID is " . htmlspecialchars($widget_id) . ".";
                    // Refresh $user_website to reflect the new addition
                    $new_website_id = $stmt_insert_website->insert_id;
                    $user_website = [
                        'id' => $new_website_id,
                        'user_id' => $user_id,
                        'domain_name' => $domain_name,
                        'widget_id' => $widget_id,
                        'subscription_status' => 'pending_payment',
                        'plan_type' => null,
                        // 'created_at' could be fetched or set to now if needed immediately
                    ];
                } else {
                    $errors[] = "Failed to add website. Please try again. If the problem persists, the domain might be too long or an unexpected error occurred.";
                    error_log("Dashboard: User ID ".$user_id." - Error inserting website: " . $stmt_insert_website->error);
                }
                $stmt_insert_website->close();
            } else {
                $errors[] = "An unexpected error occurred. Please try again. (Error code: DBPREP_ADD)";
                error_log("Dashboard: User ID ".$user_id." - Error preparing insert website statement: " . $mysqli->error);
            }
        }
    }
}
// Handle "Change Domain" form submission
elseif ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['change_domain'])) {
    if (!$user_website) {
        // This should ideally not happen if the form is only shown when $user_website exists
        $errors[] = "No website configured to change. Please add a website first.";
    } else {
        $new_domain_name = trim(filter_input(INPUT_POST, 'new_domain_name', FILTER_SANITIZE_URL));
        // Remove http(s):// prefix
        $new_domain_name = preg_replace('#^https?://#', '', $new_domain_name);
        $website_id_to_update = filter_input(INPUT_POST, 'website_id', FILTER_VALIDATE_INT);

        // Validate new domain name
        if (empty($new_domain_name)) {
            $errors[] = "New domain name cannot be empty.";
        } elseif (strlen($new_domain_name) > 255 || !preg_match('/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$/i', $new_domain_name)) {
            $errors[] = "Invalid new domain name format.";
        }

        // Validate website_id from hidden input matches the one fetched for the user
        if (!$website_id_to_update || $website_id_to_update != $user_website['id']) {
             $errors[] = "An error occurred processing your request. Please try again. (Error code: WID_MISMATCH)";
             error_log("Dashboard: User ID ".$user_id." - Website ID mismatch. Expected: ".$user_website['id']." Got: ".$website_id_to_update);
        }

        if (empty($errors)) {
            // Check if the domain name is actually different
            if ($new_domain_name === $user_website['domain_name']) {
                $success_message = "Domain name is already set to '" . htmlspecialchars($new_domain_name) . "'. No changes made.";
            } else {
                $stmt_update_domain = $mysqli->prepare("UPDATE websites SET domain_name = ? WHERE id = ? AND user_id = ?");
                if ($stmt_update_domain) {
                    $stmt_update_domain->bind_param("sii", $new_domain_name, $user_website['id'], $user_id);
                    if ($stmt_update_domain->execute()) {
                        if ($stmt_update_domain->affected_rows > 0) {
                            $success_message = "Domain name updated successfully to '" . htmlspecialchars($new_domain_name) . "'.";
                            // Refresh $user_website to reflect the change
                            $user_website['domain_name'] = $new_domain_name;
                        } else {
                             // This case should ideally be caught by the ($new_domain_name === $user_website['domain_name']) check
                             $errors[] = "No effective changes were made to the domain name.";
                        }
                    } else {
                        $errors[] = "Failed to update domain name. Please try again.";
                        error_log("Dashboard: User ID ".$user_id." - Error updating domain: " . $stmt_update_domain->error);
                    }
                    $stmt_update_domain->close();
                } else {
                    $errors[] = "An unexpected error occurred. Please try again. (Error code: DBPREP_UPD)";
                    error_log("Dashboard: User ID ".$user_id." - Error preparing update domain statement: " . $mysqli->error);
                }
            }
        }
    }
}

$mysqli->close(); // All database operations for this page are now complete.
?>

<div class="dashboard-container">
    <h2>Welcome, <?php echo htmlspecialchars($user_email); ?>!</h2>

    <?php if (!empty($success_message)): ?>
        <div class="success-message"><?php echo $success_message; ?></div>
    <?php endif; ?>
    <?php if (!empty($errors)): ?>
        <div class="errors">
            <?php foreach ($errors as $error): ?>
                <p><?php echo htmlspecialchars($error); ?></p>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <?php if ($user_website): ?>
        <div class="manage-website-section">
            <h3>Your Active Widget Configuration</h3>
            <p>Your widget (ID: <strong><?php echo htmlspecialchars($user_website['widget_id']); ?></strong>) is currently configured for the following domain:</p>
            <p class="configured-domain"><strong><?php echo htmlspecialchars($user_website['domain_name']); ?></strong></p>

            <p><strong>Status:</strong> <?php echo htmlspecialchars(ucfirst(str_replace('_', ' ', $user_website['subscription_status']))); ?></p>
            <p><strong>Plan:</strong> <?php echo htmlspecialchars($user_website['plan_type'] ? ucfirst($user_website['plan_type']) : 'N/A'); ?></p>

            <?php if ($user_website['subscription_status'] === 'active'): ?>
                <p>Your widget is active and ready to use!</p>
                <p><strong>Your Widget Script Tag:</strong></p>
                <textarea readonly rows="3" cols="70" class="widget-script-display" onclick="this.select();"><?php echo htmlspecialchars('<script src="https://widget.adawizard.com/ada-wizard-widget.js?id=' . $user_website['widget_id'] . '" async defer></script>'); ?></textarea>
                <small>Click the text above to select it, then copy (Ctrl+C or Cmd+C).</small>

                <div class="installation-instructions">
                    <h4>Installation Instructions:</h4>
                    <ol>
                        <li>Copy the script tag shown above.</li>
                        <li>Paste this script tag into your website's HTML code. For best results, place it just before the closing <code>&lt;/body&gt;</code> tag.</li>
                        <li>Ensure the script is added to all pages where you want the ADA Wizard widget to function.</li>
                        <li>After adding the script, the widget will activate based on your current plan status and the domain configured for this widget (<strong><?php echo htmlspecialchars($user_website['domain_name']); ?></strong>).</li>
                    </ol>
                    <p><strong>Note:</strong> If you are using a Content Management System (CMS) like WordPress, Joomla, Shopify, etc., you can often add custom scripts like this via your theme's settings, a custom HTML module, or a specialized plugin for adding scripts to your site's header or footer.</p>
                </div>

                <hr style="margin-top: 25px;">
                <h4>Change Domain</h4>
                <p>If you want this widget to work on a different domain, enter the new domain below.</p>
            <?php elseif ($user_website['subscription_status'] === 'pending_payment' || $user_website['subscription_status'] === 'inactive'  || $user_website['subscription_status'] === 'cancelled'): ?>
                <div class="payment-plans-section">
                    <h4>Activate Your Widget by Choosing a Plan</h4>
                    <p>Your widget for <strong><?php echo htmlspecialchars($user_website['domain_name']); ?></strong> (ID: <?php echo htmlspecialchars($user_website['widget_id']); ?>) is not yet active. Please choose a plan:</p>

                    <div class="plan-options">
                        <div class="plan">
                            <h5>Monthly Plan</h5>
                            <p class="plan-price">$19.99 / month</p>
                            <p class="plan-description">Perfect for getting started with ADA compliance</p>
                            <form action="create_checkout_session.php" method="POST">
                                <input type="hidden" name="plan_type" value="monthly">
                                <input type="hidden" name="website_id" value="<?php echo $user_website['id']; ?>">
                                <button type="submit" class="button plan-button monthly-plan">Choose Monthly Plan</button>
                            </form>
                            <small class="plan-note">Cancel anytime • No setup fees</small>
                        </div>
                        
                        <div class="plan featured-plan">
                            <div class="plan-badge">Most Popular</div>
                            <h5>Yearly Plan</h5>
                            <p class="plan-price">$199.00 / year</p>
                            <p class="plan-savings">Save $40 compared to monthly!</p>
                            <p class="plan-description">Best value for long-term protection</p>
                            <form action="create_checkout_session.php" method="POST">
                                <input type="hidden" name="plan_type" value="yearly">
                                <input type="hidden" name="website_id" value="<?php echo $user_website['id']; ?>">
                                <button type="submit" class="button plan-button yearly-plan">Choose Yearly Plan</button>
                            </form>
                            <small class="plan-note">Best value • 2 months free</small>
                        </div>
                        
                        <div class="plan">
                            <h5>Lifetime Plan</h5>
                            <p class="plan-price">$399.00</p>
                            <p class="plan-description">One-time payment • Never pay again</p>
                            <form action="create_checkout_session.php" method="POST">
                                <input type="hidden" name="plan_type" value="lifetime">
                                <input type="hidden" name="website_id" value="<?php echo $user_website['id']; ?>">
                                <button type="submit" class="button plan-button lifetime-plan">Choose Lifetime Plan</button>
                            </form>
                            <small class="plan-note">One-time payment • Best long-term value</small>
                        </div>
                    </div>
                </div>
                <hr>
                <h4>Change Domain (Before Activating)</h4>
                <p>If you want to activate this widget for a different domain, you can change it below before choosing a plan.</p>
            <?php endif; ?>


            <form action="dashboard.php" method="POST" class="change-domain-form">
                <div class="form-group">
                    <label for="new_domain_name">New Domain Name (e.g., new-example.com):</label>
                    <input type="text" id="new_domain_name" name="new_domain_name" value="<?php echo htmlspecialchars($user_website['domain_name']); ?>" required>
                    <input type="hidden" name="website_id" value="<?php echo $user_website['id']; ?>">
                </div>
                <button type="submit" name="change_domain" class="button">Update Domain</button>
            </form>
        </div>
    <?php else: ?>
        <div class="add-website-section">
            <h3>Configure Your Widget</h3>
            <p>You haven't configured your widget for a website yet. Add your domain name below to get started.</p>
            <form action="dashboard.php" method="POST" class="add-website-form">
                <div class="form-group">
                    <label for="domain_name">Domain Name (e.g., example.com):</label>
                    <input type="text" id="domain_name" name="domain_name" placeholder="example.com" required>
                </div>
                <button type="submit" name="add_website" class="button">Add Website & Get Widget</button>
            </form>
        </div>
    <?php endif; ?>

</div>

<style>
/* Plan Options Styling */
.plan-options {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 25px;
    margin: 30px 0;
}

.plan {
    background: white;
    border: 2px solid #e1e8ed;
    border-radius: 12px;
    padding: 25px;
    text-align: center;
    position: relative;
    transition: all 0.3s ease;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.plan:hover {
    border-color: #3498db;
    transform: translateY(-3px);
    box-shadow: 0 5px 20px rgba(52, 152, 219, 0.1);
}

.featured-plan {
    border-color: #27ae60;
    position: relative;
    transform: scale(1.05);
}

.featured-plan:hover {
    border-color: #229954;
    transform: scale(1.05) translateY(-3px);
}

.plan-badge {
    position: absolute;
    top: -12px;
    left: 50%;
    transform: translateX(-50%);
    background: #27ae60;
    color: white;
    padding: 6px 20px;
    border-radius: 20px;
    font-size: 0.9em;
    font-weight: 600;
}

.plan h5 {
    font-size: 1.4em;
    color: #2c3e50;
    margin-bottom: 15px;
    font-weight: 700;
}

.plan-price {
    font-size: 2em;
    font-weight: 700;
    color: #3498db;
    margin-bottom: 10px;
}

.plan-savings {
    color: #27ae60;
    font-weight: 600;
    font-size: 0.9em;
    margin-bottom: 10px;
}

.plan-description {
    color: #7f8c8d;
    margin-bottom: 20px;
    line-height: 1.4;
}

.plan-button {
    width: 100%;
    padding: 15px 20px;
    font-size: 1.1em;
    font-weight: 600;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    margin-bottom: 10px;
}

.monthly-plan {
    background: #3498db;
    color: white;
}

.monthly-plan:hover {
    background: #2980b9;
}

.yearly-plan {
    background: #27ae60;
    color: white;
}

.yearly-plan:hover {
    background: #229954;
}

.lifetime-plan {
    background: #8e44ad;
    color: white;
}

.lifetime-plan:hover {
    background: #7d3c98;
}

.plan-note {
    color: #95a5a6;
    font-size: 0.85em;
    font-style: italic;
}

/* Dashboard Container */
.dashboard-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    background: #f8f9fa;
    min-height: calc(100vh - 160px);
}

.dashboard-container h2 {
    color: #2c3e50;
    font-size: 2.2em;
    margin-bottom: 30px;
    text-align: center;
}

/* Success and Error Messages */
.success-message {
    background: #d4edda;
    border: 1px solid #c3e6cb;
    color: #155724;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 20px;
}

.errors {
    background: #f8d7da;
    border: 1px solid #f5c6cb;
    color: #721c24;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 20px;
}

/* Widget Management Section */
.manage-website-section {
    background: white;
    padding: 30px;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    margin-bottom: 20px;
}

.manage-website-section h3 {
    color: #2c3e50;
    font-size: 1.6em;
    margin-bottom: 20px;
    border-bottom: 2px solid #3498db;
    padding-bottom: 10px;
}

.configured-domain {
    background: #e8f5e8;
    padding: 15px;
    border-radius: 8px;
    border-left: 4px solid #27ae60;
    font-size: 1.2em;
    margin: 15px 0;
}

/* Widget Script Display */
.widget-script-display {
    width: 100%;
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 6px;
    padding: 15px;
    font-family: 'Courier New', monospace;
    font-size: 0.9em;
    resize: vertical;
    margin: 10px 0;
}

/* Installation Instructions */
.installation-instructions {
    background: #fff3cd;
    border: 1px solid #ffeaa7;
    border-radius: 8px;
    padding: 20px;
    margin: 20px 0;
}

.installation-instructions h4 {
    color: #856404;
    margin-bottom: 15px;
}

.installation-instructions ol {
    color: #856404;
    line-height: 1.6;
}

.installation-instructions code {
    background: #f8f9fa;
    padding: 2px 6px;
    border-radius: 3px;
    font-family: 'Courier New', monospace;
}

/* Forms */
.add-website-section,
.change-domain-form {
    background: white;
    padding: 25px;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    color: #2c3e50;
    font-weight: 600;
}

.form-group input[type="text"] {
    width: 100%;
    padding: 12px 15px;
    border: 2px solid #e1e8ed;
    border-radius: 8px;
    font-size: 1em;
    transition: border-color 0.3s ease;
}

.form-group input[type="text"]:focus {
    outline: none;
    border-color: #3498db;
}

.button {
    background: #3498db;
    color: white;
    padding: 12px 25px;
    border: none;
    border-radius: 8px;
    font-size: 1em;
    font-weight: 600;
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
    transition: all 0.3s ease;
}

.button:hover {
    background: #2980b9;
    transform: translateY(-2px);
}

/* Responsive Design */
@media (max-width: 768px) {
    .plan-options {
        grid-template-columns: 1fr;
    }
    
    .featured-plan {
        transform: none;
    }
    
    .featured-plan:hover {
        transform: translateY(-3px);
    }
    
    .dashboard-container {
        padding: 15px;
    }
    
    .manage-website-section,
    .add-website-section {
        padding: 20px;
    }
    
    .plan {
        padding: 20px;
    }
    
    .plan-price {
        font-size: 1.8em;
    }
}

@media (max-width: 480px) {
    .dashboard-container h2 {
        font-size: 1.8em;
    }
    
    .plan-price {
        font-size: 1.6em;
    }
    
    .widget-script-display {
        font-size: 0.8em;
    }
}
</style>

<?php
// $mysqli->close(); // Will be closed after form processing logic is fully integrated
require_once __DIR__ . '/../includes/footer.php'; // HTML footer
?>
