/home/awneajlw/public_html/codestechvista.com/social-media-reg.php
<?php
/**
 * Social Media Registration Page
 * Final step of registration - saves social media details and completes user registration
 * Automatically logs in the user after successful completion
 */

// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Include required files
require_once 'config/database.php';  // Database connection configuration
require_once 'includes/auth.php';    // Authentication functions

$success_message = '';
$error_message = '';
$field_errors = [];
$form_data = [];

// Check if user_id exists in session
if (!isset($_SESSION['user_id'])) {
    // Debug: Check what's in session
    error_log("Social media page: No user_id in session. Session data: " . print_r($_SESSION, true));
    
    // Try to get the latest user from registration email
    if (isset($_SESSION['registration_email'])) {
        try {
            $database = new Database();
            $db = $database->getConnection();
            $email = $_SESSION['registration_email'];
            
            $user_query = "SELECT id FROM users WHERE email = ? ORDER BY id DESC LIMIT 1";
            $user_stmt = $db->prepare($user_query);
            $user_stmt->execute([$email]);
            $user = $user_stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user) {
                $_SESSION['user_id'] = $user['id'];
                error_log("Recovered user_id from email: " . $user['id']);
            } else {
                $error_message = 'Registration not found. Please start registration again.';
            }
        } catch (Exception $e) {
            error_log("Error recovering user_id: " . $e->getMessage());
            $error_message = 'Session expired. Please complete registration again.';
        }
    } else {
        // If no registration email, try to allow form display for manual completion
        error_log("No registration_email in session, allowing manual form completion");
    }
}

