<?php
session_start();
error_reporting(0);
include('includes/config.php');
include('includes/security.php');

if (isset($_POST['submit'])) {
    $username = db_prepare($con, $_POST['username']);
    $email = db_prepare($con, $_POST['email']);
    $password = md5($_POST['password']);
    $storeName = db_prepare($con, $_POST['store_name']);
    $storeSlug = strtolower(str_replace(' ', '-', $storeName)) . '-' . rand(1000, 9999);
    $businessEmail = db_prepare($con, $_POST['business_email']);
    $businessPhone = db_prepare($con, $_POST['business_phone']);
    $businessAddress = db_prepare($con, $_POST['business_address']);
    $fullName = db_prepare($con, $_POST['full_name']);
    $businessType = db_prepare($con, $_POST['business_type']);
    $businessNumber = db_prepare($con, $_POST['business_number']);

    // Check if email already exists
    $checkEmail = mysqli_query($con, "SELECT id FROM users WHERE email='$email'");

    if (mysqli_num_rows($checkEmail) > 0) {
        echo "<script>alert('Email already registered!');</script>";
    } else {
        // Create user account with 'vendor' role
        $insertUser = mysqli_query($con, "INSERT INTO users (username, email, password, role) 
                                          VALUES ('$username', '$email', '$password', 'vendor')");

        if ($insertUser) {
            $userId = mysqli_insert_id($con);

            // Create vendor profile (pending approval)
            $insertVendor = mysqli_query($con, "INSERT INTO vendors 
                (user_id, store_name, store_slug, business_type, business_number, business_email, business_phone, business_address, status) 
                VALUES ('$userId', '$storeName', '$storeSlug', '$businessType', '$businessNumber', '$businessEmail', '$businessPhone', '$businessAddress', 'pending')");

            // Create user details
            mysqli_query($con, "INSERT INTO user_details (user_id, name, contactno) 
                               VALUES ('$userId', '$fullName', '$businessPhone')");

            if ($insertVendor) {
                // Include Unified Activity Logger
                include_once('includes/activity_logger.php');
                log_activity("Vendor Application", "New application from: $storeName (Email: $email)", "vendor");

                echo "<script>alert('Vendor application submitted successfully! Please wait for admin approval.');</script>";
                echo "<script>window.location.href='vendor-login.php'</script>";
            }
        } else {
            echo "<script>alert('Registration failed. Please try again.');</script>";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Vendor Registration - Awesome Mall</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="__admin__/css/admin-professional.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"></script>
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }

        .vendor-register-card {
            max-width: 800px;
            margin: 40px auto;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="vendor-register-card">
            <div class="card shadow-lg">
                <div class="card-header bg-primary text-white text-center py-4">
                    <h2><i class="fas fa-store me-2"></i>Become a Vendor</h2>
                    <p class="mb-0">Start selling on Awesome Mall</p>
                </div>
                <div class="card-body p-4">
                    <form method="post">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            <strong>Application Process:</strong> Your application will be reviewed by our team within
                            24-48 hours.
                        </div>

                        <h5 class="mb-3"><i class="fas fa-user me-2"></i>Personal Information</h5>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Full Name <span class="text-danger">*</span></label>
                                <input type="text" name="full_name" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Username <span class="text-danger">*</span></label>
                                <input type="text" name="username" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Email <span class="text-danger">*</span></label>
                                <input type="email" name="email" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Password <span class="text-danger">*</span></label>
                                <input type="password" name="password" class="form-control" minlength="6" required>
                            </div>
                        </div>

                        <hr class="my-4">

                        <h5 class="mb-3"><i class="fas fa-store me-2"></i>Store Information</h5>
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Business Type <span class="text-danger">*</span></label>
                                <div class="d-flex gap-4">
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="business_type"
                                            id="typeIndividual" value="Individual" onchange="toggleBusinessInput()"
                                            checked>
                                        <label class="form-check-label" for="typeIndividual">
                                            Individual Seller
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="business_type"
                                            id="typeBusiness" value="Registered Business"
                                            onchange="toggleBusinessInput()">
                                        <label class="form-check-label" for="typeBusiness">
                                            Registered Business
                                        </label>
                                    </div>
                                </div>
                            </div>

                            <!-- Business Number Input (Hidden by default) -->
                            <div class="col-md-12 mb-3" id="businessNumberGroup" style="display: none;">
                                <label class="form-label">Business Registration Number <span
                                        class="text-danger">*</span></label>
                                <input type="text" name="business_number" id="businessNumberInput" class="form-control"
                                    placeholder="Enter your business registration number">
                            </div>

                            <div class="col-md-12 mb-3">
                                <label class="form-label">Store Name <span class="text-danger">*</span></label>
                                <input type="text" name="store_name" class="form-control"
                                    placeholder="e.g., John's Electronics" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Business Email <span class="text-danger">*</span></label>
                                <input type="email" name="business_email" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Business Phone <span class="text-danger">*</span></label>
                                <input type="text" name="business_phone" class="form-control"
                                    placeholder="+233 123 456 789" required>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Business Address <span class="text-danger">*</span></label>
                                <textarea name="business_address" class="form-control" rows="2" required></textarea>
                            </div>
                        </div>

                        <div class="alert alert-warning">
                            <strong><i class="fas fa-percentage me-2"></i>Commission:</strong>
                            We charge a 10% commission on each sale. You keep 90% of the sale price.
                        </div>

                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="terms" required>
                            <label class="form-check-label" for="terms">
                                I agree to the <a href="#" target="_blank">Terms of Service</a> and
                                <a href="#" target="_blank">Vendor Agreement</a>
                            </label>
                        </div>

                        <button type="submit" name="submit" class="btn btn-primary btn-lg w-100">
                            <i class="fas fa-check me-2"></i>Submit Application
                        </button>
                    </form>

                    <div class="text-center mt-3">
                        <p class="mb-0">Already a vendor? <a href="vendor-login.php">Login here</a></p>
                        <p class="mt-2"><a href="index.php">← Back to Store</a></p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function toggleBusinessInput() {
            var typeBusiness = document.getElementById('typeBusiness');
            var group = document.getElementById('businessNumberGroup');
            var input = document.getElementById('businessNumberInput');

            if (typeBusiness.checked) {
                group.style.display = 'block';
                input.required = true;
            } else {
                group.style.display = 'none';
                input.required = false;
                input.value = ''; // Clear value
            }
        }
    </script>
</body>

</html>