<?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__ . '/../config/stripe_init.php';  // Stripe PHP library and API key initialization

$user_id = $_SESSION['user_id'];
$stripe_checkout_session_id = $_GET['session_id'] ?? null;
$plan_from_url = $_GET['plan'] ?? null; // Get plan type from URL

$page_title = "Payment Successful";
$message = "";
$is_error = false;

error_log("=== PAYMENT SUCCESS DEBUG ===");
error_log("Session ID: " . ($stripe_checkout_session_id ?? 'NULL'));
error_log("Plan from URL: " . ($plan_from_url ?? 'NULL'));
error_log("User ID: " . $user_id);

if (!$stripe_checkout_session_id) {
    $message = "No payment session ID provided. Your payment may not have been processed correctly.";
    $is_error = true;
} else {
    try {
        $checkout_session = \Stripe\Checkout\Session::retrieve($stripe_checkout_session_id);
        error_log("Retrieved Stripe session: " . json_encode($checkout_session->toArray(), JSON_PRETTY_PRINT));

        // Validate the session
        if ($checkout_session && $checkout_session->payment_status === 'paid') {
            $website_id_from_stripe = $checkout_session->client_reference_id; // Our internal website ID
            $stripe_customer_id = $checkout_session->customer;
            $stripe_payment_intent_id = $checkout_session->payment_intent;
            $stripe_subscription_id = $checkout_session->subscription ?? null; // For recurring plans
            
            // Get plan type from Stripe metadata (most reliable)
            $plan_type_paid = $checkout_session->metadata->plan_type ?? $plan_from_url ?? 'lifetime';
            
            error_log("Plan type from Stripe metadata: " . $plan_type_paid);
            error_log("Website ID from Stripe: " . $website_id_from_stripe);
            error_log("Stripe Customer ID: " . ($stripe_customer_id ?? 'NULL'));
            error_log("Stripe Subscription ID: " . ($stripe_subscription_id ?? 'NULL'));

            // Fetch the website record to ensure it belongs to the current user and update it
            $stmt_get_website = $mysqli->prepare("SELECT id, user_id, subscription_status FROM websites WHERE id = ? AND user_id = ?");
            if (!$stmt_get_website) {
                throw new Exception("Database error preparing to fetch website. (DBPREP_SUCC_GET)");
            }
            $stmt_get_website->bind_param("ii", $website_id_from_stripe, $user_id);
            $stmt_get_website->execute();
            $result = $stmt_get_website->get_result();

            if ($website_record = $result->fetch_assoc()) {
                if ($website_record['subscription_status'] === 'active') {
                    $message = "Your payment was successful, and your " . ucfirst($plan_type_paid) . " plan is already active.";
                } else {
                    // Determine subscription end date based on plan type
                    $subscription_end_date = null;
                    if ($plan_type_paid === 'monthly') {
                        $subscription_end_date = date('Y-m-d H:i:s', strtotime('+1 month'));
                    } elseif ($plan_type_paid === 'yearly') {
                        $subscription_end_date = date('Y-m-d H:i:s', strtotime('+1 year'));
                    }
                    // For lifetime, subscription_end_date remains NULL

                    // Check if we need to update columns that might not exist
                    $columns_exist = true;
                    $check_columns_query = "SHOW COLUMNS FROM websites LIKE 'stripe_subscription_id'";
                    $result_check = $mysqli->query($check_columns_query);
                    if ($result_check->num_rows === 0) {
                        error_log("stripe_subscription_id column does not exist, using basic update");
                        $columns_exist = false;
                    }

                    if ($columns_exist) {
                        // Full update with all Stripe columns
                        $stmt_update_website = $mysqli->prepare(
                            "UPDATE websites SET
                                plan_type = ?,
                                subscription_status = 'active',
                                stripe_customer_id = ?,
                                stripe_payment_intent_id = ?,
                                stripe_subscription_id = ?,
                                subscription_start_date = NOW(),
                                subscription_end_date = ?
                            WHERE id = ? AND user_id = ?"
                        );

                        if (!$stmt_update_website) {
                            throw new Exception("Database error preparing to update website. (DBPREP_SUCC_UPD)");
                        }

                        $stmt_update_website->bind_param(
                            "sssssii",
                            $plan_type_paid,
                            $stripe_customer_id,
                            $stripe_payment_intent_id,
                            $stripe_subscription_id,
                            $subscription_end_date,
                            $website_id_from_stripe,
                            $user_id
                        );
                    } else {
                        // Basic update for minimal schema
                        $stmt_update_website = $mysqli->prepare(
                            "UPDATE websites SET
                                plan_type = ?,
                                subscription_status = 'active',
                                subscription_start_date = NOW(),
                                subscription_end_date = ?
                            WHERE id = ? AND user_id = ?"
                        );

                        if (!$stmt_update_website) {
                            throw new Exception("Database error preparing to update website. (DBPREP_SUCC_UPD_BASIC)");
                        }

                        $stmt_update_website->bind_param(
                            "ssii",
                            $plan_type_paid,
                            $subscription_end_date,
                            $website_id_from_stripe,
                            $user_id
                        );
                    }

                    if ($stmt_update_website->execute()) {
                        if ($stmt_update_website->affected_rows > 0) {
                            // Generate success message based on plan type
                            switch($plan_type_paid) {
                                case 'monthly':
                                    $message = "Thank you! Your payment was successful, and your Monthly plan ($19.99/month) is now active.";
                                    break;
                                case 'yearly':
                                    $message = "Thank you! Your payment was successful, and your Yearly plan ($199.00/year) is now active.";
                                    break;
                                case 'lifetime':
                                    $message = "Thank you! Your payment was successful, and your Lifetime plan ($399.00 one-time) is now active.";
                                    break;
                                default:
                                    $message = "Thank you! Your payment was successful, and your " . ucfirst($plan_type_paid) . " plan is now active.";
                            }
                            
                            error_log("Successfully updated website {$website_id_from_stripe} with plan type: {$plan_type_paid}");
                            // Optionally, send a confirmation email here
                        } else {
                            // This might happen if the record was already updated in a rapid webhook call
                            // or if there's a logic mismatch.
                            $message = "Payment successful, but there was an issue finalizing activation. Please contact support if your plan is not active shortly.";
                            error_log("PaymentSuccess: UserID {$user_id}, WebsiteID {$website_id_from_stripe} - No rows affected on DB update after successful payment.");
                            $is_error = true;
                        }
                    } else {
                        throw new Exception("Failed to update website record after payment. (DBEXEC_SUCC_UPD)");
                    }
                    $stmt_update_website->close();
                }
            } else {
                // Security: client_reference_id didn't match a website for this user
                $message = "Payment session validation failed. Could not link payment to your account. Please contact support.";
                error_log("PaymentSuccess: UserID {$user_id} - client_reference_id {$website_id_from_stripe} from Stripe session {$stripe_checkout_session_id} not found or not owned by user.");
                $is_error = true;
            }
            $stmt_get_website->close();

        } else {
            // Session not found or payment not successful
            $message = "Could not verify your payment session or payment was not completed. Please try again or contact support.";
            error_log("PaymentSuccess: UserID {$user_id} - Stripe session {$stripe_checkout_session_id} not found or payment_status not 'paid'. Status: " . ($checkout_session ? $checkout_session->payment_status : 'N/A'));
            $is_error = true;
        }

    } catch (\Stripe\Exception\ApiErrorException $e) {
        $message = "Error communicating with payment gateway: " . htmlspecialchars($e->getMessage());
        error_log("PaymentSuccess: UserID {$user_id} - Stripe API Error: " . $e->getMessage());
        $is_error = true;
    } catch (Exception $e) {
        $message = "An unexpected error occurred: " . htmlspecialchars($e->getMessage());
        // Log the full error for admin, including specific error codes from DB exceptions
        error_log("PaymentSuccess: UserID {$user_id} - Generic Error: " . $e->getMessage() . " - Trace: " . $e->getTraceAsString());
        $is_error = true;
    }
}

