<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/Language.php';

if (!isLoggedIn()) { redirect('login.php'); }

$lang = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id = $_SESSION['user_id'];

$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($user_data) ? $user_data[0] : null;

if (!$user) {
    session_destroy();
    redirect('login.php');
}

// Ensure the user is subscribed
if (!isset($user['is_subscribed']) || $user['is_subscribed'] != 1) {
    redirect('subscription.php');
}

$success_msg = '';
$error_msg = '';

// Check if an existing request is present
$existing_request = $db->select("SELECT * FROM seller_upgrade_requests WHERE user_id = ? ORDER BY created_at DESC LIMIT 1", [$user_id]);
$request_status = !empty($existing_request) ? $existing_request[0]['status'] : null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_upgrade'])) {
    if ($request_status !== 'Pending' && $request_status !== 'Approved') {
        $business_name = sanitize($_POST['business_name']);
        $business_phone = sanitize($_POST['business_phone']);
        $business_description = sanitize($_POST['business_description']);
        $business_address = sanitize($_POST['business_address']);
        
        if (empty($business_name) || empty($business_phone)) {
            $error_msg = "Business Name and Phone are required.";
        } else {
            $insert = $db->insert(
                "INSERT INTO seller_upgrade_requests (user_id, business_name, business_phone, business_description, business_address) VALUES (?, ?, ?, ?, ?)",
                [$user_id, $business_name, $business_phone, $business_description, $business_address]
            );
            if ($insert) {
                $success_msg = "Your request has been submitted successfully and is pending review.";
                $request_status = 'Pending';
            } else {
                $error_msg = "Failed to submit request. Please try again.";
            }
        }
    }
}

$wallet_balance = isset($user['wallet_balance']) ? $user['wallet_balance'] : '0.00';
$company_logo = getSetting('company_logo', 'assets/images/logo.png');
$company_logo = (strpos($company_logo, 'http') === 0) ? $company_logo : ltrim($company_logo, '/');
$company_name = getSetting('company_name', 'WBMCZ');
$profile_image_url = !empty($user['profile_pic']) ? 'uploads/profiles/' . $user['profile_pic'] : null;

