<?php
session_start();
require_once('config/auth_config.php');
require_once('onesignal-api.php');

$error = '';
$success = '';

// Check if user is already logged in
if (isset($_SESSION['user'])) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        header('Content-Type: application/json');
        echo json_encode(['success' => true, 'redirect' => 'home.php']);
        exit();
    }
    header('Location: home.php');
    exit();
}

// Check if we have pending signin
if (!isset($_SESSION['pending_signin_email'])) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Please complete the signin process first', 'redirect' => 'signin.php']);
        exit();
    }
    header('Location: signin.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    try {
        $fullName = $_POST['full_name'] ?? '';
        $phoneNumber = $_POST['phone_number'] ?? '';
        
        if (empty($fullName)) {
            throw new Exception('Full name is required');
        }
        
        if (empty($phoneNumber)) {
            throw new Exception('Phone number is required');
        }
        
        // Create user account
        $conn = getDBConnection();
        $email = $conn->real_escape_string($_SESSION['pending_signin_email']);
        $fullName = $conn->real_escape_string($fullName);
        $phoneNumber = $conn->real_escape_string($phoneNumber);
        
        $sql = "INSERT INTO cmsb_members (email, full_name, phone_number) 
                VALUES ('$email', '$fullName', '$phoneNumber')";
        
        if (!$conn->query($sql)) {
            throw new Exception('Failed to create account: ' . $conn->error);
        }
        
        $userId = $conn->insert_id;
        
        // Set session
        $_SESSION['user'] = [
            'num' => $userId,
            'email' => $email,
            'username' => $email,
            'full_name' => $fullName,
            'phone_number' => $phoneNumber
        ];
        
        // Generate JWT token
        $jwt = generate_jwt($_SESSION['user']);

        // Save token in member_tokens table
        $token = $conn->real_escape_string($jwt);
        $expiryDate = date('Y-m-d H:i:s', time() + (60 * 60 * 24 * 7)); // 7 days expiry
        
        $insertSql = "INSERT INTO member_tokens 
            (token, membersNum, expiry_date, createdDate, updatedDate, user_type) 
            VALUES 
            ('$token', '$userId', '$expiryDate', NOW(), NOW(), 'user')";
        $conn->query($insertSql);
        
        // Clear pending signin
        unset($_SESSION['pending_signin_email']);
        
        // Return success response
        echo json_encode([
            'success' => true,
            'message' => 'Profile created successfully',
            'token' => $jwt,
            'redirect' => 'home.php'
        ]);
        exit();
        
    } catch (Exception $e) {
        error_log("Profile creation error: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        exit();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Complete Profile - Urban Halal</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        body {
            background-color: #f8f9fa;
        }
        .profile-container {
            max-width: 400px;
            margin: 50px auto;
            padding: 20px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .error-message {
            color: #dc3545;
            margin-bottom: 15px;
        }
        .success-message {
            color: #198754;
            margin-bottom: 15px;
        }
        .loading {
            display: none;
            margin-left: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="profile-container">
            <h2 class="text-center mb-4">Complete Your Profile</h2>
            
            <div id="error-message" class="error-message" style="display: none;"></div>
            <div id="success-message" class="success-message" style="display: none;"></div>
            
            <form id="profile-form" method="POST">
                <div class="mb-3">
                    <label for="full_name" class="form-label">Full Name</label>
                    <input type="text" class="form-control" id="full_name" name="full_name" required>
                </div>
                
                <div class="mb-3">
                    <label for="phone_number" class="form-label">Phone Number</label>
                    <input type="tel" class="form-control" id="phone_number" name="phone_number" required>
                </div>
                
                <button type="submit" class="btn btn-primary w-100">
                    Complete Profile
                    <span class="loading spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                </button>
            </form>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#profile-form').on('submit', function(e) {
                e.preventDefault();
                
                // Reset messages
                $('#error-message').hide();
                $('#success-message').hide();
                
                // Show loading
                $('.loading').show();
                $('button[type="submit"]').prop('disabled', true);
                
                // Get form data
                var formData = $(this).serialize();
                
                // Send AJAX request
                $.ajax({
                    url: window.location.href,
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            if (response.token) {
                                localStorage.setItem('jwt_token', response.token);
                            }
                            $('#success-message').text(response.message).show();
                            window.location.href = response.redirect;
                        } else {
                            $('#error-message').text(response.message).show();
                        }
                    },
                    error: function(xhr, status, error) {
                        var errorMessage = 'An error occurred. Please try again.';
                        try {
                            var response = JSON.parse(xhr.responseText);
                            if (response.message) {
                                errorMessage = response.message;
                            }
                        } catch (e) {
                            console.error('Error parsing response:', e);
                        }
                        $('#error-message').text(errorMessage).show();
                    },
                    complete: function() {
                        // Hide loading
                        $('.loading').hide();
                        $('button[type="submit"]').prop('disabled', false);
                    }
                });
            });
        });
    </script>
</body>
</html> 