<?php
// pro_agent_reg.php
session_start();
require_once "config.php"; // DB connection

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: agent_reg.php");
    exit;
}

$errors = [];

// Collect and sanitize inputs
$first_name = trim($_POST['first_name'] ?? '');
$last_name = trim($_POST['last_name'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$address = trim($_POST['address'] ?? '');
$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';
$confirm_password = $_POST['confirm_password'] ?? '';
$plan = $_POST['plan'] ?? 'basic';

// Defaults
$role = 'basic';
$subscription_plan = strtolower($plan);
$balance = 0;
$currency = 'NGN';
$imagePath = null;

// Validate
if ($first_name === '' || $last_name === '' || $email === '' || $phone === '' || $username === '' || $password === '') {
    $errors[] = "All required fields must be filled.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Invalid email format.";
}
if ($password !== $confirm_password) {
    $errors[] = "Passwords do not match.";
}
if (strlen($password) < 6) {
    $errors[] = "Password must be at least 6 characters.";
}

// Check username/email uniqueness
$stmt = $conn->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
$stmt->bind_param("ss", $username, $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
    $errors[] = "Username or email already exists.";
}
$stmt->close();

// Handle image upload
if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = __DIR__ . "/uploads/";
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    $fileTmp = $_FILES['image']['tmp_name'];
    $fileName = uniqid() . "_" . basename($_FILES['image']['name']);
    $targetPath = $uploadDir . $fileName;

    $allowedTypes = ['image/jpeg', 'image/png'];
    $fileType = mime_content_type($fileTmp);

    if (!in_array($fileType, $allowedTypes)) {
        $errors[] = "Only JPG and PNG images are allowed.";
    } elseif ($_FILES['image']['size'] > 2 * 1024 * 1024) {
        $errors[] = "Image must not exceed 2MB.";
    } else {
        if (move_uploaded_file($fileTmp, $targetPath)) {
            $imagePath = "uploads/" . $fileName;
        } else {
            $errors[] = "Failed to upload image.";
        }
    }
}

// If errors, show them
if (!empty($errors)) {
    $_SESSION['errors'] = $errors;
    header("Location: agent_reg.php?plan=" . urlencode($plan));
    exit;
}

// Hash password
$hashedPassword = password_hash($password, PASSWORD_BCRYPT);

// Insert user
$stmt = $conn->prepare("INSERT INTO users 
    (first_name, last_name, email, phone, address, image, username, password, role, subscription_plan, balance, currency) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param(
    "ssssssssssis",
    $first_name,
    $last_name,
    $email,
    $phone,
    $address,
    $imagePath,
    $username,
    $hashedPassword,
    $role,
    $subscription_plan,
    $balance,
    $currency
);

if ($stmt->execute()) {
    // Registration successful
    $_SESSION['success'] = "Registration successful. Please log in.";
    header("Location: login.php");
    exit;
} else {
    $_SESSION['errors'] = ["Failed to register. Please try again."];
    header("Location: agent_reg.php?plan=" . urlencode($plan));
    exit;
}
?>