$dashboard_link = 'dashboard.php';
if ($user['user_type'] == 'seller') { $dashboard_link = 'seller/index.php'; } 
elseif ($user['user_type'] == 'admin') { $dashboard_link = 'admin/index.php'; }
$all_categories = $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upgrade to Seller - <?php echo htmlspecialchars($company_name); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style> body { font-family: 'Inter', sans-serif; scroll-behavior: smooth;} .hide-scrollbar::-webkit-scrollbar { display: none; } </style>
</head>
<body class="bg-gray-50 text-gray-800">
    <!-- Header -->
    <header class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-40">
        <div class="flex items-center justify-between px-4 sm:px-6 lg:px-8 h-16">
            <div class="flex items-center space-x-4">
                <a href="<?php echo $dashboard_link; ?>" class="text-indigo-600 hover:text-indigo-800 transition-colors">
                    <i class="fas fa-arrow-left text-xl"></i>
                </a>
                <h1 class="text-xl font-bold text-gray-900">Upgrade to Seller</h1>
            </div>
            
            <div class="flex items-center space-x-4">
                <div class="hidden sm:flex items-center space-x-2 bg-indigo-50 px-3 py-1.5 rounded-full border border-indigo-100">
                    <i class="fas fa-wallet text-indigo-600"></i>
                    <span class="text-sm font-bold text-indigo-900">₹<?php echo number_format($wallet_balance, 2); ?></span>
                </div>
                
                <a href="dashboard.php" class="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center text-gray-600 hover:bg-indigo-100 hover:text-indigo-600 transition-colors">
                    <i class="fas fa-home"></i>
                </a>
            </div>
        </div>
    </header>

    <main class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        
        <?php if ($success_msg): ?>
            <div class="mb-6 p-4 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-800 flex items-start shadow-sm">
                <i class="fas fa-check-circle mt-1 mr-3 text-emerald-500"></i>
                <div class="font-medium"><?php echo $success_msg; ?></div>
            </div>
        <?php endif; ?>

        <?php if ($error_msg): ?>
            <div class="mb-6 p-4 rounded-xl bg-red-50 border border-red-200 text-red-800 flex items-start shadow-sm">
                <i class="fas fa-exclamation-circle mt-1 mr-3 text-red-500"></i>
                <div class="font-medium"><?php echo $error_msg; ?></div>
            </div>
        <?php endif; ?>

        <div class="bg-white rounded-2xl shadow-xl border border-gray-100 overflow-hidden">
            <div class="bg-gradient-to-r from-amber-500 to-amber-600 p-8 text-center text-white">
                <div class="w-20 h-20 bg-white/20 rounded-full flex items-center justify-center mx-auto mb-4 backdrop-blur-sm border-2 border-white/30">
                    <i class="fas fa-rocket text-4xl text-white drop-shadow-md"></i>
                </div>
                <h2 class="text-3xl font-bold mb-2 text-white">Become a Seller</h2>
                <p class="text-amber-100 max-w-xl mx-auto text-lg">Unlock premium features, offer your own services, and earn more by upgrading your account to a Seller profile.</p>
            </div>

            <div class="p-8">
                <?php if ($request_status === 'Pending'): ?>
                    <div class="text-center py-12">
                        <div class="w-24 h-24 bg-amber-50 rounded-full flex items-center justify-center mx-auto mb-6 text-amber-500 animate-pulse">
                            <i class="fas fa-clock text-5xl"></i>
                        </div>
                        <h3 class="text-2xl font-bold text-gray-900 mb-2">Request Under Review</h3>
                        <p class="text-gray-500 max-w-md mx-auto">Your request to upgrade to a seller account is currently being reviewed by our administrators. We will notify you once it's approved.</p>
                    </div>
                <?php elseif ($request_status === 'Approved'): ?>
                    <div class="text-center py-12">
                        <div class="w-24 h-24 bg-emerald-50 rounded-full flex items-center justify-center mx-auto mb-6 text-emerald-500">
                            <i class="fas fa-check-circle text-5xl"></i>
                        </div>
                        <h3 class="text-2xl font-bold text-gray-900 mb-2">You are already a Seller!</h3>
                        <p class="text-gray-500 max-w-md mx-auto mb-6">Your account has already been upgraded to a seller account.</p>
                        <a href="seller/index.php" class="inline-flex items-center justify-center px-6 py-3 border border-transparent text-base font-medium rounded-xl text-white bg-indigo-600 hover:bg-indigo-700 shadow-lg hover:shadow-xl transition-all">
                            Go to Seller Dashboard
                        </a>
                    </div>
                <?php else: ?>
                    <?php if ($request_status === 'Rejected'): ?>
                        <div class="mb-8 p-5 rounded-xl bg-red-50 border border-red-200 text-red-800 flex items-start">
                            <i class="fas fa-times-circle mt-1 mr-3 text-red-500 text-xl"></i>
                            <div>
                                <h4 class="font-bold text-lg mb-1">Previous Request Rejected</h4>
                                <p>Your previous upgrade request was not approved. You can submit a new request below with updated information.</p>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <form action="" method="POST" class="space-y-6">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label class="block text-sm font-semibold text-gray-700 mb-2">Business Name <span class="text-red-500">*</span></label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <i class="fas fa-store text-gray-400"></i>
                                    </div>
                                    <input type="text" name="business_name" required class="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-xl focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm bg-gray-50 focus:bg-white transition-colors" placeholder="Enter your business name">
                                </div>
                            </div>

                            <div>
                                <label class="block text-sm font-semibold text-gray-700 mb-2">Business Phone Number <span class="text-red-500">*</span></label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <i class="fas fa-phone text-gray-400"></i>
                                    </div>
                                    <input type="text" name="business_phone" required class="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-xl focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm bg-gray-50 focus:bg-white transition-colors" placeholder="Contact number">
                                </div>
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Business Description</label>
                            <textarea name="business_description" rows="3" class="block w-full p-4 border border-gray-300 rounded-xl focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm bg-gray-50 focus:bg-white transition-colors" placeholder="Briefly describe what your business does..."></textarea>
                        </div>

                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Business Address</label>
                            <div class="relative">
                                <div class="absolute top-4 left-3 flex items-center pointer-events-none">
                                    <i class="fas fa-map-marker-alt text-gray-400"></i>
                                </div>
                                <textarea name="business_address" rows="3" class="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-xl focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm bg-gray-50 focus:bg-white transition-colors" placeholder="Full business address"></textarea>
                            </div>
                        </div>

                        <div class="pt-4 border-t border-gray-100">
                            <button type="submit" name="submit_upgrade" class="w-full flex justify-center py-4 px-4 border border-transparent rounded-xl shadow-lg text-lg font-bold text-white bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-600 hover:to-amber-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-amber-500 transition-all transform hover:-translate-y-0.5">
                                <i class="fas fa-paper-plane mr-2 mt-1"></i> Submit Upgrade Request
                            </button>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </main>

</body>
</html>