require_once __DIR__ . '/../includes/header.php';
?>

<div class="payment-status-container">
    <div class="success-container">
        <?php if ($is_error): ?>
            <div class="error-icon">
                <svg width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="12" cy="12" r="10"/>
                    <line x1="12" y1="8" x2="12" y2="12"/>
                    <line x1="12" y1="16" x2="12.01" y2="16"/>
                </svg>
            </div>
            <h2>Payment Processing Issue</h2>
            <div class="errors">
                <p><?php echo $message; ?></p>
            </div>
        <?php else: ?>
            <div class="success-icon">
                <svg width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M9 12l2 2 4-4"/>
                    <circle cx="12" cy="12" r="9"/>
                </svg>
            </div>
            <h2><?php echo $page_title; ?></h2>
            <div class="success-message">
                <p><?php echo $message; ?></p>
            </div>
        <?php endif; ?>

        <div class="success-actions">
            <a href="dashboard.php" class="button primary">Go to Dashboard</a>
        </div>
    </div>
</div>

<style>
.payment-status-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 40px 20px;
}

.success-container {
    text-align: center;
    background: white;
    padding: 60px 40px;
    border-radius: 15px;
    box-shadow: 0 5px 20px rgba(0,0,0,0.1);
}

.success-icon {
    margin-bottom: 30px;
}

.success-icon svg {
    color: #27ae60;
}

.error-icon {
    margin-bottom: 30px;
}

.error-icon svg {
    color: #e74c3c;
}

.success-container h2 {
    color: #2c3e50;
    margin-bottom: 20px;
    font-size: 2em;
}

.success-message,
.errors {
    margin-bottom: 30px;
}

.success-message p {
    color: #27ae60;
    font-size: 1.2em;
    font-weight: 600;
    line-height: 1.6;
}

.errors p {
    color: #e74c3c;
    font-size: 1.1em;
    line-height: 1.6;
}

.success-actions .button {
    padding: 15px 30px;
    font-size: 1.1em;
    background: #3498db;
    color: white;
    text-decoration: none;
    border-radius: 8px;
    display: inline-block;
    transition: background 0.3s ease;
    font-weight: 600;
}

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

@media (max-width: 768px) {
    .success-container {
        padding: 40px 20px;
    }
    
    .success-container h2 {
        font-size: 1.6em;
    }
    
    .success-message p,
    .errors p {
        font-size: 1em;
    }
}
</style>

<?php
if (isset($mysqli)) { // $mysqli might not be set if db_connect.php wasn't reached or failed early
    $mysqli->close();
}
require_once __DIR__ . '/../includes/footer.php';
?>
