<?php
/**
 * API untuk mengelola data user
 * Endpoint: /api/users.php
 */

require_once '../config/database.php';

// Set CORS headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    jsonResponse(['error' => 'Database connection failed'], 500);
}

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

try {
    switch ($method) {
        case 'GET':
            handleGetUsers($db);
            break;
        case 'POST':
            handleCreateUser($db, $input);
            break;
        case 'PUT':
            handleUpdateUser($db, $input);
            break;
        case 'DELETE':
            handleDeleteUser($db, $input);
            break;
        default:
            jsonResponse(['error' => 'Method not allowed'], 405);
    }
} catch (Exception $e) {
    jsonResponse(['error' => $e->getMessage()], 500);
}

/**
 * GET - Ambil semua data user
 */
function handleGetUsers($db) {
    $query = "
        SELECT 
            u.id,
            u.username,
            u.full_name,
            u.is_admin,
            u.is_active,
            u.created_at,
            u.updated_at,
            p.id as position_id,
            p.name as position_name
        FROM users u
        LEFT JOIN positions p ON u.position_id = p.id
        ORDER BY u.id ASC
    ";
    
    $stmt = $db->prepare($query);
    $stmt->execute();
    
    $users = $stmt->fetchAll();
    
    // Hapus password dari response
    foreach ($users as &$user) {
        unset($user['password']);
    }
    
    jsonResponse([
        'success' => true,
        'data' => $users
    ]);
}

/**
 * POST - Tambah user baru
 */
function handleCreateUser($db, $input) {
    // Validasi input
    $errors = validateInput($input, ['username', 'password', 'full_name', 'position_id']);
    if (!empty($errors)) {
        jsonResponse(['error' => 'Validation failed', 'details' => $errors], 400);
    }
    
    $username = sanitizeInput($input['username']);
    $password = $input['password'];
    $full_name = sanitizeInput($input['full_name']);
    $position_id = (int)$input['position_id'];
    $is_admin = isset($input['is_admin']) ? (bool)$input['is_admin'] : false;
    $is_active = isset($input['is_active']) ? (bool)$input['is_active'] : true;
    
    // Cek apakah username sudah ada
    $checkQuery = "SELECT id FROM users WHERE username = :username";
    $checkStmt = $db->prepare($checkQuery);
    $checkStmt->bindParam(':username', $username);
    $checkStmt->execute();
    
    if ($checkStmt->fetch()) {
        jsonResponse(['error' => 'Username already exists'], 400);
    }
    
    // Cek apakah position_id valid
    $positionQuery = "SELECT id FROM positions WHERE id = :position_id";
    $positionStmt = $db->prepare($positionQuery);
    $positionStmt->bindParam(':position_id', $position_id);
    $positionStmt->execute();
    
    if (!$positionStmt->fetch()) {
        jsonResponse(['error' => 'Invalid position_id'], 400);
    }
    
    // Hash password
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
    
    // Insert user baru
    $query = "
        INSERT INTO users (username, password, full_name, position_id, is_admin, is_active)
        VALUES (:username, :password, :full_name, :position_id, :is_admin, :is_active)
    ";
    
    $stmt = $db->prepare($query);
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':password', $hashedPassword);
    $stmt->bindParam(':full_name', $full_name);
    $stmt->bindParam(':position_id', $position_id);
    $stmt->bindParam(':is_admin', $is_admin, PDO::PARAM_BOOL);
    $stmt->bindParam(':is_active', $is_active, PDO::PARAM_BOOL);
    
    if ($stmt->execute()) {
        $userId = $db->lastInsertId();
        
        // Ambil data user yang baru dibuat
        $getUserQuery = "
            SELECT 
                u.id,
                u.username,
                u.full_name,
                u.is_admin,
                u.is_active,
                u.created_at,
                u.updated_at,
                p.id as position_id,
                p.name as position_name
            FROM users u
            LEFT JOIN positions p ON u.position_id = p.id
            WHERE u.id = :user_id
        ";
        
        $getUserStmt = $db->prepare($getUserQuery);
        $getUserStmt->bindParam(':user_id', $userId);
        $getUserStmt->execute();
        $newUser = $getUserStmt->fetch();
        
        jsonResponse([
            'success' => true,
            'message' => 'User created successfully',
            'data' => $newUser
        ]);
    } else {
        jsonResponse(['error' => 'Failed to create user'], 500);
    }
}

/**
 * PUT - Update user
 */