/**
 * Social Media Form Submission Handler
 * Process social media details and complete registration
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Try to get or recover user_id
    if (!isset($_SESSION['user_id']) && isset($_SESSION['registration_email'])) {
        // Last attempt to recover user_id
        try {
            $database = new Database();
            $db = $database->getConnection();
            $email = $_SESSION['registration_email'];
            
            $user_query = "SELECT id FROM users WHERE email = ? ORDER BY id DESC LIMIT 1";
            $user_stmt = $db->prepare($user_query);
            $user_stmt->execute([$email]);
            $user = $user_stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user) {
                $_SESSION['user_id'] = $user['id'];
                error_log("Final recovery: user_id set to " . $user['id']);
            }
        } catch (Exception $e) {
            error_log("Final recovery failed: " . $e->getMessage());
        }
    }
    
    if (isset($_SESSION['user_id'])) {
    try {
        // Store form data for repopulation on error
        $form_data = [
            'whatsapp_number' => $_POST['whatsapp_number'] ?? '',
            'facebook_id' => $_POST['facebook_id'] ?? '',
            'instagram_id' => $_POST['instagram_id'] ?? '',
            'website' => $_POST['website'] ?? ''
        ];
        
        $database = new Database();
        $db = $database->getConnection();
        
        $user_id = $_SESSION['user_id'];
        $whatsapp_number = sanitizeInput($form_data['whatsapp_number']);
        $facebook_id = sanitizeInput($form_data['facebook_id']);
        $instagram_id = sanitizeInput($form_data['instagram_id']);
        $website = sanitizeInput($form_data['website']);
        
        // Validate WhatsApp Number
        if (!empty($whatsapp_number) && !preg_match('/^[0-9+\-\s()]{10,20}$/', $whatsapp_number)) {
            $field_errors['whatsapp_number'] = 'Please enter a valid WhatsApp number (10-20 digits)';
        }
        
        // Validate Website URL
        if (!empty($website) && !filter_var($website, FILTER_VALIDATE_URL)) {
            $field_errors['website'] = 'Please enter a valid website URL (e.g., https://example.com)';
        }
        
        // If validation errors exist, don't proceed
        if (!empty($field_errors)) {
            $error_message = 'Please fix the errors below and try again.';
        } else {
        
            // Debug log
            error_log("Social media submission - User ID: $user_id, WhatsApp: $whatsapp_number");
        
            // Ensure shops table exists with all columns
            $create_shops_table = "CREATE TABLE IF NOT EXISTS shops (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            shop_name VARCHAR(255) NOT NULL,
            shop_phone VARCHAR(20),
            shop_logo VARCHAR(255),
            shop_whatsapp VARCHAR(20) DEFAULT NULL,
            shop_facebook VARCHAR(255) DEFAULT NULL,
            shop_instagram VARCHAR(255) DEFAULT NULL,
            shop_website VARCHAR(255) DEFAULT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
        )";
            $db->exec($create_shops_table);
        
            // Add social media columns to existing shops table if they don't exist
            $alter_queries = [
            "ALTER TABLE shops ADD COLUMN shop_whatsapp VARCHAR(20) DEFAULT NULL",
            "ALTER TABLE shops ADD COLUMN shop_facebook VARCHAR(255) DEFAULT NULL", 
            "ALTER TABLE shops ADD COLUMN shop_instagram VARCHAR(255) DEFAULT NULL",
            "ALTER TABLE shops ADD COLUMN shop_website VARCHAR(255) DEFAULT NULL"
        ];
        
            foreach ($alter_queries as $query) {
                try {
                    $db->exec($query);
                } catch (PDOException $e) {
                    // Column already exists, continue
                    error_log("Column might already exist: " . $e->getMessage());
                }
            }
        
            // First check if shop exists for this user
            $check_query = "SELECT id FROM shops WHERE user_id = ?";
            $check_stmt = $db->prepare($check_query);
            $check_stmt->execute([$user_id]);
        
            if ($check_stmt->rowCount() > 0) {
                // Update existing shop with social media details
                $update_query = "UPDATE shops SET 
                                shop_whatsapp = ?, 
                                shop_facebook = ?, 
                                shop_instagram = ?, 
                                shop_website = ? 
                                WHERE user_id = ?";
                $stmt = $db->prepare($update_query);
                $result = $stmt->execute([$whatsapp_number, $facebook_id, $instagram_id, $website, $user_id]);
            
                if ($result) {
                    // Retrieve user details for session
                    $user_query = "SELECT email, name FROM users WHERE id = ?";
                    $user_stmt = $db->prepare($user_query);
                    $user_stmt->execute([$user_id]);
                    $user_data = $user_stmt->fetch(PDO::FETCH_ASSOC);
                    
                    // Complete registration and automatically log in the user
                    $_SESSION['logged_in'] = true;
                    $_SESSION['user_email'] = $user_data['email'] ?? $_SESSION['registration_email'];
                    $_SESSION['user_name'] = $user_data['name'];
                    $_SESSION['registration_step'] = 'completed';
                    
                    // Set user as logged in permanently
                    $_SESSION['user_id'] = $user_id;
                    $_SESSION['logged_in'] = true;
                    $_SESSION['last_activity'] = time();
                    
                    // Clean up only registration session data (keep user logged in)
                    unset($_SESSION['registration_email']);
                    unset($_SESSION['registration_otp']);
                    
                    $success_message = 'Registration completed successfully! Redirecting to home...';
                    // JavaScript redirect after showing success message
                    echo "<script>
                        setTimeout(function() {
                            window.location.href = 'home.php';
                        }, 2000);
                    </script>";
                } else {
                    $error_message = 'Failed to save social media information. Please try again.';
                }
            } else {
                $error_message = 'Shop information not found. Please complete shop registration first.';
            }
        }
        
    } catch (PDOException $e) {
        error_log("Database error in social media registration: " . $e->getMessage());
        $error_message = 'Database error occurred. Please contact support if this persists. Error: ' . $e->getMessage();
    } catch (Exception $e) {
        error_log("General error in social media registration: " . $e->getMessage());
        $error_message = 'An unexpected error occurred. Please try again. Error: ' . $e->getMessage();
    }
    } else {
        $error_message = 'Session expired. Please complete registration from the beginning.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Social Media Registration - OPTI SLIP</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background: white;
            min-height: 100vh;
            padding: 20px;
            margin: 0;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .back-btn {
            background: none;
            border: none;
            color: black;
            font-size: 24px;
            cursor: pointer;
            margin-bottom: 30px;
            padding: 10px;
            transition: all 0.3s ease;
        }
        
        .back-btn:hover {
            color: #169D53;
            transform: translateX(-3px);
        }
        
        .logo-section {
            text-align: center;
            margin-bottom: 40px;
        }
        
        .logo-container {
            display: inline-block;
            margin-bottom: 20px;
        }
        
        .logo-image {
            width: 200px;
            height: 150px;
            object-fit: contain;
            filter: brightness(0) saturate(100%);
            margin-top:-50px;
        }
        
        .form-card {
            max-width: 900px;
            margin: 0 auto;
            padding: 40px;
        }
        
        .field-card {
            background: transparent;
            border: none;
            padding: 10px;
            margin-bottom: 5px;
            position: relative;
        }
        
        .form-group {
            margin-bottom: 10px;
        }
        
        .form-label {
            position: absolute;
            top: -10px;
            left: 20px;
            background: white;
            padding: 0 8px;
            font-size: 14px;
            color: black;
            font-weight: 700;
            z-index: 2;
        }
        
        .form-input {
            width: 100%;
            padding: 25px 20px;
            border: 2px solid black;
            border-radius: 25px;
            font-size: 16px;
            background: white;
            color: black;
            font-weight: 600;
            min-height: 60px;
            transition: all 0.3s ease;
        }
        
        .form-input:focus {
            outline: none;
            border-color: #169D53;
            box-shadow: 0 0 0 3px rgba(22, 157, 83, 0.1);
        }
        
        .form-input.error {
            border-color: #dc2626 !important;
            box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.1) !important;
        }
        
        .field-error {
            color: #dc2626;
            font-size: 12px;
            margin-top: 5px;
            margin-left: 20px;
            font-weight: 500;
        }
        
        .form-input::placeholder {
            color: #9ca3af;
            opacity: 0.7;
        }
        
        .form-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 40px;
            padding: 0 10px;
            gap: 20px;
            flex-wrap: wrap;
        }
        
        .nav-btn {
            font-size: 18px;
            padding: 12px 24px;
            border: 2px solid #10b981;
            border-radius: 8px;
            background: white;
            color: #10b981;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            min-width: 120px;
            white-space: nowrap;
        }
        
        .nav-btn:hover {
            background: #10b981;
            color: white;
            transform: translateY(-2px);
        }
        
        .pagination {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 12px;
            color: #6b7280;
            background: #f8fafc;
            padding: 6px 12px;
            border-radius: 20px;
            border: 1px solid #e5e7eb;
            flex-shrink: 0;
        }
        
        .pagination .page-number {
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
            font-size: 11px;
        }
        
        .pagination .page-number.active {
            background: #10b981;
            color: white;
            transform: scale(1.1);
            box-shadow: 0 2px 4px rgba(16, 185, 129, 0.3);
        }
        
        .pagination .page-number:hover:not(.active) {
            background: #e5e7eb;
            color: #374151;
        }
        
        @media (max-width: 1024px) {
            .container {
                padding: 15px;
            }
            
            .form-card {
                padding: 30px;
            }
            
            .logo-image {
                width: 150px;
                height: 150px;
            }
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }
            
            .form-card {
                padding: 20px;
            }
            
            .logo-image {
                width: 120px;
                height: 120px;
            }
            
            .form-input {
                padding: 20px 15px;
                min-height: 55px;
            }
            
            .field-card {
                margin-bottom: 8px;
            }
            
            .nav-btn {
                font-size: 16px;
                padding: 10px 20px;
                min-width: 100px;
            }
            
            .form-footer {
                flex-direction: row;
                justify-content: space-between;
            }
            
            .pagination {
                order: 1;
                flex: 1;
                justify-content: center;
            }
        }
        
        @media (max-width: 480px) {
            .container {
                padding: 5px;
            }
            
            .form-card {
                padding: 15px;
            }
            
            .logo-image {
                width: 100px;
                height: 100px;
            }
            
            .form-input {
                padding: 18px 12px;
                min-height: 50px;
                font-size: 14px;
            }
            
            .field-card {
                margin-bottom: 5px;
            }
            
            .nav-btn {
                font-size: 14px;
                padding: 8px 16px;
                min-width: 90px;
            }
            
            .form-footer {
                flex-direction: column;
                gap: 15px;
            }
            
            .pagination {
                order: -1;
                margin-bottom: 10px;
            }
        }
        
        @media (max-width: 320px) {
            .form-input {
                padding: 15px 10px;
                min-height: 45px;
                font-size: 13px;
            }
            
            .field-card {
                margin-bottom: 3px;
            }
            
            .nav-btn {
                font-size: 13px;
                padding: 6px 12px;
                min-width: 80px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <button class="back-btn" onclick="goBack()">
            <i class="fas fa-arrow-left"></i>
        </button>
        
        <div class="logo-section">
            <div class="logo-container">
                <img src="assets/images/Optislipimage.png" alt="Opti Slip Logo" class="logo-image" onerror="this.style.display='none'; this.parentElement.innerHTML='<div style=\'color: black; font-size: 32px; font-weight: bold; line-height: 1.2;\'>OPTI<br>SLIP</div>'">
            </div>
        </div>
        
        <div class="form-card">
            <!-- Form Content -->
            <div class="form-content">
                <?php if ($success_message): ?>
                    <div class="alert alert-success" style="background: #d1fae5; color: #065f46; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                        <i class="fas fa-check-circle me-2"></i>
                        <?php echo htmlspecialchars($success_message); ?>
                    </div>
                <?php endif; ?>
                
                <?php if ($error_message): ?>
                    <div class="alert alert-danger" style="background: #fee2e2; color: #991b1b; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <?php echo htmlspecialchars($error_message); ?>
                    </div>
                <?php endif; ?>
                
                <form method="POST" id="social-media-form">
                    <div class="field-card">
                        <div class="form-group">
                            <label class="form-label">WhatsApp Number</label>
                            <input type="tel" name="whatsapp_number" class="form-input<?php echo isset($field_errors['whatsapp_number']) ? ' error' : ''; ?>" placeholder="e.g., +92 300 1234567" value="<?php echo htmlspecialchars($form_data['whatsapp_number'] ?? ''); ?>">
                            <?php if (isset($field_errors['whatsapp_number'])): ?>
                                <div class="field-error"><?php echo htmlspecialchars($field_errors['whatsapp_number']); ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="field-card">
                        <div class="form-group">
                            <label class="form-label">Facebook ID</label>
                            <input type="text" name="facebook_id" class="form-input<?php echo isset($field_errors['facebook_id']) ? ' error' : ''; ?>" placeholder="e.g., john.doe or facebook.com/john.doe" value="<?php echo htmlspecialchars($form_data['facebook_id'] ?? ''); ?>">
                            <?php if (isset($field_errors['facebook_id'])): ?>
                                <div class="field-error"><?php echo htmlspecialchars($field_errors['facebook_id']); ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="field-card">
                        <div class="form-group">
                            <label class="form-label">Instagram ID</label>
                            <input type="text" name="instagram_id" class="form-input<?php echo isset($field_errors['instagram_id']) ? ' error' : ''; ?>" placeholder="e.g., @username or instagram.com/username" value="<?php echo htmlspecialchars($form_data['instagram_id'] ?? ''); ?>">
                            <?php if (isset($field_errors['instagram_id'])): ?>
                                <div class="field-error"><?php echo htmlspecialchars($field_errors['instagram_id']); ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="field-card">
                        <div class="form-group">
                            <label class="form-label">Website</label>
                            <input type="url" name="website" class="form-input<?php echo isset($field_errors['website']) ? ' error' : ''; ?>" placeholder="e.g., https://yourwebsite.com" value="<?php echo htmlspecialchars($form_data['website'] ?? ''); ?>">
                            <?php if (isset($field_errors['website'])): ?>
                                <div class="field-error"><?php echo htmlspecialchars($field_errors['website']); ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                </form>
            </div>
            
            <!-- Footer -->
            <div class="form-footer">
                <button class="nav-btn" onclick="goToPrevious()">PREVIOUS</button>
                
                <div class="pagination">
                    <span class="page-number">1</span>
                    <span class="page-number active">2</span>
                    <span class="page-number">3</span>
                    <span class="page-number">4</span>
                    <span class="page-number">5</span>
                    <span class="page-number">6</span>
                    <span>...</span>
                    <span class="page-number">10</span>
                </div>
                
                <button type="submit" form="social-media-form" class="nav-btn">
                    <i class="fas fa-save me-2"></i>SAVE
                </button>
            </div>
        </div>
    </div>
    
    <script>
        function goBack() {
            window.history.back();
        }
        
        function goToPrevious() {
            // Navigate to previous step
            window.location.href = 'shop-registration-form.php';
        }
        
        function goToNext() {
            // Submit form first, then redirect
            document.getElementById('social-media-form').submit();
        }
        
        
        // Form submission - Let PHP handle the submission
        // No preventDefault needed - form will submit normally to PHP
        
        // Auto-focus first input
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelector('input[name="whatsapp_number"]').focus();
            
            // Add Enter key functionality to inputs
            document.querySelectorAll('.form-input').forEach(input => {
                input.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        document.querySelector('form').submit();
                    }
                });
            });
        });
    </script>
</body>
</html>