<?php
require_once 'includes/init.php'; // Use the central logic file

// If a user is already logged in, redirect them away
if (isset($_SESSION['user_id'])) {
    header("Location: dashboard/");
    exit();
}

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $full_name = trim($_POST['full_name'] ?? '');
    $business_name = trim($_POST['business_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $password_confirm = $_POST['password_confirm'] ?? '';
    $role = $_POST['role'] ?? ''; // e.g., 'tour_partner', 'hotel_partner'

    // --- Validation ---
    if (empty($full_name) || empty($business_name) || empty($email) || empty($password) || empty($role)) {
        $errors[] = "All fields are required.";
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Please enter a valid email address.";
    }
    if (strlen($password) < 8) {
        $errors[] = "Password must be at least 8 characters long.";
    }
    if ($password !== $password_confirm) {
        $errors[] = "Passwords do not match.";
    }
    if (!in_array($role, ['tour_partner', 'hotel_partner'])) {
        $errors[] = "Invalid partner type selected.";
    }

    // Check if email already exists
    if (empty($errors)) {
        $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        if ($stmt->get_result()->num_rows > 0) {
            $errors[] = "An account with this email address already exists.";
        }
        $stmt->close();
    }

    // --- Create Partner Account ---
    if (empty($errors)) {
        $password_hash = password_hash($password, PASSWORD_DEFAULT);
        
        // Set partner-specific statuses
        $status = 'pending'; // Partner accounts should start as pending until approved
        $verification_status = 'pending_documents';

        $stmt_insert = $conn->prepare("INSERT INTO users (full_name, business_name, email, password, role, status, verification_status) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt_insert->bind_param("sssssss", $full_name, $business_name, $email, $password_hash, $role, $status, $verification_status);
        
        if ($stmt_insert->execute()) {
            // Automatically log the new partner in and send them to the document submission page
            $new_user_id = $conn->insert_id;
            session_regenerate_id(true);
            $_SESSION['user_id'] = $new_user_id;
            $_SESSION['user_role'] = $role;
            $_SESSION['user_name'] = $full_name;
            
            header("Location: partner/submit-documents.php");
            exit();
        } else {
            $errors[] = "There was an error creating your account. Please try again.";
        }
        $stmt_insert->close();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Become a Partner</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="container my-5">
        <div class="row justify-content-center">
            <div class="col-lg-7">
                <div class="text-center mb-4">
                    <h1 class="h2">Become a Partner</h1>
                    <p class="text-muted">Join our network of trusted travel providers.</p>
                </div>
                <div class="card shadow-sm border-0">
                    <div class="card-body p-4 p-md-5">
                        <?php if (!empty($errors)): ?>
                            <div class="alert alert-danger">
                                <?php foreach ($errors as $error): ?><p class="mb-0"><?php echo $error; ?></p><?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                        <form method="POST">
                            <div class="row">
                                <div class="col-md-6 mb-3"><label for="full_name" class="form-label">Your Full Name</label><input type="text" class="form-control" id="full_name" name="full_name" required></div>
                                <div class="col-md-6 mb-3"><label for="business_name" class="form-label">Business / Brand Name</label><input type="text" class="form-control" id="business_name" name="business_name" required></div>
                            </div>
                            <div class="mb-3"><label for="email" class="form-label">Business Email</label><input type="email" class="form-control" id="email" name="email" required></div>
                            <div class="mb-3"><label for="role" class="form-label">I am a...</label><select class="form-select" name="role" required><option value="" disabled selected>Select Partner Type</option><option value="tour_partner">Tour Operator</option><option value="hotel_partner">Hotel/Accommodation</option></select></div>
                            <div class="row">
                                <div class="col-md-6 mb-3"><label for="password" class="form-label">Password</label><input type="password" class="form-control" id="password" name="password" required></div>
                                <div class="col-md-6 mb-3"><label for="password_confirm" class="form-label">Confirm Password</label><input type="password" class="form-control" id="password_confirm" name="password_confirm" required></div>
                            </div>
                            <div class="d-grid mt-3">
                                <button type="submit" class="btn btn-primary btn-lg">Create Partner Account</button>
                            </div>
                        </form>
                    </div>
                </div>
                 <div class="text-center mt-4">
                    <p class="text-muted">Already a partner? <a href="login.php">Sign In</a></p>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