function handleUpdateUser($db, $input) {
    // Validasi input
    $errors = validateInput($input, ['id']);
    if (!empty($errors)) {
        jsonResponse(['error' => 'Validation failed', 'details' => $errors], 400);
    }
    
    $user_id = (int)$input['id'];
    $username = isset($input['username']) ? sanitizeInput($input['username']) : null;
    $password = isset($input['password']) ? $input['password'] : null;
    $full_name = isset($input['full_name']) ? sanitizeInput($input['full_name']) : null;
    $position_id = isset($input['position_id']) ? (int)$input['position_id'] : null;
    $is_admin = isset($input['is_admin']) ? (bool)$input['is_admin'] : null;
    $is_active = isset($input['is_active']) ? (bool)$input['is_active'] : null;
    
    // Cek apakah user ada
    $checkQuery = "SELECT id FROM users WHERE id = :user_id";
    $checkStmt = $db->prepare($checkQuery);
    $checkStmt->bindParam(':user_id', $user_id);
    $checkStmt->execute();
    
    if (!$checkStmt->fetch()) {
        jsonResponse(['error' => 'User not found'], 404);
    }
    
    // Cek username unik jika diupdate
    if ($username) {
        $usernameQuery = "SELECT id FROM users WHERE username = :username AND id != :user_id";
        $usernameStmt = $db->prepare($usernameQuery);
        $usernameStmt->bindParam(':username', $username);
        $usernameStmt->bindParam(':user_id', $user_id);
        $usernameStmt->execute();
        
        if ($usernameStmt->fetch()) {
            jsonResponse(['error' => 'Username already exists'], 400);
        }
    }
    
    // Cek position_id valid jika diupdate
    if ($position_id) {
        $positionQuery = "SELECT id FROM positions WHERE id = :position_id";
        $positionStmt = $db->prepare($positionQuery);
        $positionStmt->bindParam(':position_id', $position_id);
        $positionStmt->execute();
        
        if (!$positionStmt->fetch()) {
            jsonResponse(['error' => 'Invalid position_id'], 400);
        }
    }
    
    // Build update query dinamis
    $updateFields = [];
    $params = [':user_id' => $user_id];
    
    if ($username) {
        $updateFields[] = "username = :username";
        $params[':username'] = $username;
    }
    
    if ($password) {
        $updateFields[] = "password = :password";
        $params[':password'] = password_hash($password, PASSWORD_DEFAULT);
    }
    
    if ($full_name) {
        $updateFields[] = "full_name = :full_name";
        $params[':full_name'] = $full_name;
    }
    
    if ($position_id !== null) {
        $updateFields[] = "position_id = :position_id";
        $params[':position_id'] = $position_id;
    }
    
    if ($is_admin !== null) {
        $updateFields[] = "is_admin = :is_admin";
        $params[':is_admin'] = $is_admin;
    }
    
    if ($is_active !== null) {
        $updateFields[] = "is_active = :is_active";
        $params[':is_active'] = $is_active;
    }
    
    if (empty($updateFields)) {
        jsonResponse(['error' => 'No fields to update'], 400);
    }
    
    $updateFields[] = "updated_at = CURRENT_TIMESTAMP";
    
    $query = "UPDATE users SET " . implode(', ', $updateFields) . " WHERE id = :user_id";
    
    $stmt = $db->prepare($query);
    
    foreach ($params as $key => $value) {
        if ($key === ':is_admin' || $key === ':is_active') {
            $stmt->bindValue($key, $value, PDO::PARAM_BOOL);
        } else {
            $stmt->bindValue($key, $value);
        }
    }
    
    if ($stmt->execute()) {
        // Ambil data user yang sudah diupdate
        $getUserQuery = "
            SELECT 
                u.id,
                u.username,
                u.full_name,
                u.is_admin,
                u.is_active,
                u.created_at,
                u.updated_at,
                p.id as position_id,
                p.name as position_name
            FROM users u
            LEFT JOIN positions p ON u.position_id = p.id
            WHERE u.id = :user_id
        ";
        
        $getUserStmt = $db->prepare($getUserQuery);
        $getUserStmt->bindParam(':user_id', $user_id);
        $getUserStmt->execute();
        $updatedUser = $getUserStmt->fetch();
        
        jsonResponse([
            'success' => true,
            'message' => 'User updated successfully',
            'data' => $updatedUser
        ]);
    } else {
        jsonResponse(['error' => 'Failed to update user'], 500);
    }
}

/**
 * DELETE - Hapus user
 */
function handleDeleteUser($db, $input) {
    // Validasi input
    $errors = validateInput($input, ['id']);
    if (!empty($errors)) {
        jsonResponse(['error' => 'Validation failed', 'details' => $errors], 400);
    }
    
    $user_id = (int)$input['id'];
    
    // Cek apakah user ada
    $checkQuery = "SELECT id, is_admin FROM users WHERE id = :user_id";
    $checkStmt = $db->prepare($checkQuery);
    $checkStmt->bindParam(':user_id', $user_id);
    $checkStmt->execute();
    $user = $checkStmt->fetch();
    
    if (!$user) {
        jsonResponse(['error' => 'User not found'], 404);
    }
    
    // Cek apakah user adalah admin (jangan hapus admin)
    if ($user['is_admin']) {
        jsonResponse(['error' => 'Cannot delete admin user'], 400);
    }
    
    // Hapus user
    $query = "DELETE FROM users WHERE id = :user_id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':user_id', $user_id);
    
    if ($stmt->execute()) {
        jsonResponse([
            'success' => true,
            'message' => 'User deleted successfully'
        ]);
    } else {
        jsonResponse(['error' => 'Failed to delete user'], 500);
    }
}
?>
