<?php
require_once '../connection.php';

// Check if user is admin
if (!isAdmin()) {
    header('Location: login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Get form data
    $username = trim($_POST['username']);
    $password = md5(trim($_POST['password'])); // Hash password with MD5 (you can use password_hash() for better security)
    $full_name = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $plan_id = $_POST['plan_id'];
    
    // Generate PPPoE credentials (can be same as username or custom)
    $pppoe_username = $username . '_pppoe';
    $pppoe_password = generateRandomPassword(10);
    
    // Validate inputs
    $errors = [];
    
    if (empty($username)) {
        $errors[] = "Username is required";
    }
    
    if (empty($full_name)) {
        $errors[] = "Full name is required";
    }
    
    // Check if username already exists
    $stmt = $pdo->prepare("SELECT id FROM clients WHERE username = ?");
    $stmt->execute([$username]);
    if ($stmt->rowCount() > 0) {
        $errors[] = "Username already exists";
    }
    
    // Check if PPPoE username already exists
    $stmt = $pdo->prepare("SELECT id FROM clients WHERE pppoe_username = ?");
    $stmt->execute([$pppoe_username]);
    if ($stmt->rowCount() > 0) {
        $pppoe_username = $username . '_' . time() . '_pppoe';
    }
    
    // Get plan details
    $stmt = $pdo->prepare("SELECT * FROM plans WHERE id = ? AND is_active = 1");
    $stmt->execute([$plan_id]);
    $plan = $stmt->fetch();
    
    if (!$plan) {
        $errors[] = "Invalid plan selected";
    }
    
    // If no errors, create client
    if (empty($errors)) {
        try {
            $pdo->beginTransaction();
            
            // Insert client
            $stmt = $pdo->prepare("
                INSERT INTO clients (username, password, full_name, email, phone, pppoe_username, pppoe_password, wallet_balance) 
                VALUES (?, ?, ?, ?, ?, ?, ?, 0.00)
            ");
            $stmt->execute([$username, $password, $full_name, $email, $phone, $pppoe_username, $pppoe_password]);
            $client_id = $pdo->lastInsertId();
            
            // Calculate subscription dates
            $start_date = date('Y-m-d');
            $end_date = date('Y-m-d', strtotime("+{$plan['duration_days']} days"));
            
            // Create subscription
            $stmt = $pdo->prepare("
                INSERT INTO subscriptions (client_id, plan_id, start_date, end_date, is_active) 
                VALUES (?, ?, ?, ?, 1)
            ");
            $stmt->execute([$client_id, $plan_id, $start_date, $end_date]);
            
            // Add to MikroTik (optional - uncomment when MikroTik API is configured)
            $profile = "plan_" . $plan['speed_mbps'] . "mbps";
            // addMikroTikPPPoe($pppoe_username, $pppoe_password, $profile);
            
            $pdo->commit();
            
            // Set success message
            $_SESSION['success'] = "Client added successfully!<br>
                                    PPPoE Username: {$pppoe_username}<br>
                                    PPPoE Password: {$pppoe_password}<br>
                                    <strong>Please save these credentials for the client!</strong>";
            
            header('Location: dashboard.php');
            exit();
            
        } catch (Exception $e) {
            $pdo->rollBack();
            $errors[] = "Database error: " . $e->getMessage();
        }
    }
    
    // If there are errors, store them in session and redirect back
    if (!empty($errors)) {
        $_SESSION['errors'] = $errors;
        header('Location: admin/dashboard.php#clients');
        exit();
    }
} else {
    // Not a POST request
    header('Location: admin/dashboard.php');
    exit();
}

// Function to generate random password
function generateRandomPassword($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%';
    $password = '';
    for ($i = 0; $i < $length; $i++) {
        $password .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $password;
}
?>