<?php
require_once 'includes/config.php';
session_start();

// Cek role supervisor
if ($_SESSION['role'] !== 'supervisor') {
    $_SESSION['error'] = "Unauthorized access!";
    header("Location: users.php");
    exit();
}

// Cek request POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verifikasi CSRF token
    if (!verifyCSRFToken($_POST['csrf_token'])) {
        $_SESSION['error'] = "Invalid security token!";
        header("Location: users.php");
        exit();
    }

    try {
        // Validasi input
        $username = sanitize_input($_POST['username']);
        $nama_lengkap = sanitize_input($_POST['nama_lengkap']);
        $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
        $password = $_POST['password'];
        $password_confirmation = $_POST['password_confirmation'];

        // Validasi password
        if (strlen($password) < 6) {
            throw new Exception("Password must be at least 6 characters!");
        }
        if ($password !== $password_confirmation) {
            throw new Exception("Password confirmation does not match!");
        }

        $db_auth->exec("USE " . DB_AUTH_NAME);

        // Cek username unik
        $stmt = $db_auth->prepare("SELECT id FROM marketing WHERE username = ?");
        $stmt->execute([$username]);
        if ($stmt->fetch()) {
            throw new Exception("Username is already taken!");
        }

        // Cek email unik
        $stmt = $db_auth->prepare("SELECT id FROM marketing WHERE email = ?");
        $stmt->execute([$email]);
        if ($stmt->fetch()) {
            throw new Exception("Email is already taken!");
        }

        // Insert data marketing baru
        $hash = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $db_auth->prepare("
            INSERT INTO marketing (username, password, nama_lengkap, email, supervisor_id, created_by) 
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        
        $stmt->execute([
            $username,
            $hash,
            $nama_lengkap,
            $email,
            $_SESSION['user_id'], // supervisor_id
            $_SESSION['user_id']  // created_by
        ]);

        $_SESSION['success'] = "Marketing added successfully!";
        
    } catch (Exception $e) {
        $_SESSION['error'] = $e->getMessage();
    }
}

header("Location: users.php");
exit();
